From 7be3f210c19cb406e0fe4c49e024afb45b13ab44 Mon Sep 17 00:00:00 2001 From: Matthew McEachen Date: Wed, 20 Mar 2024 22:14:50 -0700 Subject: [PATCH] v2024.3.3-prealpha --- CHANGELOG.md | 26 ++++++--- Dockerfile | 4 +- VERSION.json | 12 ++-- bin/info.js | 2 +- bin/list.js | 2 +- bin/logcat.js | 2 +- bin/logtail.js | 2 +- bin/main.js | 2 +- bin/photostructure.js | 2 +- bin/sync.js | 2 +- bin/web.js | 2 +- bin/worker.js | 2 +- defaults.env | 2 +- package.json | 10 ++-- photostructure | 2 +- public/3rd-party-licenses.txt.gz | Bin 48190 -> 48190 bytes public/app/about.css.gz | Bin 3832 -> 3832 bytes public/app/about.css.map.gz | Bin 1259 -> 1259 bytes public/app/about.js.gz | Bin 4576 -> 4576 bytes public/app/app.css.gz | Bin 9778 -> 9778 bytes public/app/app.css.map.gz | Bin 3799 -> 3799 bytes public/app/app.js.gz | Bin 112731 -> 112734 bytes public/app/health.css.gz | Bin 5446 -> 5446 bytes public/app/health.css.map.gz | Bin 1829 -> 1829 bytes public/app/health.js.gz | Bin 70458 -> 70458 bytes public/app/install.js.gz | Bin 5944 -> 5944 bytes public/app/settings.css.gz | Bin 6117 -> 6117 bytes public/app/settings.css.map.gz | Bin 2114 -> 2114 bytes public/app/settings.js.gz | Bin 11294 -> 11294 bytes public/app/splash.css.gz | Bin 1408 -> 1408 bytes public/app/splash.css.map.gz | Bin 558 -> 558 bytes public/app/splash.js.gz | Bin 5111 -> 5111 bytes tools/linux-x64/sqlite3 | Bin 1750192 -> 1750192 bytes tools/linux-x64/sqlite3-README.md | 17 ++++-- tools/mac-arm64/sqlite3-README.md | 9 +-- tools/win-x64/sqlite3-README.md | 4 +- tools/win-x64/sqlite3.exe | Bin 3730432 -> 3733504 bytes yarn.lock | 89 ++++++++++++++---------------- 38 files changed, 102 insertions(+), 91 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2ff81b..ac974f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,30 +24,38 @@ This page contains a detailed list of changes made in every build of PhotoStruct - Library upgrades to new versions of PhotoStructure are automatic, but older versions of PhotoStructure cannot open libraries from newer versions of PhotoStructure. - - - - + - + + + ## v2024.3.3-prealpha -**to be released** +**released 2024-03-20** + +- 🐛 Replaced the ExifTool health check timeout with `statTimeoutMs` (which defaults to 30s -- prior builds timed out after 7 seconds) + +- 🐛 Node.js v21 support: fixed `DeprecationWarning: The ``punycode`` module is deprecated.` + +- 📦 Update Docker image to Node.js 20.11 + +- 📦 Update SQLite tooling to 3.45 -- ✨ Add "county" support for the geotagger (to help discriminate between [same-named cities](https://discord.com/channels/818905168107012097/1218392684302172170)). This version will automatically schedule a "retag library" job, which is much faster than a "library rebuild," as we skip asset re-aggregation, transcoding, and preview generation, and only re-tag every asset. + + ## v2024.3.2-beta -**`-prealpha` released 2024-03-14 🥧 and promoted to `-beta` on 2024-03-19** +**`-prealpha` released 2024-03-14 🥧 and promoted to `-beta` on 2024-03-20** - 🐛 The warning message `Error: env(): failed to read .env file` caused [sync to fail to run](https://discord.com/channels/818905168107012097/818907922767544340/1217724819483791421]). This warning is now only emitted by the main service, and only if the file exists. @@ -109,7 +117,7 @@ As an example, a build might be `v2024.1.7-beta`. If it proves sufficiently stab PhotoStructure now adds `Where/Country/Region/City` tags for those photos and videos with Latitude and Longitude metadata. -Note that this feature is uses an embedded geo database, so no network access is required. This initial implementation only inclues cities with a population of 1000 or greater. See the new `tagGeo` and `tagGeoTemplate` [settings](/go/settings) for more details. +Note that this feature uses an embedded geo database, so no network access is required. This initial implementation only includes cities with a population of 1000 or greater. See the new `tagGeo` and `tagGeoTemplate` [settings](/go/settings) for more details. ### 🔃 Sync improvements diff --git a/Dockerfile b/Dockerfile index 892fa98..ecb1a63 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # # https://github.com/photostructure/base-tools/pkgs/container/base-tools-debian -FROM photostructure/base-tools-debian:sha-1605d9d as builder +FROM photostructure/base-tools-debian:sha-2f5c9bb as builder # https://docs.docker.com/develop/develop-images/multistage-build/ @@ -21,7 +21,7 @@ RUN yarn install --frozen-lockfile --production --no-cache # This must match the base image from # https://github.com/photostructure/base-tools-debian/blob/main/Dockerfile -FROM node:20.10.0-bookworm-slim +FROM node:20.11-bookworm-slim # ffmpeg is used for video frame extraction and transcoding # libheif-examples provides "heif-convert" diff --git a/VERSION.json b/VERSION.json index 0f366df..a232781 100644 --- a/VERSION.json +++ b/VERSION.json @@ -1,12 +1,12 @@ { - "version": "2024.3.2-beta", + "version": "2024.3.3-prealpha", "versionMajor": 2024, "versionMinor": 3, - "versionPatch": 2, + "versionPatch": 3, "versionPrerelease": [ - "beta" + "prealpha" ], - "release": "2024.3.2-beta+20240320133326", - "gitSha": "f510a99f0cb85a261405b7831fbbc749dc164e15", - "gitDate": "2024-03-20T20:33:26.000Z" + "release": "2024.3.3-prealpha+20240320221341", + "gitSha": "84e58c788ce0a6315415da9cb73a807d535433f6", + "gitDate": "2024-03-21T05:13:41.000Z" } diff --git a/bin/info.js b/bin/info.js index e866b0e..ef5d455 100755 --- a/bin/info.js +++ b/bin/info.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463:(e,t,i)=>{const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,s),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const s=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*s);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*s);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(s*t);case"day":case"days":case"d":return Math.round(864e5*s);case"week":case"weeks":case"w":return Math.round(6048e5*s);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*s)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227:(e,t,i)=>{const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120:(e,t,i)=>{const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827:(e,t,i)=>{const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015:(e,t,i)=>{const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return _(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function M(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function D(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=M,t.least=function(e){return M(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=k,t.collectBatched=function(e,t,i){const s=[];for(const n of k((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of k((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await D(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),b=i(99331),S=i(95937),P=i(98314),_=i(38835),M=i(70025),T=i(8769),E=i(43334),k=i(95402),D=i(28874),x=i(63870);class C extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>n(this,r,"m",s).call(this)),i,"worker"===e?(0,x.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,k.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,S.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&k.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,b.ending)()||!0===(0,M.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,T.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,r=new WeakSet,s=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(E.isWin?3:1)*c.minuteMs,maxTasksPerProcess:D.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:D.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:D.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,x.commandTimeoutMs)(),taskTimeoutMillis:D.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,s.set(this,void 0),n.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,s,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]=t))}get length(){return u(this,n,"f")}set length(e){l(this,n,(0,d.clamp)(0,u(this,n,"f"),e),"f")}clear(){this.length=0}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,n,"f")),e<0||e>=u(this,n,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,s,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,n,"f"){u(this,s,"f")[e]=c}));return u(this,n,"f")}pop(){return u(this,r,"m",o).call(this,u(this,n,"f")-1,(e=>{var t;return l(this,n,(t=u(this,n,"f"),--t),"f"),u(this,s,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,n,"f"){u(this,s,"f")[e]=c,l(this,a,e,"f")}));return u(this,n,"f")}shift(){return u(this,r,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,n,(i=u(this,n,"f"),--i),"f"),u(this,s,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",o).call(this,u(this,n,"f")-1-e,(e=>{const i=u(this,s,"f")[e];u(this,s,"f")[e]=u(this,s,"f")[t],u(this,s,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=n(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),s=i(31586),n=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),s=i(65843),n=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),s=i(20014),n=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)((()=>!1))},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),s=i(98553);var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},19851:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?M():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const _={timeoutMs:10*a.secondMs};async function M(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function T(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=M,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),s=i(32105),n=i(14593);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),s=i(55835),n=i(59455),a=i(48884);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),s=i(54557);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},26033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._isSupportedNode=t.RequiredNodeRange=t.isSupportedNode=void 0;const r=i(45599),s=i(76280);function n(e=process.versions.node){return(0,s.semverSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange="18||20||21",t._isSupportedNode=n},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),s=i(42659),n=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,s]of(0,l.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,l.keys)(e))if(r[n]=t(n,e[n]),s++,(0,o.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,n.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),s=i(73024),n=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function _(){return"ubuntu"===(0,t.osDistributionLinux)()}function M(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=_,t.hasApt=function(){return P()||_()},t.isFedora=M,t.isAlpine=T;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},k={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return D(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":D(e,k);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(_())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(M())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},45393:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=4},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),s=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),s=i(56409),n=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return s.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),s=i(54993);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),b=i(24399),S=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>T.prior()?.clear()))));const _=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let M=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),M)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;M=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(1708)),n=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),s=i(57150),n=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,n.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,s.logStartup)())}},28850:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),s.set(this,void 0),n(this,r,e,"f")}_call(){return(0,l.time)(a(this,r,"f")+(null==a(this,s,"f")?"(local)":"(remote)"),null==a(this,s,"f")?this.impl():a(this,s,"f").call(this))}setShim(e){n(this,s,e,"f")}hasShim(){return null!=a(this,s,"f")}clearShim(){n(this,s,void 0,"f")}}r=new WeakMap,s=new WeakMap},12089:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=a,s.set(this,void 0),n.set(this,void 0),l(this,s,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",a).call(this,e),(()=>u(this,r,"m",o).call(this,e)))}setShim(e){l(this,n,e,"f")}hasShim(){return null!=u(this,n,"f")}clearShim(){l(this,n,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",a).call(this,e))}}s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,s,"f")+(null==u(this,n,"f")?"(local)":"(remote)"),null==u(this,n,"f")?this.impl(e):u(this,n,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return s(this,r,"f")[Symbol.iterator]()}get length(){return s(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=s(this,r,"f").length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),a=this.valueOf(s(this,r,"f")[n]);if(e===a)return{found:!0,index:n};e>a?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&s(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...s(this,r,"f")];const a=t=>t<0||t>s(this,r,"f").length-1?null:(i??this.diff)(s(this,r,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return s(this,r,"f").shift()}at(e){return(0,a.at)(s(this,r,"f"),e)}toA(){return[...s(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===s(this,r,"f").length-1){const e=[...s(this,r,"f")];return s(this,r,"f").length=0,e}return s(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return s(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),s=i(82328),n=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),s=i(95705);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" …(+"+s+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function M(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=M;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(M(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['‘’].*['‘’]$/,k=/^["“”„«»〃].*["“”„«»〃]$/;function D(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||k.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=_;const M=/[^\da-z]+/gi;function T(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(M,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),s=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},75387:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},65211:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(19851),s=i(76790),n=i(22573),a=i(54993),o=i(7282),l=i(55222);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!(0,o.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),u=0}},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),s=i(55835),n=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},79184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(59455),s=i(48884),n=i(22859),a=i(28874),o=i(79781),l=i(92434);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(50357),o=i(55835),l=i(31586),u=i(68708),c=i(12168),d=i(23467),h=i(73168),f=i(50213),m=i(86580),p=i(48368),g=i(80361),y=i(28874),v=i(28544),w=i(75767),b=i(16170),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} ≠ ${o}`}function _(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function M(e,t){return[_(e),_(t)]}function T(e,t,i){const r=(0,w.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.aKey}:${r.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=v.CapturedAt.fromAssetFile(e),f=v.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const _=a.isFuzzy||f.isFuzzy;if(_&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",M)??P(e,i,"model",M);if(null!=E)return E;const k=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),D={cameraId:T(e,i,"cameraId")??null,imageId:T(e,i,"imageId")??null,lensId:T(e,i,"lensId")??null,exposureSettings:(0,w.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(k,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(k)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:D});const x=(0,s.compact)((0,u.values)(D));if((0,s.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:_});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(D).filter((e=>null==D[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos ≠ images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=E(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},13991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(19851),s=i(55835),n=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),v=i(14036),w=i(45200),b=i(34238),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function _(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>M(e*t)))}function M(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=_,t.sortScale=M,t.mtime2sort=T;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function k(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function D(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=_(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=D(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=k,t.assetFileSortCriteriaPojo=D,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of k(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),s.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,n(this,s,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return n(this,s,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,n(this,s,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=n(this,r,"f")&&clearTimeout(n(this,r,"f")),a(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,s=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(87997)),n=i(31586);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),b=i(45599),S=i(26905),P=i(55835),_=i(31586),M=i(68708),T=i(20214),E=i(57153),k=i(85556),D=i(50213),x=i(70025),C=i(95937),F="TIMEOUT",A=(0,b.defer)((()=>(0,D.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,_.gt0)(t)?new s(F).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const s=i[r];if(s.isSettled){if(s.name===F)return void A().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield s.value}}if(i.every((e=>e.name===F)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,M.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new k.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,s=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,s.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,s=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},39250:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(23838),a=i(54993),o=i(15674),l=i(73568),u=i(76740),c=i(99331),d=i(42638);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new d.Promises(e,t)}vacuum(){return s(this,r,"f").filterInPlace(((e,t)=>t.isPending&&!0!==t.payload?.aborted)),s(this,r,"f").valueCount()}enqueue({key:e,abortable:t,fn:i}){for(const t of s(this,r,"f").get(e)??[])t.payload?.abort("aborted by new work");if(this.vacuum(),(0,c.ending)())throw new l.AbortError("ending");const n=t??new u.Abortable,o=this.p.serial((0,a.toS)(e),(()=>i(n)),n);return s(this,r,"f").add(e,o),o}},r=new WeakMap},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new b(e,t,i,r)};class b extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,n,0,"f"),d(this,s,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,r,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,n,"f")}isStale(){return null==c(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,s,"f")?void 0:Date.now()-c(this,s,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,n,(i=c(this,n,"f"),++i),"f")}},u=function(e){d(this,s,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),s=i(80049);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},22781:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),s.set(this,!1),n.set(this,!1)}_call(){return a(this,s,"f")?(o(this,n,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,r,"f")):(o(this,s,!0,"f"),o(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,s,!1,"f"),!0===this.runLaterIfBusy&&a(this,n,"f")&&(o(this,n,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,s,"f")}prior(){return a(this,r,"f")}async force(){return await a(this,r,"f"),this._call()}}r=new WeakMap,s=new WeakMap,n=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var b=i(20214);async function S(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,l.gt0)(s)?(0,c.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function M({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const u=a??(o.length<=s?w.PermissivePromises:new w.Promises(i,(()=>s))),d=(0,l.gt0)(n)?e=>(0,c.thenOrTimeoutError)(t(e),n):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=S,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await S(s);r.push(...await S(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=M,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await M({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await M({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await M({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){s=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await M({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),b=i(73614);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function M(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),r=t();return M(e,Date.now()-i),r},t.pushTime=M,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>_(e,t)),i)}},42638:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),b=i(82647),S=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},59189:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(1708)),n=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),b=i(88158),S=i(45969),P=i(43334),_=i(28874),M=i(3790);function T(e){return E().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const E=(0,n.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,b.sortedKeys)((0,l.filter)((0,d.env)(),(e=>T(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const k=["HOME","LANG","USER"],D=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?k:D),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,S.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,_.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,o.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(s.default.env,(e=>T(e)||!(0,M.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:A({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let F=!1;function A({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,g.childProcLocale)():{},...C(r),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(s);if((0,y.isLogged)("debug")&&!F){F=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(s).map((([e,t])=>[e,(0,M.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>T(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return s}t.childEnv=A},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),b=i(22911),S=i(4867),P=i(73614),_=i(70025),M=i(57159),T=i(36868),E=i(66184),k=i(45643),D=i(95402),x=i(9727),C=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function A(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,D.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,k.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{D.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,D.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,k.waitForPidExit)(i,5e3)}function I(e,i,r,s=0){const a=new Date,o=[];return(0,v.niceable)(i,r)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&A(e)}),s-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,D.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,E.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new b.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,T.endStream)(a.stdin);const v=new d.Latch;null==a.stdout?v.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==a.stderr||s?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,S.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,S.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,S.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const E=p.join("");(0,l.notBlank)(E)&&g.push(new Error(E)),!r&&(0,o.isNotEmpty)(g)&&C().warn(f+" resulted in errors:",g);const k=i.isIgnorableError??_.isIgnorableError,D=g.filter((e=>!0!==k(e)));if(D.length>0)throw 1===D.length?D[0]:new M.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!n&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:E}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,D.killPid)(a.pid,!0),e}}t.endProcess=A,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),s=i(41400),n=i(19851),a=i(28874);(0,s.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,n.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},34330:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),b=i(25764),S=i(99331),P=i(42638),_=i(38835),M=i(8769),T=i(57159),E=i(66003),k=i(50213),D=i(45643),x=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,k.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,M.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,M.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,M.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),s=i.sibling(r);if(s.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",s.posixPathFrom((0,l.examples)()));const n=(0,d.originalsDir)();if(s.isSelfOrDescendantOf(n))return a.join("$library",s.posixPathFrom(n));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",s.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(6858),a=i(1708),o=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return s(this,r,"f").push(...e),this}async parse(e=a.argv,t){let i=(0,m.addHelpFooter)(new n.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of s(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":o.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,a.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of s(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),s=i(38639),n=i(17181),a=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,s.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),a.Settings.logColor.envValue=e,(0,n.setupLogFormatter)()}))}}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(1708)),n=i(22573),a=i(38639);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},53978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},43380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(28874),s=i(2858),n=i(22573),a=i(38639),o=i(46292);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},54772:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return _(w(e))}function y(e){return(0,f.clampRGB)(T(M(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function M(e){const[t,i,r]=v(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=_,t.lab2xyz=M,t.xyz2rgb=T,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const k=new Map;function D(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return F(x(e))}function F(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function A(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function I(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(k,e,(()=>D(e,t))):D(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(A(e))},t.hsv2hsl=F,t.hsl2hsv=A,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},42079:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(31586),s=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),v=(0,s.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let _=y*v==0?0:b-w;_-=2*(_>Math.PI?1:0)*Math.PI,_+=2*(_<-Math.PI?1:0)*Math.PI;const M=2*(0,s.sqrt)(y*v)*Math.sin(_/2),T=(i+c)/2,E=(y+v)/2;let k;y*v==0?k=w+b:(k=(w+b)/2,k-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,k+=2*(k<0?1:0)*Math.PI);const D=(T-50)**2,x=1-.17*Math.cos(k-Math.PI/6)+.24*Math.cos(2*k)+.32*Math.cos(3*k+Math.PI/30)-.2*Math.cos(4*k-63*Math.PI/180),C=1+.015*D/(0,s.sqrt)(20+D),F=1+.045*E,A=1+.015*E*x,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*k-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*I)*O;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(M/(o*A),2)+L*P/(a*F)*M/(o*A))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(40958),s=i(31586),n=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},32848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(48884),o=i(31843),l=i(70417),u=i(3048);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},40401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),v=i(85810),w=i(3048),b=i(76490),S=i(1971),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=M[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function D(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(_.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...T,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&D(g-1);const n=s.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n),2);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),k(a,t);const A=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),I=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:A,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:A,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const _=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],M={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},T=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:M[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function k(e,t){const i=e.countSum,r=e.size;D(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function D(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=k,t.mergeLabhashes=D,t.mergeNearCentroids=x},85409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(31586),s=i(68708),n=i(50989);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),v=i(21330),w=i(928),b=i(54261),S=i(73389),P=i(51275),_=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function M(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function k(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void _().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=M,t.toDated=function(e){return M(e)?e:void 0},t.mapDated=function(e,t){return M(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):k(e)},t.datedToDateTime=k,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=D(e)),r??(r=D(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,v.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),s=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),s=i(31586),n=i(54557),a=i(91655),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),s=i(40958),n=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),v=i(79842),w=i(66649),b=i(98247),S=i(98725),P=i(928),_=i(54261),M=i(73389),T=i(89724),E=i(17415),k=i(88600),D=i(51275);function x(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,k.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(S.ISO_YMD_RE.exec(e)?.groups??S.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tx(e))).join("-")}toLocal(){return(0,T.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function F(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,_.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,E.zoneToTzOffsetMinutes)((0,w.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(s=>(0,d.map)((0,P.getDay)(e),(n=>(0,d.map)((0,P.getHour)(e),(a=>(0,b.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,h.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${x(n)}:${x(a)}`},t.toExifDateTime=F,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,M.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,_.hasTime)(e)||(i??(0,v.datedToPrecisionMs)(e))>=c.dayMs?O(e):F(e,(0,D.getZoneName)(e))?.toISOString({includeOffset:t})};const A="yyyy:MM:dd HH:mm:ss.SSS",I=A+"ZZ";function O(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>x(e))).join(t)}function L(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(w.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,v.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,D.hasZone)(t)?I:A):void 0},t.datedToYMD=O,t.toFuzzyDate=L,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,w.datedToMillis)(e)||null==(0,w.datedToMillis)(t))return;const[s,n]=[e,t].map((e=>(0,w.datedToMillis)(e))).sort(),o=(n-s)/(r+1),l=(0,D.getZoneName)(e),u=l===(0,D.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,_.hasTime)(e)))?L(c):c},t.setZone=function(e,t,i){const r={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,D.hasZone)(e)},s=(0,E.normalizeZone)(t);return null!=e&&null!=s&&(0,_.hasTime)(e)?e instanceof y.DateInterval?e.setZone(s,r):F(e)?.setZone(s,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,v.datedToDateTime)(e);if(null==i)return;const r=(0,D.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),v=i(68852),w=i(4001),b=i(28874),S=i(24689),P=i(79842),_=i(66649),M=i(98247),T=i(21330),E=i(54261),k=i(73389),D=i(16400),x=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,_.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,k.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function A(e,t,i){try{const r=(0,M.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,M.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,M.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:M.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>A(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const e of n){const t=a(e);if(null!=t&&(0,x.isValidDate)(t))return t}}t.parseDated=I;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),s=i(31586),n=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),s=i(31586),n=i(68708);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),s=i(19851),n=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,s.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?M(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(M(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function _(e,t){return M(Date.now()-e,t)}function M(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=_,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:_(i)};const M=/\b(?Z|UTC|GMT)\b/,T=/(?[-±+−])/,E=/[-−]/,k=/(?[01]\d)/,D=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return v(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),M,new m.RegExpEscaped("|"),T,k,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const A=/\b(?(?:Etc\/)?GMT)\b/,I=(0,n.lazy)((()=>(0,m.concatRegexp)([A,T,D,m.RegExpOptional.from(x)])));function O(e){return F(I().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return _(i);if(null!=t){const i=S(e);if(null!=i)return _(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),v=(0,s.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),w=(0,s.lazy)((()=>(0,n.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),b=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,p.datedToISO)(e)))))),S=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,y.datedToLocal)(e)))))),P=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,m.datedToMillis)(e))))));function _(e){if(null==e)return!1;const t=T(e);return v().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return _(e)?e:void 0},t.isValidDate=_;const M=String(new Date("bad"));function T(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===M)return M;const t=(0,n.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,E())&&s.push("year is in the future"),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):S().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):b().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(t)).join("; "))}catch(t){return v().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=T;const E=(0,s.lazy)((()=>r.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return _(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==T({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),s=i(31586),n=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},82261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},92407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(19851),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},55332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(19851),s=i(50213),n=i(76187),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},91872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i,r){const a=Date.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}))}},12943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(79842),s=i(66649),n=i(40958),a=i(68708);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},65753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(19851),s=i(7282),n=i(28874);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*((0,s.isTest)()?.25:5))))},80632:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(54993),u=i(50213),c=i(23560),d=i(65211),h=i(29882),f=i(53265),m=i(66430),p=i(66184),g=i(28874),y=i(15674),v=i(87550);function w(){const e=g.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,a.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=g.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=g.Settings.logSql.valueOrDefault}){e=(0,f.resolve)(e),(0,h.mkdirpSync_)((0,r.dirname)(e));const b=(0,h.posixPathFromGrandparent)(e),S=(0,m.nativePathSizeSync)(e),P=(0,u.mkLogger)("db.mkdb("+b+")");if(null!=S){const E=Math.round(S/o.MiB),k=Math.ceil(1.5*E);k>g.Settings.dbCacheSizeMb.valueOrDefault&&(P.info("Dynamically setting dbCacheSize to "+g.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:E}),g.Settings.dbCacheSizeMb.envValue=k);const D=Math.round(1.5*E);D>g.Settings.maxMemoryMb.valueOrDefault&&(P.warn("Large database: setting maxMemoryDb to "+D+"MB",{dbFileSizeMb:E,"Settings.maxMemoryMb":g.Settings.maxMemoryMb.valueOrDefault}),g.Settings.maxMemoryMb.envValue=D)}P.info("Opening "+e+"...");const _={fileMustExist:!1,readonly:!1};if((0,a.gt0)(t)&&(_.timeout=Math.ceil(t)),i){const x=(0,u.mkLogger)("SQLite("+b+")"),C=(0,p.defaultLogLevel)();function F(e,...t){var i;(0,n.blank)(e)||x.log(C,(i=e,(0,l.toS)(i).replace(/\s{2,}/g," ")),{args:t})}_.verbose=F}const M=new v(e,_);P.info("Open. Setting PRAGMAs...");for(const A of(0,s.compact)(['encoding = "UTF-8"',"threads = "+(0,y.maxCpus)(),"foreign_keys = ON","page_size = "+w(),"trusted_schema = 0","cache_size = -"+Math.round(g.Settings.dbCacheSizeMb.valueOrDefault*o.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL",(0,a.gt0)(g.Settings.dbBusyTimeoutMs.valueOrDefault)?"busy_timeout = "+g.Settings.dbBusyTimeoutMs.valueOrDefault:null,"temp_store = MEMORY","synchronous = "+g.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,c.isDbJanitorService)()?(0,l.toS)(g.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+g.Settings.dbAutoVacuumMode.valueOrDefault]))P.tapThunk({msg:"PRAGMA "+A,result:()=>M.pragma(A)});const T=M;return T.__uid=(0,d.uid)(),T},t.pageSizeBytes=w},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},95704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(40958),s=i(31586),n=i(59455),a=i(65753),o=i(51040);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},76187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(17217),s=i(87391),n=i(7311);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},51040:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+$/gm,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(19851),s=i(50357),n=i(30976),a=i(50213),o=i(95696),l=i(80632),u=i(76187),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},87391:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},27180:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(5916),s=i(84777),n=i(89966),a=i(63870),o=i(87550);t.sqliteVersion_=(0,r.lazyAsync)({desc:"db.sqliteVersion",later:async function(){let e;try{e=new o(":memory:");const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,n.sqliteNativePath_)(),r=(await(0,s.stdout_)(i,["-version"],{timeoutMs:(0,a.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:r.split(/\s+/,1)[0],fullToolVersion:r,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,a.commandTimeoutMs)()})},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),b=i(29882),S=i(45969),P=i(43334),_=i(28874),M=i(41692),T=i(32774),E=i(80612),k=i(32551),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function x(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function C(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:T.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:T.DefaultDockerLibraryDir},...x()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,k.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,k.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,k.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...x()),i}t.tmpCacheDirs=x,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:x(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:C(),desc:"cache"})));const F=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(A)}));function A(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{F();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,b.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=A},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),s=i(45969),n=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},79960:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(45255),o=i(84777),l=i(16287),u=i(57902),c=i(43334),d=(0,r.lazy)((()=>(0,n.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,o.stdout_)("defaults",h,{timeoutMs:a.ShortCommandTimeoutMs});if((0,s.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),s=i(45969),n=i(32774);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),s=i(96706),n=i(29882);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),s=i(49776),n=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},48195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotLibraryDir=t.isLibraryDir=void 0;const r=i(19851),s=i(22573),n=i(98553),a=i(12168),o=i(50213),l=i(15056),u=i(98314),c=i(17217),d=i(16287),h=i(2858),f=i(87290),m=(0,r.lazy)((()=>(0,o.mkLogger)("dir.IsLibraryDir")));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),s=i(54993),n=i(29882),a=i(28874);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),s=i(55835),n=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e),!1)}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function M(e){return y(_(e))}async function T(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await M(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=M,t.setupLibraryDbDir_=T},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),s=i(7282),n=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),s=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),b=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,n.join)((0,m.homeDir)(),".psenv"));const t=(0,b.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,d.debom)(s.default.readFileSync((0,g.resolve)(r))),n=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(n))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),s=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(1708)),n=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),s=i(19851),n=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),s=i(26905),n=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),s=i(38639),n=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function b(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function S(e){return!!((0,s.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||b(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=b,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===S(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=S;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),s=i(31586),n=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),s.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(n(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),s=i(19851),n=i(15197);t.ee=(0,s.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new n.CapturingEventEmitter(e)}))},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(73024)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(76760)),n=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),s=i(76760);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),v=f(i(1708)),w=i(46466),b=f(i(57975)),S=f(i(38522)),P=i(19851),_=i(40958),M=i(5233),T=i(22573),E=i(42659),k=i(50357),D=i(96249),x=i(98553),C=i(55835),F=i(31586),A=i(68708),I=i(97790),O=i(39926),L=i(51926),R=i(59455),N=i(54993),B=i(48884),j=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),H=i(76850),q=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Y=i(43334),Z=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),se=i(89968),ne=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),be=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const Se=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const s=(0,fe.resolve)(i),n=new Pe(s,t);return Se().set(i,n),Se().set(s,n),n}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,k.eql)(["."],e)||e.every(T.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,H.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,be.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,A.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,M.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Z.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),_e)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,n=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*E.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),s=i(88840),n=i(14036),a=i(29882);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,n.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),b=i(16287),S=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class M{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new M(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new M(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return M.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new M(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>M.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new M(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=M},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),v=i(54557),w=i(50213),b=i(88158),S=i(56519),P=i(46292),_=i(32551),M=i(35280),T=i(87290),E=i(96706),k=i(57902),D=i(43334),x=i(78984),C=i(33995),F=i(28874),A=i(21144),I=i(83278),O=i(48313),L=i(85772),R=i(78133),N=i(46356),B=i(17217),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?k.LogLevels.debug:k.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class H{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const q=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new H;e.push(G,q);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((D.isWin?"*":"")+"/"+t.s+"/",t.desc));if(D.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}D.isLinux&&e.push(new U(`${(0,_.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ne,whyNoMedia:L.whyNoMedia,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ne}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Z=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return F.Settings.disableAllFilters.valueOrDefault?void 0:x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ne(e){return!(0,M.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),...F.Settings.argvScanPaths.values,...F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,A.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ne},88561:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},79267:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const c=i(19851),d=i(40958),h=i(42659),f=i(31586),m=i(71371),p=i(50213),g=i(7282),y=i(409),v=i(78406),w=i(25764),b=i(99331),S=i(91655),P=i(34102),_=i(89968),M=i(85772);class T{static for(e){return new T(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,a,d=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=a,this.minRetained=d,s.set(this,void 0),this.intervalMs=(0,c.lazy)((()=>(0,f.clamp)((0,g.isTest)()?0:5*h.minuteMs,h.dayMs,this.staleMs/2))),n.set(this,void 0),this.cleanup=(0,y.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>u(this,r,"m",o).call(this)}),l(this,s,(0,p.mkLogger)("fs.FileCleanup("+e+")"),"f")}scheduleInterval(){return(null==u(this,n,"f")||u(this,n,"f").ended)&&l(this,n,new v.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:w.EndableRanks.first}),"f"),u(this,n,"f")}cancelInterval(){u(this,n,"f")?.end(),l(this,n,void 0,"f")}}t.FileCleanup=T,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(e){if(!(0,f.gt0)(this.minRetained))return new Set;const t=new m.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},o=async function(){try{if((0,b.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await _.DirectoryEntry.for(e);if(null==t)return[];u(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,S.fmtFullDuration)(this.staleMs," ")});const i=await u(this,r,"m",a).call(this,t),n=Date.now()-this.staleMs,o=new Set,l=[],c=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,M.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,f.gte)(e.mtimeMs(),n)))if(e.isDirectory())try{await e.rmdir_(),c.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(u(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,P.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&u(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),l.push(e.nativePath),o.add(e.dir)}catch(t){u(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const h=[...l,...c];return(0,d.isNotEmpty)(h)&&t.clear(),u(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:l.length,pruned_dir_count:c.length}),h}catch(e){return void u(this,s,"f").error("cleanup() failed",{error:e})}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,n.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),s=i(17217),n=i(16287),a=i(68284);async function o(e){return(0,r.pick)(await(0,n.stat_)((0,s.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,s.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),s=i(19851),n=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,s.set(this,[]),n.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,n,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,s,"f").push(e)}close(){u(this,n,"f").close()}}t.FileWatcher=m,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,s,"f"))t(e,this.nativePath)}}},13829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(55835),s=i(13538),n=i(81168),a=i(37628),o=i(46292),l=i(73209),u=i(95696);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},73209:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const _=i(58587),M=P(i(44652)),T=i(87997),E=i(40958),k=i(17586),D=i(42659),x=i(50357),C=i(75240),F=i(55835),A=i(31586),I=i(30976),O=i(13538),L=i(54993),R=i(7282),N=i(68852),B=i(23560),j=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),H=i(55222),q=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,s,Math.max(Date.now(),b(this,s,"f",n)+1),"f",n),(0,E.compactBlanks)([H.TokenRadix.encode(b(this,s,"f",n)),B.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,A.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return b(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>b(this,r,"m",w).call(this)),e.endableRank??j.EndableRanks.postdb,(0,q.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=s,s,(i=b(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(b(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await b(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+b(this,l,"f")),this.staleMs=(0,A.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),b(s,s,"f",o).push(this)}get acquired(){return b(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await b(this,r,"m",f).call(this,e)??b(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,k.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,x.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==b(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:D.secondMs);S(this,c,setInterval((()=>b(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=b(this,c,"f")&&(clearInterval(b(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(b(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),S(this,u,!1,"f"),(0,F.map)(b(this,d,"f"),(e=>(0,T.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?b(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>b(this,r,"m",v).call(this)),(0,A.toGt0)(this.staleMs)??D.secondMs),"f"),b(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(b(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,A.gt0)(this.staleMs)&&Date.now()>b(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await b(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await b(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,A.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,A.gt0)(t)&&!(0,_.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),b(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await b(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await b(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,E.filterInPlace)(b(s,s,"f",o),(e=>b(e,l,"f")!==b(this,l,"f")))},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),s=i(51926),n=i(54993),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(73024)),n=i(57075),a=i(46466),o=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44652)),n=r(i(73024)),a=i(46466),o=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(n.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),s=i(42659),n=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),s=i(54993),n=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,n.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,n.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,n.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,n.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(51926),n=i(54993);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(76760)),n=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},61704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(21144),s=i(17217);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=n(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),b=i(88561),S=i(65238),P=i(16287),_=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),M="NoMedia",T=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+M+"$","im"),E=Object.freeze(["."+M,M]),k=Object.freeze((0,u.flatten)(E.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function D(e){return null!=T.exec(e)}t.isNoMediaName=D;const x=(0,o.lazy)((()=>new b.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=v.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return D(i.base)||await(0,w.isCachedirTagFile)(i)?x().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await x().getOrSetAsync(i.nativePath,(()=>F(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function F(e){if(D(e.base))return x().set(e.parent().nativePath,e.nativePath),_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,S.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([A(e.nativePath,i),(0,S.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,w.isCachedirTagDirectory)(e)?_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function A(e,t){for(const i of g.isCaseSensitiveFs?k:E){if(!0===t?.aborted)return null;const r=a.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return _().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(D(r.basename))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,r.basename))});if(r.basename===w.CACHEDIR_TAG){const t=(0,a.join)(e,r.basename);if(await(0,w.isCachedirTagFile)(t))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=F,t._dirHasNoMediaChild=A},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),b=i(17217),S=i(16287),P=i(66430),_=i(5545);function M(e){return((0,b.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return C(e).some(M)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,b.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return E((0,v.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return n.default.dirname((0,b.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const T=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=T.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function k(e){const t=n.default.parse((0,b.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,n.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,b.toNativePath_)(e.ancestor),i=(0,b.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function x(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(y.isLinux?r===s:(0,p.equalsIgnoreCase)(r,s))}function C(e){return(0,b.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function F(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function A({p:e,maxLength:t}){const i=(0,b.toNativePath_)(e);if(i.length<=t)return i;const r=C(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),O([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),O([...s,...n])}function I(e){return e.startsWith("\\\\")}function O(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),y.isWin?"":n.default.sep)}t.parseNativePath=E,t.parentBasename=k,t.grandParentBasename=function(e){return k(n.default.parse((0,b.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return x(b.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return x(b.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return x(b.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=F,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,b.toNativePath_)(e),r=(0,b.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,v.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=A,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(A({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;if(F(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await s.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,b.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,b.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),b=i(16287),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function M(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,...M()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),b=i(22573),S=i(42659),P=i(26905),_=i(75240),M=i(55835),T=i(31586),E=i(68708),k=i(13538),D=i(89937),x=i(12168),C=i(54993),F=i(48884),A=i(50213),I=i(45255),O=i(81168),L=i(56519),R=i(56038),N=i(31562),B=i(84777),j=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),H=i(43334),q=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Y=i(34238),Z=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),se=i(73209),ne=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,A.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),r=new fe(i,t);return(0,O.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,M.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,M.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,M.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,k.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,T.clamp)(I.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,M.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,M.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),H.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,M.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),v=i(83278),w=i(19748),b=i(92423),S=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):null}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function k(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function D(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function A(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function I(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:A}]}function O(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:_},{notVideoTooShort:M},{notVideoTooLong:T},{notRejectedRating:k},{notExcludedKeyword:D}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=_,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=A,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(76760)),n=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(s.default.join((0,p.execDir)(),"resources"),s.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=s.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),s=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),s=i(84542);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(51455)),n=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),b=i(88561),S=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function _(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const M=(0,a.lazy)((()=>new b.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function T(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function E(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=k(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(s===f.Timeout&&(0,g.onTimeout)({soft:!1}),s!==f.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=T,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():T(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){T(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?E(e):k(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=k},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const s=i(73024),n=r(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=n.default.resolve(t,...e);if((0,s.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??n.default.resolve(...e))},t.execDir=(0,l.defer)((()=>n.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(22454),s=i(28874),n=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),s=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const s=r(i(73024)),n=r(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function S(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(S(r),S(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}t.stat_=v,t.statMaybe=w,t.statToType=b,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),s=i(56409);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(57075)),n=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),v=i(19851),w=i(40958),b=i(22573),S=i(42659),P=i(98553),_=i(31586),M=i(68708),T=i(50989),E=i(51926),k=i(85556),D=i(54993),x=i(89788),C=i(23467),F=i(7282),A=i(23560),I=i(77377),O=i(71567),L=i(73568),R=i(25764),N=i(38836),B=i(99331),j=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),H=i(5012),q=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Y=i(84542),Z=i(73428);t.AssetFileSyncStates=(0,T.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,T.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,T.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,T.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const X={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,M.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,T.strEnum)(...(0,M.keys)(new class{constructor(e,t,i,r,s,n,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,v.lazy)((()=>(0,Z.writeTextfile_)(re().nativePath,(0,E.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(X)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=S.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,q.isCsvExt)(e)&&(0,_.gte)(e.mtimeMs(),t)))},t.syncReport=(0,v.lazy)((()=>new se));class se extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new x.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,s,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,b.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,H.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,D.toS)(e.path),state:e.state,details:(0,D.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:t,at:new Date(t).toISOString(),...i,...(0,M.pick)(e,"from","elapsedMs","url")};(0,M.isEmptyObj)(e.meta)||(s.meta=(0,P.stringify)(e.meta)),(0,F.isTest)()&&process.stdout.write((0,P.stringify)(e)+Y.Newline),f(this,r,"m",u).call(this,s)}}maybeSystemData(e){(0,A.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:n}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,B.ending)()||r instanceof L.AbortError?t.SyncFileStates.canceled:r instanceof k.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return f(this,n,"f")??f(this,r,"m",h).call(this)}async flushClose(){return f(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,n,"f");return m(this,n,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,s,"f")}}t.SyncReport=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,r,"m",c).call(this,i):(f(this,r,"m",c).call(this,{...i,details:(0,w.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Y.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,s,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,j.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,s,"f").nativePath),this.logger.info("Opening new report: "+f(this,s,"f")),(0,F.isTest)()&&(0,O.stdoutWrite)({syncReport:f(this,s,"f").nativePath},!1),m(this,n,(0,g.createWriteStream)(f(this,s,"f").nativePath),"f"),f(this,n,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Y.Newline),f(this,n,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(48161)),n=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44652)),n=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},79847:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkFileUri=t.trashOrUnlinkFileUris_=void 0;const o=n(i(51455)),l=a(i(49378)),u=i(40958),c=i(22573),d=i(13538),h=i(83104),f=i(45255),m=i(31562),p=i(98314),g=i(34102),y=i(28874),v=i(45200),w=i(63870),b=i(16287),S=i(74128),P=i(84258),_="fs.Trash";async function M(e){const t=Date.now(),i=(0,w.commandTimeoutMs)(),r=(0,c.toNotBlank)(e.nativePath)??await(0,d.thenOrTimeout)((0,v.uri2nativePath)(e.uri,e.mountpoint),i);if((0,c.blank)(r)||r===h.Timeout)return(0,S.syncReport)().onProgress({from:_,state:"failed",details:"Could not convert URI to native path",path:e.uri,elapsedMs:Date.now()-t}),{uri:e.uri,unlinked:!1};const s=await(0,b.statMaybe)(r);if(null==s)return(0,S.syncReport)().onProgress({from:_,state:"noop",details:"Failed to delete: no such file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(!s.isFile())return(0,S.syncReport)().onProgress({from:_,state:"noop",details:"Failed to delete: not a file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(y.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,d.thenOrTimeoutError)((0,l.default)(r,{glob:!1}),i),await function(e){return(0,m.untilTrue)((async()=>null==await(0,b.statMaybe)(e)),{timeoutMs:f.ShortCommandTimeoutMs})}(r))return(0,S.syncReport)().onProgress({from:_,state:"deleted",details:"Moved file to trash",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0};(0,P.logger)().warn("soft-delete("+r+") didn't seem to work: the file is still there?")}catch(e){(0,S.syncReport)().onProgress({from:_,state:"note",details:"Failed to soft-delete file to trash: "+(0,p.errorToS)(e),path:r,elapsedMs:Date.now()-t}),(0,P.logger)().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}try{return await(0,d.thenOrTimeoutError)(o.unlink(r),i),(0,g.ee)().emit("fileChanged",r),(0,P.logger)().info("unlink("+r+") successful"),(0,S.syncReport)().onProgress({from:_,state:"deleted",details:"Permanently deleted file",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0}}catch(i){return(0,S.syncReport)().onProgress({from:_,state:"failed",details:"Could not move file to trash or delete: "+(0,p.errorToS)(i),path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!1}}}t.trashOrUnlinkFileUris_=async function(e){const t=[];for(const{uri:i,mountpoint:r}of(0,u.uniqBy)(e,(e=>e.uri)))try{t.push(await M({uri:i,mountpoint:r}))}catch(e){t.push({uri:i,unlinked:!1,error:e})}return t},t.trashOrUnlinkFileUri=M},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),s=i(41400),n=i(55835),a=i(92782),o=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),h=i(87128),f=i(95696);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=n(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await a.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(76760)),n=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},60526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(47783),a=i(63335),o=i(18454);t.exiftoolHealthCheck=(0,s.defer)((()=>o.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifTool…",settings:[],later:async()=>{const e=await(0,n.exiftoolVersion_)();return{level:"ok",msg:["ExifTool is OK","ExifTool "+(0,a.ver)(e),(0,r.tt)((0,n.exiftool)().options.exiftoolPath)],meta:{exiftoolVersion:e}}}})))},19652:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const a=i(51455),o=n(i(22915)),l=i(40958),u=i(82950),c=i(22573),d=i(45599),h=i(12168),f=i(50213),m=i(79960),p=i(32551),g=i(98314),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,p.homeDir)(),o.getHomeFolder(),o.getPicturesFolder(),o.getVideosFolder(),o.getDesktopFolder(),await(0,m.defaultApplePhotosLibrary)()]).sort(),t=new Map,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,a.readdir)(e,{withFileTypes:!0})}catch(i){if(["ENOTDIR","ENOENT"].includes(i?.code))continue;t.set(e,i)}const r=0===t.size?{level:"ok",msg:["Default media directories are OK","The following directories are readable:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Error reading "+(0,h.plur)(t.size,"media directory")+":",(0,u.li)([...t.entries()].map((([e,t])=>(0,u.tt)(e)+":"+(0,g.errorToS)(t,{maxLen:80}))))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},79483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(45599),s=i(45969),n=i(19652),a=i(18454);t.externalDirsHealthCheck=(0,r.defer)((()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",pendingMsg:"Checking default photo directories…",settings:[],later:n.externalDirectoryCheck})))},63664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const r=i(22573),s=i(45599),n=i(41400),a=i(50268),o=i(98553),l=i(50213),u=i(23560),c=i(45255),d=i(5916),h=i(28874),f=i(34238),m=i(51140),p=i(4988),g=i(18454),y=(0,s.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({desc:"health.getRemoteHealthSummary",later:async()=>{try{if((0,u.isWebService)())return;const e=await(0,p.get_)(f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}),{timeoutMs:c.ShortCommandTimeoutMs}),t=(0,o.parseJSON_)(e.data);if(m.HttpStatusIs.ok(e.statusCode)&&(0,a.isHealthCheckSummary)(t))return"ready"===t.state&&(0,r.toNotBlank)(t.libraryDir)!==(0,r.toNotBlank)(h.Settings.libraryDir.valueOrDefault)&&(y().error("getHealthSummary(): libraryDir mismatch! Switching to that library directory...",{local:h.Settings.libraryDir.valueOrDefault,remote:t.libraryDir}),h.Settings.libraryDir.value=t.libraryDir),y().debug("getHealthSummary()",{response:e}),t;y().warn("getHealthSummary(): invalid response",{response:e})}catch(e){y().warn("Failed to get health check summary from web service",{error:e})}}}),t.getLocalHealthSummary=(0,d.lazyAsync)({desc:"health.getLocalHealthSummary",later:()=>g.HealthCheck.awaitSettled()}),(0,n.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},18454:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b,S,P,_=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},M=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const T=i(19851),E=i(40958),k=i(76790),D=i(22573),x=i(41400),C=i(50357),F=i(26905),A=i(50268),I=i(55835),O=i(68708),L=i(30976),R=i(51926),N=i(13538),B=i(42279),j=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),H=i(50213),q=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Y=i(77740),Z=i(98314),X=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),se=i(21525),ne=i(82638),ae=(0,T.lazy)((()=>(0,H.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{_(this,s,"f",l).push(e+": failed: "+(0,Z.errorToS)(t)),this.onResultChange()})),_(this,s,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return _(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){_(this,s,"f",l).push((0,R.isString)(e)?e:(0,Z.errorToS)(e)),this.onResultChange()}static lastErrors(){return _(this,s,"f",l).toA()}static addLoadingMsg(e){_(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,E.compact)((0,j.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:_(this,s,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[_(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=_(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>_(this,s,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return _(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,A.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=_(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=s.summary();if(e.pendingCount>0){const t=await Promise.all(s.testResultsCritical());e=s.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){s.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,F.shortStack)());else{this.onResultChange(),_(this,s,"f",l).clear(),_(this,s,"f",d).clear(),_(this,s,"f",h).clear(),_(this,s,"f",c).clear(),this.summary.clear(),M(this,s,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new s(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return _(this,s,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,n,o,l,u,c,d,h,f,m,S,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=n,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=S,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),w.set(this,(0,T.lazy)((async()=>{await _(this,p,"f").prior(),(0,C.eql)(_(this,g,"f"),_(this,r,"m",v).call(this))||(this.onReset?.(),await this.refresh(),_(this,w,"f").unset())}))),this.refresh=(0,T.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await _(this,p,"f").prior();const e=_(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,H.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[A.HealthCheckSections.ordinal(this.section),l??999,this.id],M(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>_(s,s,"f",a).enqueue({name:this.id,l:()=>_(this,r,"m",b).call(this,o)}),ttlMs:S}),"f"),this.isCritical&&_(this,p,"f").watchLater({onChange:s.onCriticalResult,onError:s.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>_(this,w,"f").call(this)))}isStale(){return _(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return _(this,p,"f").settledCount()}reset(){return _(this,p,"f").unset(),this.onReset?.(),M(this,g,{starting:!0},"f"),this}setTTL(e){_(this,p,"f").setTTL(e)}result(){return _(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return _(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return _(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??_(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,E.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,E.isNotEmpty)(i)&&(r.links=(0,E.uniqBy)(i)),(0,E.isNotEmpty)(t)&&(r.buttons=(0,E.uniqBy)(t)),r}t.HealthCheck=oe,s=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,w=new WeakMap,r=new WeakSet,o=function(){return(0,E.filterInPlace)(_(this,s,"f",n),(e=>!e.isPending)),_(this,s,"f",n)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,ne.summarizeHealthChecksSync)({errors:_(this,s,"f",l),skipPending:_(this,s,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&M(this,s,!0,"f",u),i.state!==_(this,s,"f",c).last?.state&&_(this,s,"f",c).push({state:i.state,ts:Date.now()}),i},v=function(){return(0,O.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},b=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,F.shortStack)()}),M(this,g,_(this,r,"m",v).call(this),"f");try{if((0,Y.getDevEnvFlag)("PS_SLOMO")&&await(0,x.delay)((0,L.randomInt)(.3*i,.7*i)),this.isSkipped())return _(this,r,"m",S).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const s=await(0,N.thenOrTimeoutError)(e(),i);return _(this,r,"m",S).call(this,{test:s,elapsedMs:Date.now()-t})}catch(e){return _(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},S=function({test:e,src:t="#toResult",elapsedMs:i}){var r,n;const a=s.normalizeMsg(e.msg),o=e.level??((0,z.toS)(a).toLowerCase().includes("error")?"error":(0,z.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,E.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(M(this,y,(n=_(this,y,"f"),r=n++,n),"f"),r),(0,$.ending)()?u:this.logger.tap({level:se.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const s=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,D.toNotBlank)((0,Z.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,X.isFatalError)(e)&&s.toLowerCase().includes("warn")?"warn":"error"),_(this,r,"m",S).call(this,{test:{msg:s,level:t},src:"#toErrorResult",elapsedMs:i})},n={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new U.CountingSet},f={value:[]},oe.all=(0,T.lazy)((()=>Object.freeze((0,k.sortBy)(_(s,s,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,q.debounce)((()=>{ae().info("onCriticalResult()",s.summary.refresh())}),250),oe.summary=(0,T.lazy)((()=>_(s,s,"m",m).call(s))),oe.resetDebounced=(0,q.debounce)((()=>s.reset()),50)},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},88625:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=t.testHealthCheck=void 0;const r=i(19851),s=i(82950),n=i(45599),a=i(50268),o=i(50213),l=i(7282),u=i(44198),c=i(34102),d=i(2858),h=i(60526),f=i(79483),m=i(18454),p=i(39214),g=i(86403),y=i(42482),v=i(35675),w=i(89035),b=i(31974),S=i(20752),P=i(85200),_=i(37301),M=i(65756),T=i(15024),E=i(3956),k=i(29332),D=i(61274),x=i(38372),C=i(49913),F=i(84728),A=i(7245),I=i(16264),O=(0,n.defer)((()=>(0,o.mkLogger)("health.HealthCheckSetup")));t.testHealthCheck=(0,n.defer)((()=>m.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,settings:[],pendingMsg:"Test check…",later:async()=>{const e=a.HealthCheckLevels.validOrElse((0,u.env)().PS_TEST_HEALTH_CHECK_LEVEL,a.HealthCheckLevels.ok);return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,s.b)("details")}:`,(0,s.li)("alpha",(0,s.tt)("bravo"),"charlie")]}}}))),t.healthCheckSetup=(0,r.lazy)((()=>{(0,h.exiftoolHealthCheck)(),(0,p.heifHealthCheck)(),(0,y.libraryDirectoriesCheck)(),(0,v.libraryFreeSpaceCheck)(),(0,E.settingsEnvHealthCheck)(),(0,D.settingsSystemHealthCheck)(),(0,k.settingsLibraryHealthCheck)(),(0,f.externalDirsHealthCheck)(),(0,w.memoryHealthCheck)(),(0,b.nodejsHealthCheck)(),(0,S.notInDMGHealthCheck)(),(0,P.osHealthCheck)(),(0,_.powershellHealthCheck)(),(0,x.sharpHealthCheck)(),(0,g.jpegtranHealthCheck)(),(0,T.securityHealthCheck)(),(0,M.sqliteHealthCheck)(),(0,C.systemLoadHealthCheck)(),(0,A.videoHealthCheck)(),(0,I.volumeHealthCheck)(),(0,F.versionHealthCheck)(),(0,l.isProd)()||(0,t.testHealthCheck)();let e=(0,d.libraryHasSettings)();d.libraryHasSettings.watchLater((t=>{null!=t&&e!==t&&(O().info("libraryHasSettings changed. Resetting health checks.",{newValue:t}),e=t,m.HealthCheck.resetDebounced())}));for(const e of["volumesChanged","mountpointsChanged","error"])(0,c.ee)().on(e,(()=>{O().debug("Clearing health check cache",{event:e}),m.HealthCheck.resetDebounced()}));(0,c.ee)().on("fatal",(e=>m.HealthCheck.addError(e)))}))},39214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(41400),a=i(55835),o=i(34102),l=i(277),u=i(45969),c=i(63335),d=i(18454);t.heifHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-heif",pendingMsg:"Checking HEIF/HEIC tooling…",settings:["heifConvertPath"],links:[{text:"Read how to set up HEIF support with PhotoStructure",url:"https://photostructure.com/getting-started/heif-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getHeifSupportDetails)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["HEIF images will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.heifHealthCheck.prior()?.reset()))}))},86403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testJpegtran_=t.jpegtranHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(55835),a=i(98314),o=i(89966),l=i(51210),u=i(76280),c=i(63335),d=i(18454);async function h(){const e=await(0,o.jpegtranNativePath_)(),t=await(0,l.jpegtranVersion_)();return{nativePath:e,version:t,satisfies:(0,u.semverSatisfies)(t,">=1.5")}}t.jpegtranHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,pendingMsg:"Checking "+(0,r.tt)("jpegtran")+"…",settings:[],later:async()=>{try{const e=await h();return{level:"ok",msg:["jpegtran is OK",(0,n.map)(e.version,c.ver),(0,n.map)(e.nativePath,r.tt)]}}catch(e){return{level:"error",msg:["Something's amiss with jpegtran",(0,a.errorToS)(e)]}}}}))),t.testJpegtran_=h},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},42482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(98553),o=i(31586),l=i(94174),u=i(87290),c=i(98314),d=i(29882),h=i(45969),f=i(43334),m=i(28874),p=i(2858),g=i(59107),y=i(18454),v=i(42495);async function w(){const e=await(0,u.setupLibraryDirs_)();return(0,p.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,r.li)(...e.map((e=>(0,r.tt)(e))))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}t.libraryDirectoriesCheck=(0,n.defer)((()=>y.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directories…",settings:["libraryDir","originalsDir","previewsDir","cacheDir"],ttlMs:s.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,h.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],okLinks:[{type:"button",text:"Run library maintenance jobs",url:"/admin/run-maintenance",method:"POST",icon:"handyman"}],later:async()=>(await(0,p.readSettings)(),(0,h.isDocker)()?async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,r.tt)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,r.tt)(m.Settings.libraryDir.toEnvLine(m.Settings.libraryDir.defaultValue))}`]};const t=await(0,g.mountpoints_)(),i=(0,d.bestMountpointForDir)(e,t);if(null==i||"/"===i)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,r.tt)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[v.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,r.tt)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`];return null!=t&&(0,o.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,r.tt)(t.uid)+", groupid "+(0,r.tt)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[v.DockerVolumeLink]}}return await w()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,l.userDesc)()}.`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[v.DockerVolumeLink]}}}():async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"no-library",msg:["No PhotoStructure library is open",(0,a.stringify)(m.Settings.libraryDir.getState())]};if(!(0,p.libraryHasSettings)())return{level:"no-library",msg:["No PhotoStructure library is open",m.Settings.libraryDir.hasValue()?(0,r.tt)(m.Settings.libraryDir.toEnvLine()):void 0]};try{return await e.isReadWriteExecutable_()?await w():{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(t){return{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,l.userDesc)()}`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}())})))},35675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(31586),l=i(68708),u=i(12168),c=i(87290),d=i(77740),h=i(28874),f=i(7014),m=i(18454);t.libraryFreeSpaceCheck=(0,a.defer)((()=>(0,l.tap)(m.HealthCheck.for({section:"Library",id:"library-free-space",settings:["libraryDir","minDiskFreeGb","originalsDir","previewsDir","cacheDir"],pendingMsg:"Checking free space on library volume(s)…",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,c.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(e)} is not a directory`};const t=[];for(const e of await(0,c.setupLibraryDirs_)()){const i=await(0,f.bestVolumeForPath)(e);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.tt)(e)}`};let r=t.find((e=>e.vol.mountpoint===i.mountpoint));null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*u.GB,n=[];for(const{vol:e,paths:a}of t){const t=(0,s.b)(`Volume ${(0,s.tt)(e.mountpoint)} has ${(0,u.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.li)((0,r.uniq)(a).sort().map(s.tt))}`;if(e.available{for(const t of["minDiskFreeGb","libraryDir","originalsDir","configDir"])h.Settings[t].watchLater((()=>e.reset()))}))))},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},31974:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(1708)),n=i(82950),a=i(45599),o=i(26033),l=i(63335),u=i(18454);t.nodejsHealthCheck=(0,a.defer)((()=>u.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.js…",settings:[],links:[{text:"Read about PhotoStructure NodeJS support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e="You're running Node.js "+(0,l.ver)(s.default.versions.node)+".\nPhotoStructure requires "+(0,n.tt)(o.RequiredNodeRange)+".";return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",e]}:{level:"warn",msg:["Node.js is not a supported version",e]}}})))},20752:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(45599),s=i(43899),n=i(43334),a=i(18454);t.notInDMGHealthCheck=(0,r.defer)((()=>n.isMac&&n.isElectron?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure installation directory…",settings:[],later:async()=>s.ProjectPath.isInDMG()?{level:"error",msg:"PhotoStructure cannot run directly from a DMG disk image. Please drag and drop the PhotoStructure icon onto your Applications folder to install.",checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure isn't running directly from a DMG disk image"}}):void 0))},85200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const r=i(45599),s=i(96175),n=i(18454);t.osHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating system…",settings:[],links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,s.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,s.osFullName)()]}:{level:"warn",msg:["Operating system is not supported",(0,s.osFullName)()+" was detected, but only "+e+"."]}}})))},37301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(98314),a=i(43334),o=i(24399),l=i(63335),u=i(18454);t.powershellHealthCheck=(0,s.defer)((()=>a.isWin?u.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShell…",settings:["powerShellArgs"],ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,o.checkPowerShell_)();return{level:"ok",msg:["PowerShell is OK",(0,l.ver)(e)],meta:{version:e}}}catch(e){return{level:"error",msg:"PowerShell failed: "+(0,n.errorToS)(e)}}}}):void 0))},65756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(27180),a=i(98314),o=i(63335),l=i(18454);t.sqliteHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLite…",settings:[],links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await n.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,r.li)(["embedded: "+(0,o.ver)(e.libraryVersion),(0,r.tt)(e.sqliteNativePath)+": "+(0,o.ver)(e.toolVersion)])]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,a.errorToS)(e)}}}})))},15024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(31586),o=i(94174),l=i(77740),u=i(44198),c=i(59958),d=i(43334),h=i(18454);t.securityHealthCheck=(0,n.defer)((()=>{const e=d.isWin?"an administrator":"root";return h.HealthCheck.for({section:"System",id:"proc-not-superuser",pendingMsg:"Checking user permission level…",settings:[],later:async()=>{if("0"===(0,u.env)().PUID)return{level:"disabled",msg:`Admin health check is disabled (${(0,s.tt)("PUID=0")}).`};const t=(0,r.compact)([(0,a.gte0)((0,o.userid)())?"Current user id: "+(0,s.b)((0,s.tt)((0,o.userid)())):void 0,(0,a.gte0)((0,o.groupid)())?"Current group id: "+(0,s.b)((0,s.tt)((0,o.groupid)())):void 0,"Current user name: "+(0,s.b)((0,s.tt)(await(0,o.username)()??"(unknown)"))]);return!0===await(0,o.isRootUser)()||(0,l.getDevEnvFlag)(c.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK)?{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]}:{msg:["PhotoStructure is not running as "+e,...t],level:"ok"}}})}))},3956:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(12168),a=i(28874),o=i(63225),l=i(18454);t.settingsEnvHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settings…",settings:[],links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,a.allSettings)())if(t.hasValue()&&null!=t._envValue()){const i=!0===t.opts.sensitive?"********":t.toEnvValue(t._envValue());null!=i&&e.push((0,r.tt)(t.key+"="+i))}const t=[(0,n.plur)(e.length,"environment setting"),(0,r.li)(e)],i=(0,o.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,r.li)(i.map((e=>(0,r.tt)(e.envKey)+": "+e.msg))),"---",...t]}:{level:"ok",msg:t}}})))},29332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(45599),s=i(2858),n=i(18454),a=i(61274);t.settingsLibraryHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settings…",settings:["libraryDir"],links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")})))},61274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=t.validateSettingsToml=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(12168),o=i(81168),l=i(98314),u=i(95696),c=i(2858),d=i(32707),h=i(18454);async function f(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.tt)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.tt)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,a.plur)(i.settings.length,t+" setting override"),(0,s.b)("Source:"),(0,s.tt)(e),(0,s.b)("Settings:"),(0,s.li)(i.settings.map((e=>(0,s.tt)(e.key+"="+e.toEnvValue(e.value)))))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,l.errorToS)(t)}}}t.validateSettingsToml=f,t.settingsSystemHealthCheck=(0,n.defer)((()=>h.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settings…",settings:[],links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>f(u.PosixFile.forMaybe((0,d.systemSettingsFile)()),"system")})))},38372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpHealthCheck=void 0;const r=i(45599),s=i(98314),n=i(21473),a=i(18454);t.sharpHealthCheck=(0,r.defer)((()=>a.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharp…",settings:[],later:async()=>{try{return await(0,n.testSharp_)(),{level:"ok",msg:["Sharp is OK","Image processing is working as expected."]}}catch(e){return{level:"error",msg:["Something's amiss with Sharp",(0,s.errorToS)(e)]}}}})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},49913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(31586),o=i(28874),l=i(14854),u=i(18454);t.systemLoadHealthCheck=(0,n.defer)((()=>u.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system load…",settings:["cpuBusyPercent"],ttlMs:s.minuteMs,later:async()=>{if(o.Settings.cpuBusyPercent.valueOrDefault<=0)return{level:"ok",msg:["CPU utilization is not monitored",(0,r.tt)(o.Settings.cpuBusyPercent.key)+" is set to <= 0"]};const e=l.CpuUsage.instance().busyPct(),i=(0,l.isTooBusy)();return(0,t.systemLoadHealthCheck)().setTTL((i?6:60)*s.secondMs),{level:i?"stop-sync":"ok",msg:"CPU utilization is "+(0,a.fmtPct)(e)+"\n"+(i?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause if CPU utilization exceeds")+" "+(0,r.tt)(o.Settings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(o.Settings.cpuBusyPercent.valueOrDefault)}}})))},84728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(40044),a=i(18454);t.versionHealthCheck=(0,s.defer)((()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure version…",settings:["autoUpdateCheck","configDir","libraryDir","optOut"],ttlMs:r.hourMs,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:n.checkVersion_})))},7245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(41400),a=i(55835),o=i(34102),l=i(66106),u=i(45969),c=i(63335),d=i(18454);t.videoHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-video",pendingMsg:"Checking video tooling…",settings:["ffmpegPath"],links:[{text:"Read how to set up video support with PhotoStructure",url:"https://photostructure.com/getting-started/video-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getVideoToolDetails_)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["Videos will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["Videos will not be imported","No video tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.videoHealthCheck.prior()?.reset()))}))},16264:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(13538),l=i(83104),u=i(12168),c=i(48884),d=i(45255),h=i(43334),f=i(69108),m=i(48165),p=i(63870),g=i(7014),y=i(18454);t.volumeHealthCheck=(0,a.defer)((()=>y.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,pendingMsg:"Checking volumes…",settings:[],links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:h.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=Date.now(),i=await(0,o.thenOrTimeout)((0,g.volumes)(),(0,p.commandTimeoutMs)());if(i===l.Timeout){const i=await(0,o.thenOrTimeout)(h.isWin?(0,m.getLocalVolumesWin_)():(0,f.dfPosixRawLocal_)(),d.ShortCommandTimeoutMs);return(0,t.volumeHealthCheck)().logger.warn("volumes() timed out, retrying in 5m"),setTimeout((()=>(0,t.volumeHealthCheck)().refresh()),5*n.minuteMs),{level:"warn",msg:[i===l.Timeout?"Something seems wrong with your computer's volumes":"Something seems wrong with one or more remote filesystem mounts","Gathering volume metadata took longer than "+(0,n.fmtAgo)(e,"")+"."]}}const a=i.filter((e=>!1===e.ok));if((0,r.isNotEmpty)(a))return{level:"warn",msg:["One or more volumes are not healthy","Check the following:",(0,s.li)(a.map((e=>(0,s.tt)(e.mountpoint))))]};const[y,v]=(0,c.partition)(i,(e=>!0===e.remote)),w=["Storage volumes are OK"];return(0,r.isNotEmpty)(v)&&w.push((0,s.b)((0,u.plur)(v.length,"local volume")+":"),(0,s.li)(...v.map((e=>(0,s.tt)(e.mountpoint))))),(0,r.isNotEmpty)(y)&&w.push((0,s.b)((0,u.plur)(y.length,"remote volume")+":"),(0,s.li)(...y.map((e=>(0,s.tt)(e.mountpoint))))),{level:"ok",msg:w}}})))},95242:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),v=i(57159),w=i(83278),b=i(95696),S=i(62105),P=i(84258),_=i(38156),M=i(69589),T=i(28874),E=i(47783),k=i(29990),D=i(16047),x=i(42725),C=i(4192),F=i(32876),A=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class O{constructor(e,t,i){r.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,M.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(r=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,S.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await n(this,r,"m",s).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:n,height:a,sha:l,mimetype:u}=t;if(null==s||null==n||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:n,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(x.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(r,s)){const n=(0,k.fitSizes)(e,e.mimetype),a=(0,o.diff)(r,s);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=n.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:n});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=O,s=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},x.ImageSize.sq().length+x.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:x.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,D.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,k.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=x.ImageSize.largestSq(),b=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,h.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of l){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&r.reducer===F.Fit&&T.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of x.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=T.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(r)+" -> "+(0,u.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,C.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),v=i(70417),w=i(35721);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},33106:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(9288)),n=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(40958),s=i(33374),n=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),s=i(54993),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),s=i(19851),n=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(9288)),n=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),v=i(88561),w=i(95696),b=i(17217),S=i(50213),P=i(23624),_=i(28874),M=i(12089),T=i(16170),E=i(1078),k=i(33106),D=i(86580),x=i(78011),C=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const A=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,D.fitToResolution)(i.dimensions,Math.round(_.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,D.fitToResolution)(i.dimensions,_.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?k.dctHash:k.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,M.shim1)({name:"img.imageHash",cache:A,impl:I}),t._imageHash_=I,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},80361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(33374),l=i(57924),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(21605),m=i(48884),p=i(50213),g=i(97352),y=i(85810),v=i(3048),w=i(32848),b=i(82647),S=i(38812),P=i(70417),_=i(23624),M=i(28874),T=i(86580),E=i(48368),k=i(2090),D=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function F(e,t,i=E.HashDim){const r=(0,_.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function A({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,r),l=F(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));D().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function I(e,t,i="debug",r={}){return D().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=A({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(r,s)}),m=A({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=A({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void D().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,v=(0,T.aspectRatio)(r),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let _=0,x=0;n&&(x+=M.Settings.imageHashFuzzyDateDelta.valueOrDefault,_+=M.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=M.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,_+=M.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(_+=M.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=M.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((_+(i.minImageCorr??M.Settings.minImageCoeffPct.valueOrDefault))/100),I=R((x+(i.minColorCorr??M.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,k.fmtAspectRatio)(v)} vs ${(0,k.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=I,z=j&&N.avg>=F;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:_,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:I,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return D().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=F(e,t,i);return f.Rotations.map((e=>(0,_.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=A,t.isSimilarImage=I,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return I(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},42725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},4192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},78011:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(9288)),n=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},48604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),s=i(31586),n=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(9288)),n=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,n.lazy)((()=>{s.default.simd(l.Settings.enableSIMD.valueOrDefault),s.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),s.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(77988),n=r(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),v=i(56519),w=i(56038),b=i(57159),S=i(95696),P=i(17217),_=i(28874),M=i(47783),T=i(16170),E=i(95141),k=i(54979),D=i(1078),x=i(63870),C=i(86580),F=i(277),A=i(16047),I=i(13940),O=i(5733),L=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,M.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await z(e,t))?.nativePath}async function j(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes<_.Settings.maxEmbeddedBuffer.valueOrDefault;try{const t=await B(e,i,l);if(null==t)return;const s=(0,n.default)(t,{failOn:_.Settings.imageFailOn.valueOrDefault}),o=await s.metadata(),u=(0,C.aspectRatio)(o);if(null!=a&&null!=u&&!(0,h.closeTo)(a,u,.2))return void N().info("imgFromExif("+e+", "+i+"): rejecting (aspect ratio mismatch)",{fileAspectRatio:a,renderedAspectRatio:u});const c=(0,C.lteBoth)(r,o);return N().debug("imgFromExif("+e+", "+i+")",{valid:c,minDim:r,useBuffer:l,fileAspectRatio:a,renderedAspectRatio:u,dim:(0,f.pick)(o,"width","height")}),c?{sharp:s,file:(0,m.isString)(t)?S.PosixFile.for(t):void 0}:void 0}catch(t){return void N().info("Failed to read image from EXIF tag "+i,{src:e,error:t})}}async function z(e,t){const i=t.toLowerCase().endsWith("tiff")?".tiff":".jpg";try{const r=await(0,I.tmpImageFile_)({src:e,tag:t,ext:i});return await r.applyIfEmpty_({retries:2,fn_:i=>(0,M.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=j,t.toSharp=function(e){const t=e;if((0,O.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:_.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=N().addParameterContext(e.nativePath);(0,O.setupSharp)();const n=await(0,k.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,D.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const I=(0,C.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),z=(0,T.isSharpMimeType)(n)&&null==t,V=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||z||V)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:z,isMirrorOrientation:V});else{const i=!1,n=await(0,M.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[..._.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(..._.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>j(e,n,t,x,I)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,F.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,F.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,L.isVideoSupported)())try{return await(0,v.thenMap)((0,L.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,w.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=z},21473:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=void 0;const s=r(i(34589)),n=i(76760),a=r(i(9288)),o=i(50357),l=i(98553),u=i(68708),c=i(23560),d=i(43899),h=i(28874),f=i(5733);t.testSharp_=async function e(t){try{(0,f.setupSharp)();const e=t??(0,n.join)(d.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(e,{failOn:"error"}),r=await i.resize(24,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,o.eql)((0,u.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:24,height:32,channels:3}),"Unexpected sharp output: "+(0,l.stringify)(r.info))}catch(i){if(!(0,c.isWorkerService)()&&h.Settings.enableSIMD.valueOrDefault)return h.Settings.enableSIMD.envValue=!1,e(t);throw i}}},181:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(9288)),n=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),v=i(54979),w=i(63870),b=i(5733),S=i(50961),P=i(66106),_=i(51210),M=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void M().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=M().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&M().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(M().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,_.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))M().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),v=i(56038),w=i(31562),b=i(98314),S=i(34102),P=i(88561),_=i(95696),M=i(17217),T=i(74128),E=i(31843),k=i(70417),D=i(33847),x=i(28874),C=i(94678),F=i(43207),A=i(47783),I=i(16170),O=i(95141),L=i(1078),R=i(63870),N=i(89782),B=i(13940),j=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,j.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,E.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function H(e){return await(0,t.isVideoSupported)()?_.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=V("extractVideoFrame",e),r=_.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,j.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,B.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,A.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,N.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,F.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,j.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,A.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,j.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,A.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,F.extractDurationSec)(i);if(!(0,c.gt)(n,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=H,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await G())return;const n=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,A.readTags)(e),h=(0,L.extractSizeInfoFromTags)(d),m=(0,F.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,A.readRawTags)(t),r=await(0,A.readRawTags)(e),s=(0,F.extractDurationSec)(r),n=(0,F.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),s=x.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,C.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,v.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:r.halt,...g},m=x.Settings.transcodeMaxDim.valueOrDefault,p=(0,k.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,j.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-n})}catch(t){throw(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:Date.now()-n}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await H(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,j.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),v=i(84258),w=i(28874),b=i(76280),S=i(63870),P=i(19769),_=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function M(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:w.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=M;const T=/ffmpeg version n?(?\S+)/i,E=(0,u.lazy)((async()=>{const e=await M();if(null==e)return void _().info("failed to find ffmpeg in $PATH",{ffmpegPath:w.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=T.exec(t.result)?.[1];return _().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){E.unset(),t.ffmpegVersionDescription.unset()}function D(e){const t=e?.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function x(e){const t=[...w.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(w.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=w.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(E(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",k),(0,g.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await E.prior()??E.refresh()},t.isFFmpegSupported=async function(){return null!=await E()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await M(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=x,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await M(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...x(t),...F(t),...D(t),"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){_().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,v.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return _().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return _().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await M(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(19851),s=i(42659),n=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),v=i(89782),w=i(13940),b=i(42725),S=i(19769),P=(0,r.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,w.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>k(e,t)})};const _=["-T"],M=["-Z","-"],T=["-o","1"],E=["-t","0","-j"];async function k(e,t){const i=await(0,v.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=b.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[..._,...M,...T,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],w={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:w});const k=(0,c.execFile)(g,y,void 0,w),D=[];function x(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});D.push(r)}}if(k.on("error",x),k.stderr.on("data",x),await t.writeStream_(k.stdout),(0,s.isNotEmpty)(D))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:D,path:e.nativePath});(0,c.endProcess)(k)}t.dcraw_emu_=k},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),v=i(50213),w=i(56519),b=i(76596),S=i(46292),P=i(87290),_=i(77740),M=i(34102),T=i(83278),E=i(28874),k=i(37692),D=i(71706),x=i(83950),C=i(72042),F=i(33603),A=i(48132);t.k=(0,y.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,C.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,_.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function L(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:x.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,F.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await L((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,A.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function B(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=L,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await L(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof x.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,_.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,F.sids)({timeoutMs:A.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),s=(n=(0,l.flatten)((await(0,w.someOrTimeout)([()=>function(e){return L(E.Settings[(0,t.k)().L].value,"Settings",A.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:A.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,f.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l))),(e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,o.later)((()=>{(0,M.ee)().on("clearCache",(()=>t.m.unset())),(0,M.ee)().on((0,t.k)().c,(()=>t.m.unset())),k.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=B,t.l=async function(){try{return await B()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await B()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},84194:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(40958),a=i(76790),o=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),h=i(19851),f=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(45599),o=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),h=i(50213),f=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),v=i(45879),w=i(70854),b=i(57902),S=i(72308),P=i(43334),_=i(24399),M=i(7014),T=i(30933),E=i(71706),k=i(84194);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const D=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,k.toUID)(k.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function A(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(F)))}async function I(){return P.isLinux?(await A("lm")).map((e=>(0,k.toUID)(k.S.lm,e))):void 0}async function O(){return P.isLinux?(await A("lp")).map((e=>(0,k.toUID)(k.S.lp,e))):void 0}async function L(){return P.isLinux?(await A("lb")).map((e=>(0,k.toUID)(k.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,k.toUID)(e,t)))}catch(e){return void D().warn((0,t.k)().i+" failed",e)}}async function N(){return(await _.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,k.toUID)(k.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,k.toUID)(k.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,k.toUID)(k.S.bm,(0,r.compactBlanks)(await A("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,k.toUID)(k.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,k.toUID)(k.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,k.toUID)(k.S.nm,e)))}async function H(){return(0,c.toA)(await(0,M.volumes)()).map((e=>(0,k.toUID)(k.S.vl,e.uuid)))}const q=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,I,O,L,B,U,H],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)q.add(e);return D().tap({msg:"sids()",result:(0,k.sortUids)([...q,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,f.isTest)())for(const t of e)q.add(t)},t.clearSids=function(){(0,f.isTest)()&&q.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),s=i(23560),n=i(66184),a=i(72210);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),s=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),s=i(42659),n=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},12495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(19851),s=i(42659),n=i(23560),a=i(79267),o=i(32144),l=i(28874);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isLogExt)(e.ext)})))},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),s=i(31586),n=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),s=i(57902);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,s.set(this,[]),n.set(this,(0,l.lazy)((()=>{o(this,s,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,s,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,n,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,r,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,r,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){if(null==e||0===o(this,s,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,s,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),s=i(50989),n=i(28874);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=n.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),s=i(76760),n=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),b=i(38836),S=i(99331),P=i(42638),_=i(76596),M=i(98314),T=i(89968),E=i(29882),k=i(28874),D=i(28981),x=i(20839),C=i(21727),F=i(66184),A=i(57902),I=i(72210),O=i(98192);function L(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,k.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(A.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,M.errorToS)(t))))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,_.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,M.errorToS)(e))))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,M.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),s=i(82328),n=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),b=i(23560),S=i(81168),P=i(78406),_=i(25764),M=i(20197),T=i(14977),E=i(36868),k=i(28874),D=i(32105),x=i(20839),C=i(21727),F=i(66184),A=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:_.EndableRanks.logger,unref:!0,onEnd:()=>c(this,s,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,A.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,M.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),k.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),s=i(84542),n=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),s=i(76790),n=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),s=i(41400),n=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),b=i(24068),S=i(43705),P=i(51879);function _(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),M();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new S.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,n.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&b.LogTail.instance()}function M(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=_,t.setupLogFormatter=M,(0,s.later)((()=>{h.Settings.logStdout.watchLater(_),h.Settings.logDir.watchLater(_),h.Settings.tailLogs.watchLater(_),h.Settings.logColor.watchLater(M),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},82647:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p69(){return n(this,r,"m",s).call(this,.5)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,s=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},44983:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(76790),s=i(93973);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},36372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(76790),s=i(42659),n=i(31586),a=i(97238),o=i(50597),l=i(9103),u=i(55222);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},38812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(21605);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}×${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),s=i(65713);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),s=v(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(38522),s=i(22573),n=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(48161)),n=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),b=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==b.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=S.exec(e)}function _(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=_,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=_(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,s.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=_(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),s=i(19851),n=i(54993);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(22573),s=i(51926),n=i(83556);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),s=i(59455),n=i(31562);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),b=i(54993),S=i(54557),P=i(19851),_=i(50213),M=i(88158),T=i(409),E=i(78406),k=i(25764),D=i(99331),x=i(56519),C=i(46292),F=i(8769),A=i(83278),I=i(32144),O=i(29882),L=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),j=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,O.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,T.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??L.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,f.isEmpty)(s))return B().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,N.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){B().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!z(r,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:r}),a.push(W(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,F.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,s,"f").delete(l),o(this,s,"f").getOrSet(l,(async()=>{const i=o(this,r,"m",n).call(this,e.pid),s=(0,v.opt)((0,M.Try)((()=>(0,O.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:s,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,s,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,r,"m",n).call(this,e);return(0,x.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new E.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:k.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=U,s=new WeakMap,a=new WeakMap,r=new WeakSet,n=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new U(A.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const s=i(31421),n=i(48161),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),b=i(56519),S=i(84777),P=i(8103),_=i(45879),M=i(43334),T=i(24399),E=i(45643),k=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){if(M.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,_.readFileMaybe)("/proc/"+i+"/stat")));return k().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,E.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>D(e)&&t.includes(e.pid)));return k().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=D,t.pidInfo=async function(e){return(0,b.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,b.thenMap)((0,E.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const C="Get-Process",F="| Select-Object -Property Id,ProcessName,StartTime";function A(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(T.PowerShell.instance().ended)return R(e);const t=[C,"-Id",A(e),"-ErrorAction SilentlyContinue",F].join(" ");return(0,b.thenMap)(T.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===a.default.pid))||r.push({pid:a.default.pid,start:new Date(v.StartTs),cmd:"node "+a.default.title}),r}async function N(e){return t=(await(0,S.stdoutResult_)("ps",["-p",A(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(M.isLinux)return(0,c.toGt0)((0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){k().warn("clk_tck failed",{error:e})}return 100})),j=(0,g.lazy)((()=>Date.now()-(0,n.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,s=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(s)?{pid:i,cmd:r,start:new Date(j()+s/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),s=i(42659),n=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),b=i(31562),S=i(84777),P=i(34102),_=i(43334),M=i(28874),T=i(63870),E="{ready}",k=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",M.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(M.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:M.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),M.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(M.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,k),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,k),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),s=i(91655),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874),l=(0,n.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,s.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,s.pick)(e??{},"retries","halt","path"),...(0,s.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),s=i(22573),n=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){_(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&M()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(m.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const b=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],S={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function _(e){for(const t of b)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:S;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function M(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=_,t.disableExternalNetworkRequests=M},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),s=i(53265),n=i(87652);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},4936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(55835),l=i(51926),u=i(50213),c=i(81168),d=i(79842),h=i(21330),f=i(51275),m=i(29882),p=i(28874),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+e.replace(/'/g,"′")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),s=i(83556);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),b=i(44198),S=i(96706),P=i(34102),_=i(28283),M=i(81075),T=i(98778),E=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?n(this,r,"m",s).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?n(this,r,"m",s).call(this,e??t)+": "+i:null==this.fromEnv(e)?n(this,r,"m",s).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,S.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,b.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return M.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,b.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&S.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,b.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&S.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,S.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],E.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],E.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+r],E.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,T.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,T.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,T.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,s=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),s=i(51168),n=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),b=i(7282),S=i(12801),P=i(4328),_=i(70488),M=i(84248),T=i(5531),E=i(99315),k=i(34365),D=i(34580),x=i(96706),C=i(50274),F=i(33866),A=i(52086),I=i(48584),O=i(45969),L=i(43334),R=i(24540),N=i(70379),B=i(71300),j=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),H=i(30577),q=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Y=i(71988),Z=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),se=i(57039),ne=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(b.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function be(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:be}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:be}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new se.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>q.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:q.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>q.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),minDelayBetweenSpawnMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ne.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:T.CheckpointTypes,defaultValue:T.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:k.SynchronousModes,defaultValue:k.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,O.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:F.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:H.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":s.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new ne.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:A.CropStrategies.attention,strEnum:A.CropStrategies}),videoFrameAtSec:new ne.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>j.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new se.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ne.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new ne.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function Se(e){const i=((0,u.blank)(e)?"":e).split(n.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(n.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=Se,t.pathWithDefaults=(0,a.lazy)((()=>Se((0,x.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(31586),n=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{w.Settings.configDir.opts.defaultValue=o.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,n.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,n.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,s.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),b=i(81168),S=i(83556),P=i(87290),_=i(98314),M=i(34102),T=i(83278),E=i(95696),k=i(60865),D=i(4175),x=i(83179),C=i(81075),F=i(28874),A=i(41692),I=i(84438),O=i(32707),L=i(6707),R=i(98778),N=i(55018),B=i(10357),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,O.systemSettingsFile)()){if(null!=e)return X(T.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,L.readTomlFile_)((0,O.systemSettingsFile)()))?.[F.Settings.libraryDir.name])}catch{return}}function U(e){return(0,L.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function H(){return U((0,O.systemSettingsFile)())}function q(e){return U(z(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:F.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,M.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,x.settingsToObj)(i),wip:r}),r){const t=await(0,L.readTomlFile_)(s),i=await(0,L.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function K(e=(0,O.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,F.persistedSystemSettings)()),t}function Y(e){return X(z(e))}async function Z(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,F.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,F.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function Q(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,L.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,F.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,F.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}})));return t.info("loaded",{settings:(0,x.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,D.handleDeprecatedSettings)(),(0,D.handleMetaSettings)(a),{settings:a,warnings:n}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Y()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return F.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=H,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await H()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await q()&&await Z()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,M.ee)().on("clearCache",G),(0,M.ee)().on("settingsChanged",G),F.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,k.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(E.PosixFile.for(e),(0,F.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=Z,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([F.Settings.noNetwork,F.Settings.httpPort,F.Settings.license,F.Settings.logStdout,F.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(F.Settings))ee().has(e.key)||e.unset();(0,M.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),F.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(E.PosixFile.forMaybe((0,O.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,M.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${(0,k.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,s=e.strEnum,(0,r.compact)((0,a.splitStringArray)(i)?.map((e=>s.getCI(e))));var i,s},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),s=i(55835),n=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),s=i(44652),n=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},63225:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=void 0;const r=i(68708),s=i(81168),n=i(44198),a=i(59958),o=i(28874);t.verifyPsEnvSettings=function(e=(0,n.env)(),t=.25){const i=[];for(const n of(0,r.keys)(e).filter((e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!a.IgnorableEnvKeys.includes(t)}))){const r=e[n],a=(0,o.ciSettings)().lookup(n);if(null!=a){const e=a.value.whyInvalidEnvValue(r);null!=e&&i.push({envKey:n,msg:e})}else{const e=(0,o.ciSettings)().lookupNearest(n,t);null==e?i.push({envKey:n,msg:`No setting was found like "${n}"`}):(0,s.equalsIgnoreCase)(e.key,n)||i.push({envKey:n,msg:`Did you mean setting "${e.value.key}"?`})}}return i}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),s=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),s=i(81168);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),v=i(81168),w=i(76596),b=i(79842),S=i(66649),P=i(21330),_=i(98725),M=i(928),T=i(54261),E=i(89724),k=i(17415),D=i(88600),x=i(51275),C=i(29882),F=i(17217),A=i(68284),I=i(57902),O=i(28874),L=i(65162),R=i(71300),N=i(14036),B=i(61424),j=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,b.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,F.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,b.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,A.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,_.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,k.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,k.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,w.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,x.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,T.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,x.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,k.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,b.datedToStartDateTime)(this.date)??(0,b.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,b.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function H(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],s=r;if((0,D.isValidDate)(t)){if((0,k.isValidZone)(e.tz)&&(!(0,x.hasZone)(t)||R.OverrideUTCZoneTags.includes(s))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,v.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,b.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,b.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,b.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,x.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function q(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,_.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,b.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,_.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,v.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",H(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??s("tags",H(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("stat+bname",await(0,B.extractStatBname)(e)))??(n?void 0:s("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",q(e,t)))??(n?void 0:s("path",G(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await $(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return H(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),s=i(97352),n=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(77988),n=r(i(76760)),a=r(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),v=i(12168),w=i(56038),b=i(4867),S=i(36557),P=i(98247),_=i(21330),M=i(98725),T=i(23467),E=i(88561),k=i(95696),D=i(17217),x=i(16287),C=i(50213),F=i(17921),A=i(7282),I=i(88158),O=i(23560),L=i(28874),R=i(12089),N=i(45255),B=i(81168),j=i(63870),z=i(15674),V=i(28544),W=i(43207),U=i(72180),H=i(75767),q=i(12788),G=i(80495),$=i(14036),J=i(67083),K=i(3432),Y=i(28630),Z=i(15912),X=i(30748),Q=i(16170),ee=i(95141),te=i(7330),ie=i(54979),re=i(1078),se=i(61424),ne=i(8791),ae=(0,o.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ce()};const le=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,S.batchClusterOptions)((0,A.isTest)()?8:(0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function ue(){const e=le();return e.ended?le.refresh():e}function ce(e=!1){return(0,d.map)(le.clear(),(t=>t.end(e)))}t.exiftool=ue,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeoutError)({p:ue().version(),timeoutMs:N.ShortCommandTimeoutMs})},t.exiftoolVersionMaybe=function(){return(0,d.map)(le.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,j.commandTimeoutMs)()})))},t.shutdownExiftool=ce,t.extractBinaryTag=function(e,t,i){return ue().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),ie.mimetypeCache.prior()?.clear()};async function de(e){return(0,f.omit)(await ge(e,!1),...t.IgnoredSidecarFields)}function he(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function fe(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function me(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function pe(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ae().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,ie.readMimeType)(e),s=await e.sidecar(),n=(0,Q.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Q.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ae().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function ge(e,i=!0){const r=k.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void ae().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ae().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,Y.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,Q.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ae().debug("readRawTags() sidecar had values",{sidecar:e.base})):ae().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,J.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,ee.orientationToRotation)(a.Rotation),ae().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ye(e,t){return null==t?void 0:(0,w.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Q.normalizeMimetype);if((0,u.blank)(r))return void ae().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,M.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ae().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,se.canInferForDir)(e.parent()),l=await(0,K.maybeInferTimezone)(e,n,o);if(ae().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values])if(!(0,U.isUtcTagName)(t)){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,_.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l)}const c=o?(0,X.extractMakeAndModel)(n):await(0,se.inferMakeAndModel)(e,n);c.Make!==(0,X.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ae().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,G.extractExposureSettings)(n),g=await(0,re.extractSizeInfoFromFile)(e,n);if(null==g)return void ae().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,ne.extractTitleDescription)(n),...d,cameraId:(0,H.cameraIdFromTags)(n),imageId:(0,H.imageIdFromTags)(n),lensId:(0,H.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,te.extractRating)(n)};(0,A.isTest)()&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ae().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ae().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(de(e),de(t))},t.readTags=he,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=k.PosixFile.for(e);return ye(t,await ge(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await he(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await ue().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ae().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,ee.extractRotation)(await ge(e,!0))},t.moveOriginal=fe,t.overwriteTags_=async function(e,t){try{await(0,w.time)("exiftool.overwriteTags:"+e,(async()=>{await ue().write(e.nativePath,t,await me(e)),e.clearThisAndParent()}))}catch(i){ae().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await ue().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=me,t.writeTagDest=pe,t.writeTags_=function(e,t,i){return(0,w.time)("exiftool.writeTags:"+e,(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await pe(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=k.PosixFile.for(t),s=(0,f.fromEntries)(i);ae().info("writeTags()",{src:e,dest:t,t:s}),await ue().write(r.nativePath,s,await me(r)),L.Settings.overwriteOriginal.valueOrDefault||await fe(r),r.clearThisAndParent()}}))},t.readRawTags=ge,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ae().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ae().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...L.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,$.isVideoExt)(n.default.extname(e))?[]:["-fast"]],r=await(0,w.time)("exiftool.read()",(()=>ue().read(e,i).catch((t=>{ae().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ae().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,Q.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),oe&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ye},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function _(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function M(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([_(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(_)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=M,t.findInequalFields=function(e,i){const r=M(e),n=M(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),s=i(40958),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),s=i(45599),n=i(68708),a=i(50213),o=(0,s.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,n.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:s}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[s])&&(t[i]=t[s]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,n.pick)(e,"Directory","FileName"));for(const t of(0,n.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),v=i(50213),w=i(81168),b=i(66649),S=i(17415),P=i(29882),_=i(95696),M=i(17217),T=i(28874),E=i(47783);function k(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=k,t.mkHistoryRecord=D,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function A(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,M.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=_.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=A,t.ensureInferredHistoryRecords=async function(e,i,r){const s=k(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?A(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),I(i,s,n)},t.ensureHistoryRecords=I},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(53705)),n=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),w=i(14245),b=i(61424),S=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,w.omitInvalidGeolocationTags)(t);{const e=_(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=M(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function _(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return S().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function M(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,u.toDated)(t[r]);if(null==s||(0,f.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return S().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return S().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=_,t.inferTzOffsetMinutesFromFilename=M},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function _(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function M(e){return Array.isArray(e)&&e.every(M)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(M))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(M))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=_,t.isKeywordStruct=M,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=_(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(M(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},38010:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(50213),g=i(84885),y=i(66649),v=i(98725),w=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function _(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-_(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),s=i(54993),n=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},66039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(75020),u=i(59455),c=i(50213),d=i(68852),h=i(81168),f=i(70417),m=i(28874),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,v=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,w=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,v),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function _(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,w),null!=e&&(_(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const M=(0,s.compactBlanks)(t.split(/\s+/)),T=l.length,E=b.length;if(M.length>0)if(0===T&&E>0)l.push(...M);else if(0===E&&T>0&&1===M.length)b.push(...M);else if(1===M.length)l.push(...M);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?M.pop():M.shift()),l.push(...M)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function _(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function M(e,t,i){return _("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=_([t.modifier,t.lifespan]),r=_(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?_([r,e]):M(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),s=i(54993),n=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),s=i(40958),n=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,s.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},3127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(54993),s=i(42231);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),v=i(79842),w=i(21330),b=i(98725),S=i(51275),P=i(35280),_=i(19748),M=i(88561),T=i(95696),E=i(65238),k=i(17217),D=i(57902),x=i(28874),C=i(80496),F=i(65162),A=i(28544),I=i(47783),O=i(88840),L=i(30748),R=i(16170),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new M.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,_.extFilter)(O.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7,i=!0){if(!await j(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(r,(e=>(0,F.bname)(e))),n=(0,k.findFileIndex)(e,s);if(n<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),q(e,t,!1)):void 0;const l=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[s.slice(n-2*t,n),s.slice(n+1,n+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=H(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),s=i(22573),n=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),s=i(57975),n=i(90595),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(T(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function M(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?M:_;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:_(o,!1)),r}function k(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+k(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=T;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(D)?e.replace(D,(e=>k(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),s=i(40958),n=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),s=i(22573),n=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(9103),a=i(37628);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},50036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=void 0;const r=i(46292),s=i(95696);t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")}},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),s=i(30577);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),s=i(22573),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},27274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.semverGte=t.semverLatest=void 0;const r=i(54993),s=i(48884),n=i(76280),a=i(30577);function o(e){const t=(0,n.toSemver)(e),i=a.UpdateChannels.ordinal((0,a.extractUpdateChannel)((0,r.toS)(e)));return null==t?void 0:[t.major,t.minor,t.patch,i,...t.prerelease.slice(1)]}function l(...e){return(0,s.greatestBy)(e,o)}t.semverLatest=l,t.semverGte=function(e,t){return l(e,t)===e}},38244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateChannelVersion=void 0;const r=i(68708),s=i(51926),n=i(30577);t.isUpdateChannelVersion=function(e){return(0,r.isObject)(e)&&n.UpdateChannels.has(e.channel)&&(0,s.isString)(e.version)}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},63335:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=void 0;const r=i(22573);t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v|ver|version)?\s*/,"version ")}},40044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=t.checkVersion_=t.currentChannel=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(75240),l=i(17344),u=i(50213),c=i(37805),d=i(5916),h=i(46292),f=i(16287),m=i(43205),p=i(28874),g=i(63870),y=i(89372),v=i(50036),w=i(60865),b=i(27274),S=i(38244),P=i(30577),_=i(63335),M=(0,a.defer)((()=>(0,u.mkLogger)("VersionCheck")));t.currentChannel=function(){const e=[p.Settings.updateChannel.valueOrDefault,(0,w.channel)()].map((e=>P.UpdateChannels.ordinal(e))).sort()[0];return P.UpdateChannels.values[e]??p.Settings.updateChannel.valueOrDefault},t.checkVersion_=async function(e){if(p.Settings.noNetwork.valueOrDefault)return{level:"disabled",msg:["PhotoStructure version checking is disabled","Set "+(0,s.tt)(p.Settings.noNetwork.toEnvLine(!1))+" to enable."]};if(!p.Settings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===p.Settings.optOut.value?e.push("Set "+(0,s.tt)(p.Settings.optOut.toEnvLine(!1))+" to enable."):!1===p.Settings.autoUpdateCheck.value?e.push("Set "+(0,s.tt)(p.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.tt)(p.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,h.configDir)();if(null==i||!await(0,f.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const u=e?.installedVersion??c.version,d=(0,P.extractUpdateChannel)(u),m=(0,P.eligibleForChannel)(d),g=a.versions.filter((e=>m.includes(e.channel))).map((e=>e.version)),y=e?.latestVersion??(0,b.semverLatest)(...g);if(null==y)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+p.Settings.updateChannel.toEnvLine()]};const v=(0,P.extractUpdateChannel)(y),w="You are running "+(0,l.EditionName)()+" "+(0,_.ver)(u),S="The latest published "+(0,s.tt)(v)+" build is "+(0,_.ver)(y),M=v===d?void 0:"You should consider switching to the "+(0,s.tt)(v)+" channel.",T=Date.now()-a.updatedAt,E="Last checked "+(T{const e=(0,v.channelVersionsCache)(),i=await(0,y.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",headers:{"User-Agent":await(0,m.userAgent)()},cache:e,ttlMs:n.dayMs,preCacheTransform:e=>({versions:e,updatedAt:Date.now(),updatedByVersion:c.version})}),r=i.data;if(null==r||!Array.isArray(r.versions)||0===r.versions.length||r.versions.some((e=>!(0,S.isUpdateChannelVersion)(e)))||r.updatedByVersion!==c.version){if(i.fromCache)return M().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();M().throw("getChannelVersions_(): Invalid response",{result:r})}return M().tap({msg:"getChannelVersions_()",result:r})}})},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),s=i(9595),n=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},42233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(45200),s=i(98770),n=i(7014);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),s=i(22573),n=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),b=i(24541),S=i(60224),P=i(63870),_=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const M=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(M)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(T(e),(e=>e+":\\"))}function k(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=k,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function A(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function I(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(D)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(A)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=A,t.volumeInfoWin=I},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),b=i(16287),S=i(45969),P=i(43334),_=i(69108),M=i(98770),T=i(44224),E=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const k=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?k().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):k().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(k().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void k().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await D(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,E.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,M.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void k().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),s=i(5233),n=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),_=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),s=i(19851),n=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),b=i(8769),S=i(34102),P=i(17217),_=i(16287),M=i(43334),T=i(28874),E=i(8540),k=i(68884),D=i(44224),x=i(24541),C=i(69375),F=i(63870),A=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function O(e=(0,F.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function L(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{T.Settings.libraryDir.watchLater(I),T.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&T.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(M.isMac&&(e.info("Setting up Mac diskutil activity watcher"),O((0,F.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),M.isLinux){const i=(0,D.maybeWatchProcMounts)();await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),O((0,F.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),O((0,F.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",M.isWin?x.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,F.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(M.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return M.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,S.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),I()})),T.Settings.mountpointsTtlMs.watch(O)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>L(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),L()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!M.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,F.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>L(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),b=i(68884),S=i(59107),P=i(69375),_=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await k()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,b.isGioSupported)())try{await(0,c.thenMap)((0,b.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){_().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function T(e){return!v.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function k(e=M,t=T,i=E){if(y.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return _().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return _().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void _().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=T,t.readProcMounts=k,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(M)?new h.FileWatcher(M,{recursive:!1,persistent:!1},(()=>{_().info("detected change in "+M),(0,d.setUnrefTimeout)((()=>S.mountpoints.refresh()),n.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),s=i(42659),n=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await T()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function M(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,u.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=M;const T=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?M():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(_(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),s=i(12168),n=i(28874);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),b=i(28874),S=i(59107),P=i(63870),_=i(68995),M=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),T=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function E(e){return(0,a.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function k(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=k(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(b.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of b.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),r=await D(i).catch((e=>M().info("Failed to read "+i,{error:e})));if(null!=r)return M().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,_.volumeUuidSubpath)());if("/"===e.mountpoint)return M().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(b.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return M().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(b.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,_.writeVolumeUuid)(e);if(!(0,n.blank)(t))return M().tap({msg:"readVolumeUUID(): wrote new "+(0,_.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return M().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>T.clear())),S.mountpoints.watchLater((()=>T.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(E(e))return;if((0,a.isFalse)(e.ok))return;const t=await T().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>M().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=E,t.toVolumeUUID=k,t.readUuidFile_=D,t.readVolumeUUID=x},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),b=i(50213),S=i(7282),P=i(23560),_=i(28850),M=i(45255),T=i(81168),E=i(56519),k=i(4867),D=i(49776),x=i(9595),C=i(77740),F=i(44198),A=i(96706),I=i(8769),O=i(57159),L=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),j=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),H=i(43334),q=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Y=i(27461),Z=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=s.default.platform(),ne=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,ne),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,x.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ne.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:se}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))n.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:M.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,q.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==q.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function me(e,i){const r=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(r))return;const s=await(0,L.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function pe(e,t,i){const r=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,W.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,T.equalsIgnoreCase)(n,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,S.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,v.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,k.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,O.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if((0,S.isTest)()){const e=(0,p.toInt)((0,F.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeoutError)({p:H.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=q.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeoutError)({p:H.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,Z.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>H.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},89372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=void 0;const r=i(45599),s=i(98553),n=i(31586),a=i(50213),o=i(51140),l=i(4988),u=(0,r.defer)((()=>(0,a.mkLogger)("web.HttpGet")));t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,n.gt0)(await t.size())&&(0,n.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await(0,l.get_)(e.url,{headers:e.headers});o.HttpStatusIs.success(r.statusCode)||u().throw("Failed",{url:e.url,response:r});const a=(0,s.parseJSON_)(r.data),c=e.preCacheTransform?.(a)??a;return u().info("Fetch success. Caching",{args:e,json:c,cache:t}),await t.writeJson_(c),{data:c,updatedAt:Date.now(),fromCache:!1}}},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),h=i(34238),f=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const a=n(i(37067)),o=n(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),h=i(50213),f=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),v=(0,u.defer)((()=>(0,h.mkLogger)("net.get")));async function w(e,t){return b({...t,url:e})}async function b(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?a.request:"https"===t.scheme?o.request:v().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??f.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",h=e?.agent??!1,b=r(t.toString(),{method:c,headers:u,timeout:n,agent:h},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const a={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&y.HttpStatusIs.redirect(a.statusCode)&&!(0,l.blank)(e.headers.location)?(v().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(w(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(v().debug("complete",{...a,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(a))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||b.write(e.body),b.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=w,t.httpRequest_=b},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},14854:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(48161)),h=i(42659),f=i(45599),m=i(55835),p=i(31586),g=i(68708),y=i(19851),v=i(50213),w=i(7282),b=i(78406),S=i(25764),P=i(38835),_=i(74128),M=i(82647),T=i(43334),E=i(28874),k=i(30933),D=i(15674),x=(0,y.lazy)((()=>(0,v.mkLogger)("work.CpuUsage"))),C=(0,y.lazy)((()=>{const e=F.instance().busyPct();(0,_.syncReport)().maybeSystemData({from:"cpuUsage",state:"note",details:"Current system load is too high to schedule more work",meta:(0,g.compactValues)({loadCpuPct:I(),cpuBusyPct:e})}),x().warn("Current system load is too high to schedule more work",{cpuBusyPct:e,max:E.Settings.cpuBusyPercent.valueOrDefault})}),((0,w.isTest)()?15:60)*h.secondMs);t.isTooBusy=function(){if(E.Settings.cpuBusyPercent.valueOrDefault<=0)return!1;const e=F.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(4*E.Settings.cpuBusyPercent.valueOrDefault/3));return(0,p.gte)(e,t)?(C(),!0):(C.unset(),!1)};class F extends b.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,D.singleThreadedMode)()?60:T.isWin?20:10)*h.secondMs,rank:S.EndableRanks.first}),r.add(this),s.set(this,new M.Average(5)),n.set(this,new A),(0,p.mapFinite)(I(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??I()}}t.CpuUsage=F,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,I());const e=new A;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},F.instance=(0,f.defer)((()=>new F));class A{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?(0,p.sigFigs)(t/r*100,3):void x().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+P.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function I(){return T.isWin?void 0:(0,p.sigFigs)(d.default.loadavg()[0]/(0,k.cpuInfo)().length*100,3)}},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),s=i(37692);let n=!1;function a(){return n}function o(e=!0){l(e),(0,s.writeStateFile)({paused:e})}function l(e){e!==n&&(n=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=a,t.pause=o,t.resume=function(){return o(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return a()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),s.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=b,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(b()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(b()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=w();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,v());return t=(0,a.clamp)(1,s,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const s=r(i(78474)),n=i(40958),a=i(76790),o=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),h=i(87290),f=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),v=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let w;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new s.default;let b=0;function S(){const e=(0,h.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-b>o.minuteMs;i&&(b=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(w?.nativePath)||(w?.close(),w=void 0),r&&null!=e&&(w??(w=new f.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=S()?.readJsonSync();for(const i of e?.events??[])_.get(i.e)!==i.ts&&(v().info("emitting event "+i.e),t.stateEvents.emit(i.e),_.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const _=new Map;function M(e){const i=S();if(null==i)v().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),s=function(e){const t=Date.now()-10*o.minuteMs;return(0,n.uniqByLast)((0,a.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:s};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=M,t.addStateEvent=function(e){const t=Date.now();_.set(e,t),M({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),s=i(87997),n=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},75761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),s=i(31586),n=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),s=i(22573),n=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),s=i(73872);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s.hasPrior=()=>r,s}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),s=i(21605),n=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),s=i(68708),n=i(34666),a=i(32639);function o(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,n.isPrimitive)(e)||(0,n.isPrimitive)(t))return e===t;if(!(0,s.isObject)(e)||!(0,s.isObject)(t))return!1;for(const i of(0,s.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),s=i(42659),n=i(55835),a=i(31586),o=i(12168),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),s=i(50357),n=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class s extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=s},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,(t=>!e(i,t,s)));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),s=i(22573),n=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,s){return!(null==s||!o(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,s.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return o(e)&&e>0}function b(e){return o(e)&&e>=0}function S(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function M(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=S,t.map2Numeric=function(e,t,i){return S(e,(e=>S(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,n.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return S(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=M,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return M(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),s=i(30976),n=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),s=i(54993),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),s=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),s=i(68708),n=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let s=!0;const n=setTimeout((()=>{s&&(s=!1,i(a.Timeout))}),t);try{n.unref?.();const t=await e;s&&(s=!1,i(t))}catch(e){s&&(s=!1,r(e))}finally{clearTimeout(n)}}))}async function c(e,t,i=!0){const s=await u(e,t,i);if(s===a.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return s}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?a.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return c(e,s,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,n.tot)(i);const s=await u(e,t,r);return s===a.Timeout?(0,n.tot)(i):s}},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),s=i(30301),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(30301),s=i(54993);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},58939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(55835),s=i(31586);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),s=i(30301),n=i(31586),a=i(97238),o=i(29652);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return n(e)??[]},t.optToA=n},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),s=i(23541),n=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},98401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cancelFileAndProcCleanups=t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=t.maybeCleanup_=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(56519),o=i(76187),l=i(87290),u=i(79267),c=i(32144),d=i(13829),h=i(69734),f=i(95696),m=i(65238),p=i(70257),g=i(13940),y=i(12495),v=i(95402),w=i(28874),b=i(40958),S=i(42659),P=i(31586),_=i(64526),M=i(22526),T=i(69032),E=(0,r.lazy)((()=>(0,s.mkLogger)("library.Cleanup")));async function k(){const e=_.Library.instance();if(null==e)E().info("No library to vacuum.");else{E().info("Running tag and search maintenance...");try{await(0,T.runTagMaintenance)()}catch(e){E().warn("Failed to run tag maintenance",{error:e})}E().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,n.isDbJanitorService)()&&(E().info("Running database maintenance..."),await e.runDbBackup_())}E().info("Cleaning child processes..."),await(v.Pids.instance()?.killOldProcs()),E().info("Cleaning stale and temp files..."),await D(),await(0,a.mapAsync)({name:"fileCleanup",arr:j(),f:e=>e.cleanup()})}t.maybeCleanup_=(0,r.lazy)(k,5*S.minuteMs),t.cleanup_=k;const D=(0,r.lazy)((()=>(0,l.libraryDataDirPosixFile)()?.join("shared-state").rmrf())),x=(0,r.lazy)((()=>u.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:g.imageCacheDir_,staleMs:w.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ImageCacheName)}))),C=(0,r.lazy)((()=>u.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>f.PosixFile.for((0,m.readdirCacheDir)()),staleMs:w.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(m.ReadDirCacheName)}))),F=(0,r.lazy)((()=>u.FileCleanup.for({name:"previewWipCleanup",rootNativePath:l.libraryPreviewsDirPosixFile,staleMs:S.hourMs,isPrunable:e=>(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)}))),A=(0,r.lazy)((()=>u.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:d.defaultFsAdvisoryLockDir,staleMs:S.hourMs,isPrunable:h.isPsLockFileOrDir}))),I=(0,r.lazy)((()=>u.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,P.gt0)(w.Settings.syncReportRetentionCount.valueOrDefault)?(0,l.librarySyncReportsDir)():void 0,staleMs:S.hourMs,isPrunable:e=>(0,p.isWip)(e)||(0,c.isCsvExt)(e)})));function O(e){return(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)||(0,o.isSqliteFile)(e)}const L=(0,r.lazy)((()=>u.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,M.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:S.hourMs,isPrunable:O}))),R=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,M.libraryDbObjects_)().libraryDbBackupDir,staleMs:S.hourMs,minRetained:w.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:O})));async function N(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const B=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:N,staleMs:S.hourMs,minRetained:1,isPrunable:O})));function j(){return(0,b.compact)([x(),C(),F(),A(),(0,y.LogDirCleanup)(),I(),L(),R(),B()])}t.fileCleanups=j,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{v.Pids.instance()?.scheduleInterval();for(const e of j())e.scheduleInterval()})),t.cancelFileAndProcCleanups=function(){t.scheduleFileAndProcCleanups.unset(),v.Pids.instance()?.cancelInterval();for(const e of j())e.cancelInterval()}},64526:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(27395),u=i(25764),c=i(38836),d=i(99331),h=i(45608),f=i(15056),m=i(87290),p=i(38835),g=i(57159),y=i(61704),v=i(95696),w=i(18454),b=i(13940),S=i(48604),P=i(19851),_=i(23560),M=i(28874),T=i(2858),E=i(7014),k=i(63870),D=i(15674),x=i(22573),C=i(38639),F=i(42659),A=i(56409),I=i(68708),O=i(25470),L=i(22526),R=i(41844);class N extends c.EndableWrapper{static instance(){const e=M.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,_.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired_(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new A.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted_(),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted_();const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=M.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;M.Settings.maxConcurrentImports.hasValue()||(M.Settings.maxConcurrentImports.tmpValue=e,(0,D.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted_(),(0,_.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted_(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.previews=(0,P.lazy)((()=>(0,I.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new R.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,_.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.onEnd=(0,P.lazy)((async()=>{if(!(0,d.ending)())for(const{ea:e,t}of[{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,k.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise.then((()=>this))}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup_(){return(await this.dbModelJanitor())?.backup_()}}t.Library=N,r=N,n=new WeakMap,s={value:void 0}},19113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(62105),s=i(181),n=i(94448),a=i(39604);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},56992:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calcVolumesTTL=t.setVolumesTTL=void 0;const r=i(19851),s=i(50213),n=i(76596),a=i(87290),o=i(28874),l=i(2858),u=i(63870),c=i(7014),d=i(42659),h=i(31586),f=i(12168),m=(0,r.lazy)((()=>(0,s.mkLogger)("SetVolumesTTL")));async function p(){if(!(0,l.libraryHasSettings)())return;const e=[],t=await(0,c.volumes)(),i=o.Settings.minDiskFreeGb.defaultValue*f.GB;for(const r of[(0,a.libraryOriginalsDirPosixFile)(),(0,a.libraryPreviewsDirPosixFile)()]){const s=await(0,c.bestVolumeForPath)(r,t);if(null==s)return void m().warn("Can't find volume for "+r+", using default TTL for volumes()");if(s.available(0,l.mkLogger)("library.SuggestedLibraryDir")));class O{static async for(e,t){if((0,x.blank)(e))return;const i=await(0,E.bestVolumeForPath)(e,t);if(null==i)return void I().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:e});const r=await(0,p.isLibraryDir)(e);return new O(e,r,i)}constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=T.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=T.Settings.minDiskFreeGb.valueOrDefault*A.GB){if(this.isLibrary)return;const t=await(0,_.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,S.containsHiddenPathname)(this.nativePath))return I().tap({...i,result:"contains hidden path"});{const e=await(0,b.whyExcludedDirectoryRecursive)(w.BaseFile.for(this.nativePath));if(null!=e)return I().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,v.canRWXFirstExistingAncestor)(this.nativePath)?(0,C.gt0)(e)&&this.availableBytesnew O(e,!1,{mountpoint:"/test",available:A.GB})))});const l=[],d=[],h=await(0,F.thenOrTimeoutMaybe)(i,T.Settings.statTimeoutMs.valueOrDefault)??await(0,F.thenOrTimeoutMaybe)((0,E.volumes)(),T.Settings.statTimeoutMs.valueOrDefault);if(null==h||(0,k.isEmpty)(h))return I().warn("volumes() is empty: they don't get any suggestions."),[];async function v(t){const i=await O.for(t,h);if(null!=i)return i.isLibrary||i.isCurrentLibrary?(I().info("addSuggestion(): path is a library",i),void l.push(i)):void(null==await i.whyExcluded(e)&&d.push(i))}if(await v(T.Settings.libraryDir.value),(0,M.isDocker)())return[...l,...d];await v(await(0,g.picturesDir)());const w=[n.default.cwd(),...await(0,P.childDirectories_)(n.default.cwd())];(0,M.isDocker)()||w.push(...await(0,P.childDirectories_)((0,m.homeDir)())),(0,k.filterInPlace)(w,(e=>(0,S.isNotHiddenPosixPath)(e)));for(const e of w)await(0,p.isLibraryDir)(e)&&(I().info("current working dir is a library",e),await v(e));function b(){return Date.now()-r>c.ShortCommandTimeoutMs-500&&(I().debug("...ran out of time, stopping."),!0)}(0,M.isDocker)()||await v(s.default.join((0,m.homeDir)(),(0,a.AppName)())),await(0,f.mapAsync)({name:"suggestedLibraryDirs.addVolume",arr:h,f:e=>async function(e){try{if(await(0,p.isLibraryDir)(e.mountpoint))return I().info("addVolume(): vol.mountpoint is a library",e.mountpoint),void await v(e.mountpoint);for(const t of await(0,P.childDirectories_)(e.mountpoint)){if(b())break;if(await(0,p.isLibraryDir)(t))I().info("addVolume(): dir is a library",t),await v(e.mountpoint);else for(const i of await(0,P.childDirectories_)(t)){if(b())break;await(0,p.isLibraryDir)(i)&&(I().info("addVolume(): dir is a library",t),await v(e.mountpoint))}}const t=s.default.join(e.mountpoint,(0,a.AppName)());I().info("addVolume(): adding default suggestion",t),await v(t)}catch(t){I().warn("addVolume(): Failed to add suggestion",{err:t,vol:e})}}(e),timeoutMs:c.ShortCommandTimeoutMs}),I().debug("Finished gathering suggestions. Filtering...",{priorLibraries:l,suggestions:d});const _=l;for(const e of(0,D.sortBy)(d,(e=>[-e.availableBytes,-e.nativePath.length]))){if(_.length>=t)break;_.some((t=>t.nativePath===e.nativePath||t.mountpoint===e.mountpoint))||(I().debug("adding new path",e),_.push(e))}return(0,k.uniqBy)((0,D.sortBy)(_,(e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath])),(e=>e.nativePath))}t.SuggestedLibraryDir=O,t.suggestedLibraryDirs=(0,h.lazyAsync)({desc:"library.suggestedLibraryDirs",later:()=>L()}),t._suggestedLibraryDirs=L},77948:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemInformation=t.libraryMetrics=void 0;const r=i(21330),s=i(46296),n=i(17344),a=i(18454),o=i(81674),l=i(66184),u=i(96175),c=i(24540),d=i(23560),h=i(28874),f=i(2858),m=i(84968),p=i(94174),g=i(37805),y=i(14854),v=i(15674),w=i(40958),b=i(22573),S=i(38639),P=i(75240),_=i(55835),M=i(31586),T=i(20214),E=i(51926),k=i(12168),D=i(43487),x=i(54017),C=i(48723);async function F(){if(null==D.Asset.db())return;const e=[];e.push((0,k.plurMetric)(D.Asset.shownCount(),"asset"));const t=x.AssetFile.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,E.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,k.plurMetric)(i.assetFileCount,t+" file"))}return e.push((0,k.plurMetric)(C.Tag.rows(),"tag")),e}t.libraryMetrics=F;const A={pending:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"};t.systemInformation=async function(){const e=await(0,o.b)(),t=e?.l?.tier??"lite",i=a.HealthCheck.summary();return(0,w.compact)([{term:"Version",defn:g.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:A[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,S.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,_.mapOr)(e?.l?.exp,(e=>(0,r.toIsoDate)(e)),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,u.osFullName)()},{term:"CPUs",defn:(0,u.CPUs)()},{term:"System load",defn:(0,_.map)(y.CpuUsage.instance().busyPct(),(e=>(0,M.fmtPct)(e)+" busy"))??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(h.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,v.maxConcurrentImports)()} concurrent imports, ${(0,v.sharpThreadsPerProcess)()} gfx/process)`},(0,d.isWebService)()?{term:"Web uptime",defn:(0,P.fmtDuration)((0,m.runtimeMs)())}:void 0,(0,b.mapNotBlank)((0,c.procDeviceModel)(),(e=>({term:"Device",defn:e}))),{term:"Current user",defn:await(0,p.username)()+((0,M.gte0)((0,p.userid)())?"":" (userid: "+(0,p.userid)()+", groupid: "+(0,p.groupid)()+")")},(0,f.libraryHasSettings)()?{term:"Library path",defn:h.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,await(0,T.thenMap)(F(),(e=>({term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:e}))),{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,l.defaultLogLevel)()}]).filter((({term:e,defn:t})=>(0,b.notBlank)(e)&&(0,b.notBlank)(t)))}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},46628:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(47783),c=i(97573),d=i(42231),h=i(40958),f=i(22573),m=i(68708),p=i(75020),g=i(54993),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function v(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(v));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w},88224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(28874),o=i(42231),l=i(40958),u=i(20214),c=i(43487),d=i(46628),h=i(63175),f=i(4407),m=i(58886),p=i(32646),g=i(48144),y=i(60047),v=i(6186),w=i(42003),b=i(43723),S=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function P({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];if(t=(0,l.uniqBy)([e,...t],(e=>e.nativePath)),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,y.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),a.Settings.tagGeo.valueOrDefault)for(const e of t){const t=await(0,p.geoTagFile)(e);if(null!=t){u.push(t);break}}await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,b.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,g.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,w.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{S().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const P=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(v.normalizeTagRoot),o.joinTagPath)),_=await(0,v.tagDeltas)(i,P);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:P,result:_}),_}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await P({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=P},63175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(47783),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},4407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(47783),h=i(40958),f=i(55835),m=i(31586),p=i(75020),g=i(54993),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function _(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function M(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),_);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),M);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=_,t.dayTagRef=M,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(r.date)}},58886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(19851),s=i(50213),n=i(42231),a=i(21404),o=i(40958),l=i(89937),u=i(75020),c=i(54017),d=i(94448),h=i(69032),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},32646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTagFile=t.geoTag=void 0;const r=i(48884),s=i(56519),n=i(50213),a=i(28874),o=i(47783),l=i(14245),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)((()=>(0,n.mkLogger)("curators.GeoTagger")));function p(e){const t=a.Settings.tagGeoMaxDistanceKm.valueOrDefault;if(t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t))return void m().warn("geoTag(): GeolocationDistance too large, skipping geo tag",(0,f.pickDeep)(e,...l.GeolocationFields));const i=a.Settings.tagGeoSynonyms.synonymMap(),s=a.Settings.tagGeoTemplate.valueOrDefault.map((t=>(0,r.first)(i.get(t)??[t],(t=>(0,f.pluckDeep)(e,t)?.value)))),n=(0,c.compactBlanks)(s);return m().tap({msg:"geoTag",result:0===n.length?void 0:(0,c.compact)([u.TagRoots.Where,...n]),meta:{picked:s}})}t.geoTag=p,t.geoTagFile=function(e){return(0,s.thenMap)((0,o.readTags)(e),p)}},48144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(47783),h=i(97573),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),v=i(96249),w=i(55835),b=i(75020),S=i(54993),P=i(6186),_=i(43723),M=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),T=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return M().tap({msg:"extractDashDashTags()",result:(0,w.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,w.mapOr)(T(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function k(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>T.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=k;const D=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(D,(e=>(i.push(e),"")));s.push(...(0,w.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function F(e,t){const[i,s]=(0,r.partition)(x(e),_.isWhoTag),n=(0,v.flatten)(i.map(_.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return M().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=C,t.processKeywords=F,t.keywordTagFiles=async function(e,t){return F([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(k)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},60047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(56519),s=i(28874),n=i(47783),a=i(75020),o=i(40958),l=i(22573),u=i(55835);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},6186:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhereRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(50213),s=i(28874),n=i(42231),a=i(75020),o=i(40958),l=i(22573),u=i(45599);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.WhereRoot={name:a.TagRoots.Where,ordinal:5},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,t.WhereRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Where,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase()))),g=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhereRoot,...e.slice(1)]:g.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},42003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}t.friendlySubtype=y,t.fixCase=v},43723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(19851),s=i(50213),n=i(28874),a=i(47783),o=i(28630),l=i(66039),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(w)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function v(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function w(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=v,t.nameTag=w},98348:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(48884),d=i(19851),h=i(23560),f=i(25764),m=i(38836),p=i(99331),g=i(5916),y=i(12959),v=i(55332),w=i(91872),b=i(80632),S=i(51040),P=i(44955),_=i(15056),M=i(70025),T=i(57159),E=i(18454),k=i(28874),D=i(5233),x=i(42659),C=i(31586),F=i(68708),A=i(30976),I=i(17036),O=i(27134),L=i(35052);class R extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=x.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),k.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*x.secondMs),this.migrate_=(0,g.lazyAsync)({desc:"db.migrate",later:async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{await(0,O.verifyDb_)((()=>this.db))}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||k.Settings.dbForceRecover.valueOrDefault)&&(E.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new I.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e}}}),this.tableInfo_=(0,d.lazy)((()=>(0,L.localTableInfo)(this.db)))}toJSON(){return(0,F.pick)(this,"schema","dbFile")}get isOpen(){return!0===l(this,n,"f")?.open}get inTransaction(){return this.isOpen&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(t||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,b.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new T.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===k.Settings.dbAutoVacuumMode.valueOrDefault&&(0,C.gt0)(k.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%k.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&(this.logger.info("running incremental_vacuum..."),l(this,n,"f")?.pragma("incremental_vacuum")),l(this,n,"f")}async verify_(){await(0,O.verifyDb_)((()=>this.db))}assertHeartbeat_(){const e=(0,A.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{this.logger.info("closing db",l(this,n,"f")),await(0,D.retryOnReject_)((()=>{!0===l(this,n,"f")?.open&&l(this,n,"f")?.close()}),{timeoutMs:k.Settings.dbBusyTimeoutMs.valueOrDefault,maxRetries:5,errorIsRetriable:M.isSqliteBusyError,retryDelay:x.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,w.handleDbRetries_)("db.checkpoint",(()=>this.db),(()=>(0,O.checkpoint_)({db:this.db})),this.onRetry),await(0,w.handleDbRetries_)("db.optimize",(()=>this.db),(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,w.handleDbRetries_)("db.vacuum",(()=>this.db),(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,O.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,_.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,P.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,y.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,v.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=R,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,C.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},25470:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(66364),d=i(50213),h=i(23560),f=i(78406),m=i(25764),p=i(38836),g=i(99331),y=i(56038),v=i(12959),w=i(55332),b=i(76187),S=i(73209),P=i(28874),_=i(42659),M=i(75240),T=i(95700),E=i(22526),k=i(45648),D=5*_.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends f.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:_.minuteMs,rank:m.EndableRanks.db,endTimeoutMs:5*_.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new p.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),m.EndableRanks.postdb,D),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*_.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,k.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,k.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,y.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,v.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,w.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,M.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:D,endableRank:m.EndableRanks.postdb,noopIfContested:!1});(0,h.isDbManager)()&&await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,b.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),await this.db.closeDb()},o=function(){return this.ended||(0,g.ending)()||(0,c.isSuspended)()}},22526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(19851),s=i(50213),n=i(92407),a=i(55332),o=i(44955),l=i(15056),u=i(87290),c=i(98314),d=i(38835),h=i(73209),f=i(95696),m=i(17217),p=i(18454),g=i(57902),y=i(28874),v=i(2858),w=i(40958),b=i(22573),S=i(42659),P=i(94448),_=i(98348),M=i(45648),T=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function k(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function D(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=D(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,M.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=k,t.libraryDbInfoJsonFile=D,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:k(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new _.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new _.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,M.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,M.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},86859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(54557),s=i(50213),n=i(99331),a=i(56038),o=i(65753),l=i(66184),u=i(70417),c=i(28874),d=i(40958),h=i(22573),f=i(45599),m=i(96249),p=i(31586),g=i(51926),y=i(57038),v=i(21074),w=(0,f.defer)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,y.knex)()(this.tableName)}prep(e,t=!1){const i=(0,v.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return w().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&w().log((0,l.defaultLogLevel)(),i+"(): "+(0,v.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;w().throw(t,{method:i,...(0,v.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,a.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,g.replaceAll)((0,g.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,v.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,m.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}async batched(e){let t,i=0;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,o.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&(await e.onResults(t),i+=t.length)}while((0,d.isNotEmpty)(t)&&!(0,n.ending)()&&(null==e.maxResults||e.maxResults>i));return{resultCount:i,done:null==t||t.length<(0,o.maxBatchPluckSize)()}}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}async pluckBatched(e){let t=0;const i=(0,u.min)([e.limit??(0,o.maxBatchPluckSize)(),e.maxResults]);if(i<=0||(0,p.lte0)(e.maxResults))return{done:!1,resultCount:t};let r;for(;null==e.maxResults||e.maxResults<=0||t(0,o.mkLogger)("db.DbSchemaValid")));function y(e){return l.PosixFile.for(s.default.join(u.ProjectPath.Data(),e+"-schema.json"))}t.schemaJsonFile=y,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,p.localTableInfo)(e.db),i=t.map((e=>e.tableName)),r=(await y(e.schema).readJson_()).tableInfo;{const e=r.map((e=>e.tableName)),t=(0,c.diff)(e,i);(0,c.isNotEmpty)(t)&&g().throw("Db is missing "+(0,f.plur)(t.length,"table")+": "+(0,h.andList)(t))}for(const e of t){const t=r.find((t=>t.tableName===e.tableName));if(null==t)g().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,c.isNotEmpty)(i)&&g().throw("Db is missing "+(0,f.plur)(i.length,"column")+" from table "+e.tableName+": "+(0,h.andList)(i.map((e=>e.name))))}}g().info("Validated schema.",{from:(0,d.shortStack)()})}catch(e){throw(0,m.dbModelHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return y(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",tableInfo:(0,p.localTableInfo)(t)},{spaces:2})}},45648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},36908:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(42231),o=i(40958),l=i(76790),u=i(23838),c=i(31586),d=i(54993),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},57038:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(31832)),n=i(19851),a=i(56519),o=i(55835),l=i(68708);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},17036:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(77598),l=i(19851),u=i(50213),c=i(7282),d=i(37805),h=i(4867),f=i(51040),m=i(77740),p=i(38835),g=i(8769),y=i(57159),v=i(34102),w=i(73209),b=i(95696),S=i(43899),P=i(18454),_=i(28874),M=i(40958),T=i(42659),E=i(41400),k=i(98553),D=i(55835),x=i(34666),C=i(32639),F=i(45648),A=i(94715),I=i(27134);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,A.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,k.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:_.Settings.dbMaintenanceTimeoutMs.valueOrDefault},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=A.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(A.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.info("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),(0,c.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{if((0,m.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,D.map)(e,(e=>e(r))),await(0,h.thenOrTimeoutError)({p:this.applyMigration_(r,i),timeoutMs:5*_.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch((e=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile(),r=(0,f.splitBatchSql)(i);if((0,M.isEmpty)(r))this.logger.info("No-op migration: "+e);else{t&&this.db.pragma("foreign_keys = OFF");for(const t of r)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,I.foreignKeyCheck_)(this.db)}}finally{t&&this.db.pragma("foreign_keys = ON")}}},94715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(97352),o=i(68852),l=i(81168),u=i(85810),c=i(42022),d=i(1971),h=i(79842),f=i(89724),m=i(17415),p=i(88600),g=i(20014),y=i(42231),v=i(87001),w=i(40958),b=i(55835),S=i(31586),P=i(97790),_=i(89937),M=i(54993),T=i(7656),E=i(36908),k=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),D=new RegExp(`^(${(0,o.escapeRegExp)(_.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())k().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)}function A(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>D.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=F,t.isoToPrecisionMs=A,t.Migrations={fix_root_tags:F,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},A),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,M.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();k().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));k().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:T.rebuildTagAssetCounts,create_tag_fts:e=>{e.exec("DROP TABLE IF EXISTS tag_fts"),e.exec("CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize=\"unicode61\");")},rebuild_null_island:e=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,y.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")}}},27134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(14121),s=i(19851),n=i(50213),a=i(84777),o=i(12959),l=i(5531),u=i(91872),c=i(99315),d=i(76187),h=i(51040),f=i(38835),m=i(57159),p=i(29882),g=i(95696),y=i(89966),v=i(38156),w=i(28874),b=i(63870),S=i(5233),P=i(42659),_=i(41400),M=i(50357),T=i(98553),E=i(56409),k=i(31586),D=i(20214),x=i(51926),C=i(12168),F=i(59455),A=i(54993),I=i(94448),O=i(9508),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){L().debug("pragmaOrThrow_()",{db:N(e),db_open:e?.open,pragma:t,okResult:i});const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,M.eql)(r,i)||L().throw(`${t} failed for ${N(e)}: ${(0,T.stringify)({result:r})}`)}function N(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}function B(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function j(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function z(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function V(e){await(0,u.handleDbRetries_)("db.quickCheck",e,B),await(0,_.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",e,j),await(0,_.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",e,z)}function W(e){return(0,O.withDbSync)(e,V,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,k.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,I.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=B,t.integrityCheck_=j,t.foreignKeyCheck_=z,t.verifyDb_=V,t.verifyDbFile_=W,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,F.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,k.gt0)(n?.busy)&&i>0?(await(0,_.delay)(250),e({db:t,retries:i-1})):n};const U=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,A.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,A.toS)(e);U.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),await W(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,D.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,D.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},21074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(48884),s=i(68852),n=i(81168),a=i(12943),o=i(96249),l=i(98553),u=i(31586),c=i(68708),d=i(32639),h=i(54993);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},35052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(22573),s=i(23838);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},9508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(80632),s=i(28874),n=i(30301),a=i(54993);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)((()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i})));try{return t((function(){const e=o();return e.open?e:o.refresh()}))}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const n=(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i});try{return await t(n)}finally{n.close()}}},74085:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelHealthCheck=void 0;const r=i(77740),s=i(98314),n=i(18454),a=i(28874),o=i(82950),l=i(42659),u=i(45599),c=i(64526),d=i(16185),h=i(45648),f=i(31687),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.dbModelHealthCheck=(0,u.defer)((()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library database…",settings:["libraryDir","forceLocalDbReplica"],timeoutMs:()=>10*a.Settings.dbMaintenanceTimeoutMs.valueOrDefault,ttlMs:l.minuteMs,onReset:()=>(0,h.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837"}],later:async()=>{const e=await(c.Library.instance()?.ready);if(null==e)return{level:"disabled",msg:["Library database tests disabled: no library is open"]};let t,i=!1;try{const s=Date.now();if(i=!1,(0,h.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,o.li)((0,h.dbSetupErrors)())],links:[m]};if(t=await e.modelDb(),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await(0,d.assertValidDbSchema_)(t),i=!0,await t.verify_(),await t.vacuum(),f.Heartbeat.assertPing_();const n=await e.dbModelSetup_();return{level:"ok",msg:["Library database is OK",(0,o.li)(["Schema validation, vacuum, optimize, and upsert round-trip took "+(Date.now()-s)+"ms","Live db is "+(0,o.tt)(t.dbFile.nativePath),"Local replica mode is "+(0,o.tt)(n.useReplica),n.useReplica?"Cold library db is "+(0,o.tt)(n.libraryDbFile):void 0])]}}catch(r){return{level:"error",msg:["Library database validation failed",(i?"":"Unrecoverable: ")+(0,s.errorToS)(r),null==t?void 0:"Live db is "+(0,o.tt)(t.dbFile.nativePath),null==e?void 0:"Local replica mode is "+(0,o.tt)(await e.useReplica())],links:i?[m]:void 0}}}});return(0,h.addDbSetupErrorListener)((()=>e.refresh())),e}))},8400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(19851),s=i(88625),n=i(2858),a=i(74085),o=i(1991),l=i(40549);t.libraryHealthCheckSetup=(0,r.lazy)((async()=>{await(0,n.readSettings)(),(0,s.healthCheckSetup)(),(0,o.syncHealthCheck)(),(0,a.dbModelHealthCheck)(),(0,l.volumeUuidHealthCheck)()}))},1991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncHealthCheck=void 0;const r=i(48884),s=i(50213),n=i(95696),a=i(62105),o=i(18454),l=i(2858),u=i(40958),c=i(82950),d=i(45599),h=i(94019),f=(0,d.defer)((()=>(0,s.mkLogger)("health.SyncHealthCheck")));t.syncHealthCheck=(0,d.defer)((()=>o.HealthCheck.for({section:"Library",id:"library-nothing-to-sync",ordinal:99,settings:["scanAllDrives","scanPaths","scanLibraryFirst","scanLibraryLast"],pendingMsg:"Checking synced directories…",later:async()=>{if(!(0,l.libraryHasSettings)())return{level:"disabled",msg:"Library sync paths test disabled: no library is open"};const e=(await(0,h.pathsToSync)()).map((e=>e.nativePath));if((0,u.isEmpty)(e))return{level:"warn",msg:"No paths are configured to scan\n"+(0,c.li)([(0,c.tt)("PS_SCAN_ALL_DRIVES")+" is false",(0,c.tt)("PS_SCAN_PATHS")+" is empty","both "+(0,c.tt)("PS_SCAN_LIBRARY_FIRST")+" and "+(0,c.tt)("PS_SCAN_LIBRARY_LAST")+" are false"]),links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]};{const t=e.map((e=>n.PosixFile.for(e)));return f().info("Checking if any paths are empty",{posixFiles:t}),null==await(0,r.findAsync)(t,(async e=>null!=await e.someDescendant((e=>e.isDirectorySync()||(0,a.acceptParentAndFileAndSimple)(e)),1)))?{level:"warn",msg:["No eligible files found in scanned paths","Checked paths:",(0,c.li)(e.map(c.tt))],links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]}:{level:"ok",msg:["At least one directory with eligible files is configured to be synced","Checked paths:",(0,c.li)(e.map(c.tt))]}}}})))},40549:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=void 0;const r=i(50213),s=i(56519),n=i(18454),a=i(28874),o=i(2858),l=i(85087),u=i(63870),c=i(86848),d=i(7014),h=i(40958),f=i(82950),m=i(45599),p=i(57924),g=i(23838),y=i(68708),v=i(94019),w=(0,m.defer)((()=>(0,r.mkLogger)("health.VolumeUUIDHealthCheck")));t.volumeUuidHealthCheck=(0,m.defer)((()=>n.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumes…",settings:["scanAllDrives"],links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],later:async()=>{if(!(0,o.libraryHasSettings)())return{level:"disabled",msg:"Volume UUID test disabled: no library is open"};const e=[],t=[];if(a.Settings.scanAllDrives.valueOrDefault)e.push(...await(0,d.volumes)());else{const i=await(0,v.scanPaths)(),r=await(0,s.mapAsyncSerial)({name:"scannedVolumes",arr:i.result.map((e=>e.nativePath)),f:e=>(0,d.bestVolumeForPath)(e),timeoutMs:(0,u.commandTimeoutMs)()});e.push(...(0,h.uniqBy)(r,(e=>e.mountpoint))),t.push(...i.noUriPaths)}const i=[...(0,g.groupBy)(e,(e=>e.uuid)).values()].filter((e=>e.length>1)),r=e.filter((e=>null==e.uuid&&!(0,c.volumeUuidNotExpected)(e))).map((e=>e.mountpoint)),n=(await(0,d.volumes)()).filter((e=>!1===e.ok)).map((e=>(0,h.compactBlanks)([e.mountpoint,e.status]).join(": ")));if(w().debug("volumeHealthCheck result",{missingUUIDs:r,noUriPaths:t,unhealthyVolumes:n,scannedVolumes:e.map((e=>(0,y.pick)(e,"uuid","mountpoint")))}),(0,h.isEmpty)(r)&&(0,h.isEmpty)(i)&&(0,h.isEmpty)(t)&&(0,h.isEmpty)(n))return(0,h.isEmpty)(e)?{msg:["No volumes need UUIDs",(0,f.tt)(a.Settings.scanAllDrives.key)+" is false, and no volumes other than the library are configured to be scanned."],level:"ok"}:{msg:["All scanned volume UUIDs are OK",(0,f.li)(e.map((e=>(0,f.tt)((0,l.volsha)(e.uuid)+" → "+e.mountpoint))))],level:"ok"};{const e=[];return(0,h.isEmpty)(n)||e.push("Some volumes are unhealthy",(0,f.li)(n.map((e=>(0,f.tt)(e))))+"PhotoStructure may crash or hang when accessing unhealthy volumes."),(0,h.isEmpty)(r)||e.push("Some volumes are missing UUIDs",(0,f.li)(r.map((e=>(0,f.tt)(e)))),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(i)||e.push("Some volumes have duplicate UUIDs",i.map((e=>(0,f.li)((0,p.andList)(e.map((e=>(0,f.tt)(e.mountpoint))))+" share UUID "+(0,f.tt)(e[0].uuid)))).join("\n---\n"),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(t)||e.push("Some paths failed to have URIs generated",(0,f.li)(t.map((e=>(0,f.tt)(e)))),"This will prevent these paths from being imported."),{level:"warn",msg:e.join("\n---\n"),links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}})))},86801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(93944).install()}catch{}const r=i(98314),s=i(98424);process.on("unhandledRejection",(e=>console.error("UNHANDLED REJECTION",(0,r.errorToS)(e)))),process.on("uncaughtException",(e=>console.error("UNCAUGHT EXCEPTION",(0,r.errorToS)(e)))),(0,s.run)()},64501:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InfoArgs=void 0,t.InfoArgs={beforeParse:e=>e.option("--volumes","Emit a table with currently mounted volume metadata. See https://photostructure.com/volumes for details.").option("--mountpoints","Emit a table with currently mountpoints. See https://photostructure.com/volumes for details.").option("--sync-paths","Emit a table listing the paths that will be synced next.").option("--plan, --licensing","Emit plan/licensing information. See the About page in the web UI for more details or to activate a subscription.").option("--child-env","Emit the environment variables provided to all spawned processes.").option("--validate","Only run file validation on the given filenames (requires current PLUS subscription).").option("-j, --json","Emit metadata as un-indented, uncolorized JSON.").option("--load-library","Load the library database so more metadata can be shown (like if a file is currently in your library). This adds a second or two (depending on the size of your library).").option("--filter ",'Case-insensitively filter keys by . may have dots. Note that .nativePath is always included. Repeat to filter for multiple terms ("--filter foo --filter bar").',((e,t)=>t.concat([e])),[]).option("--file-filters","Include an exhaustive list of file and directory filters. This is hundreds of lines long, so it's not included by default.").option("--image-hash",'Automatically filter image hash fields. Equivalent to "--filter imageHash --filter imageHashComparison"').option("--flat","Only return values for objects with only one field").option("--suggested-libraries","Emit the suggested library directories (as seen on the settings page).").option("--volumes-ttl","Emit the volume cache time-to-live (use with --debug to see details).").option("--is-library ","Run a couple quick checks to see if looks like a PhotoStructure library.").option("--read-settings ","Read the given file and output the parsed settings.").option("--reindex","Rebuild the tag full-text index and recount every asset tag count. This may take a minute or two. Don't have a sync running concurrently. Implies --cleanup.").option("--globs, --exclude-globs","Emit all file and directory exclusion globs.").option("--health","Emit details for all health checks.").option("--doctor","Emit details for all health checks that aren't OK.").option("--skip-health","Disable health checks.").option("--version-check","Check now if the current version is the latest.").option("--table","Emit with console.table() (useful with --volumes or --filter).").option("--cleanup","Run a bunch of maintenance tasks."),afterParse:function(){}}},98424:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.run=void 0;const s=r(i(57975)),n=i(19851),a=i(50213),o=i(88158),l=i(23560),u=i(19913),c=i(83556),d=i(94174),h=i(79184),f=i(79781),m=i(13991),p=i(92434),g=i(45608),y=i(56519),v=i(31562),w=i(9727),b=i(69554),S=i(38790),P=i(53978),_=i(43380),M=i(91655),T=i(15056),E=i(49776),k=i(48195),D=i(87290),x=i(46296),C=i(98314),F=i(8769),A=i(57159),I=i(83278),O=i(92423),L=i(95696),R=i(89966),N=i(63664),B=i(18454),j=i(80361),z=i(181),V=i(34592),W=i(81674),U=i(17181),H=i(43205),q=i(28874),G=i(2858),$=i(32707),J=i(63225),K=i(85087),Y=i(50036),Z=i(40044),X=i(59107),Q=i(63870),ee=i(7014),te=i(14854),ie=i(40958),re=i(22573),se=i(38639),ne=i(42659),ae=i(55835),oe=i(68708),le=i(34666),ue=i(5670),ce=i(12168),de=i(59455),he=i(98401),fe=i(64526),me=i(56992),pe=i(57064),ge=i(77948),ye=i(31503),ve=i(8400),we=i(92244),be=i(64501),Se=i(46854);t.run=async function(){try{await async function(){const e=await new b.CLI(ue.ServiceNames.info,"[FILE...]",["* Omit any filenames to run diagnostics and output system configuration, tooling, and health check information.","* File paths should be absolute or relative to cwd.","* Provide 2 file paths to see why PhotoStructure may consider them variants of the same asset.","* To emit valid JSON, set NO_COLOR=1 or use --json."].join("\n")).add(be.InfoArgs,_.WriteSettingsArg,ye.LogArgs,S.ColorArgs,P.TimingArg).parse();(0,u.setServiceName)("info"),(0,U.setupLogger)();const t=e.opts(),i=(0,ie.uniq)(e.args),r=(0,se.isTrue)(t.flat),g=(0,se.isTrue)(t.table),F=!0===t.reindex;F&&(q.Settings.recountAllTags.envValue=!0);const A=F||(0,se.isTrue)(t.cleanup);(0,se.isTrue)(t.imageHash)&&(t.filter??(t.filter=[]),t.filter.push("imageHash"),t.filter.push("imageHashComparison"));const Pe=(0,se.isTrue)(t.fileFilters),_e=(0,n.lazy)((()=>{if((0,ie.isEmpty)(t.filter))return;const e=(0,de.toA)(t.filter);return r&&i.length<=1||e.unshift("nativePath"),2===i.length&&e.push(...e.map((e=>"a."+e)),...e.map((e=>"b."+e))),e}));function Me(e){e=function(e){const t=_e();return null==t?e:Array.isArray(e)?e.map((e=>(0,oe.pickDeep)(e,...t))):(0,oe.pickDeep)(e,...t)}(e),r&&(e=(0,oe.flattenObject)(e));const i=(0,se.isTrue)(t.json);r&&(0,le.isPrimitive)(e)?console.log(e):i||(0,se.isFalse)(q.Settings.logColor.value)?console.log(JSON.stringify(e,void 0,i?void 0:2)):g?console.table(e):console.log(s.default.inspect(e,{depth:7,colors:!0,maxArrayLength:1024}))}let Te;if((0,u.setServiceName)("info"),(0,se.isTrue)(t.skipHealth)?B.HealthCheck.disableAll(!0):Te=await(0,N.getRemoteHealthSummary)(),(0,re.notBlank)(t.readSettings)){const e=await(0,G.importFileSettings_)(I.BaseFile.for(t.readSettings));return Me({settings:(0,oe.fromEntries)(e.settings.map((e=>[e.name,e.value]))),warnings:e.warnings})}if(await(0,G.readSettings)(),A&&(l.isDbJanitorService.set(!0),q.Settings.logLevel.isUnset()&&(q.Settings.logStdout.envValue=!0,q.Settings.logLevel.envValue="warn",(0,U.setupLogger)())),(0,se.isTrue)(t.versionCheck))return await((0,Y.channelVersionsCache)()?.unlink()),q.Settings.autoUpdateCheck.tmpValueIfUnset=!0,Me(await(0,Z.checkVersion_)());if((0,se.isTrue)(t.globs)||(0,se.isTrue)(t.excludeGlobs)){const e=(0,O.excludeGlobs)();return Me({excludeGlobs:{file:e.file.map((e=>(0,oe.pick)(e,"pattern","desc"))),dir:e.dir.map((e=>(0,oe.pick)(e,"pattern","desc")))}})}if((0,se.isTrue)(t.volumes)){const e=await(0,ee.volumes)();if(null!=e)return Me(e.filter((e=>!0!==e.ignorable)).map((e=>({filesystem:e.filesystem,...e,size:(0,ce.fmtBytes)(e.size),used:(0,ce.fmtBytes)(e.used),available:(0,ce.fmtBytes)(e.available),volsha:(0,K.volsha)(e.uuid)}))));console.error("--volumes failed. Please retry with --info for details.")}if((0,se.isTrue)(t.mountpoints)){const e=await(0,X.mountpoints)();if(null!=e)return Me(e);console.error("--mountpoints failed. Please retry with --info for details.")}if((0,se.isTrue)(t.plan)||(0,se.isTrue)(t.licensing)){const e=(await(0,W.m)())[0],t=(0,ae.map)(e?.l,(t=>({email:t.sub,trial:t.trial,issued_at:t.iat,expires:t.exp,meta:e.meta})));return Me({plan:await(0,W.t)(),current_license:t})}if((0,se.isTrue)(t.suggestedLibraries))return Me(await(0,pe.suggestedLibraryDirs)());if((0,se.isTrue)(t.volumesTtl))return Me({volumesTTL:await(0,me.calcVolumesTTL)()??(0,Q.volumeMetadataTtlMs)()});if((0,se.isTrue)(t.childEnv))return Me((0,w.childEnv)());const Ee=(0,a.mkLogger)("info");if((0,se.isTrue)(t.loadLibrary)||(0,se.isTrue)(t.syncPaths)||A){const e=(0,D.libraryDataDirPosixFile)();if(null==e)return console.error("Error: please set up your library.");if(!await e.isDirectory())return console.error("Error: your library data dir, "+e+", is missing.");Ee.info("Waiting for library to spin up...");const t=fe.Library.instance();try{await(t?.ready)}catch(e){Ee.warn("Failed to spin up library",e)}const i=(0,T.pathToDb)(e,"models");if(!await i.isNonEmptyFile())return console.error("Error: your library database, "+i+" is missing.")}if(A)return await(0,he.cleanup_)(),Me({cleanup:"OK"});if((0,se.isTrue)(t.syncPaths))return Me(await(0,we.syncPathsForUI)());if((0,re.notBlank)(t.isLibrary)){const e=await(0,k.whyNotLibraryDir)(t.isLibrary);return Me((0,oe.compactValues)({isLibrary:null==e,why:e}))}if((0,se.isTrue)(t.validate)){if((0,ie.isEmpty)(i))throw new Error("--validate requires filenames");return q.Settings.validateVideos.envValue=!0,q.Settings.validateJpegImages.envValue=!0,q.Settings.validateRawImages.envValue=!0,Me(await Promise.all(i.map((async e=>[e,(0,re.notBlankOr)(await(0,z.whyInvalidFile)(e),"OK")]))))}if((0,ie.isEmpty)(i)){await(0,v.until)((()=>te.CpuUsage.instance().busyPct()),{timeoutMs:2*ne.secondMs,intervalMs:250});const e={systemInfo:(0,oe.fromEntries)((await(0,ge.systemInformation)()).map((({term:e,defn:t})=>[(0,c.asObjectKey)(e),t])))};return e.versionCheck={userAgent:await(0,H.userAgent)(),...await(0,Z.checkVersion_)().catch((e=>({error:(0,C.errorToS)(e)}))),currentChannel:(0,Z.currentChannel)()},e.user_ids=(0,d.userids)(),e.group_ids=(0,d.groupids)(),e.username=await(0,d.username)(),e.paths={libraryDir:q.Settings.libraryDir.valueOrDefault,originalsDir:(0,D.libraryOriginalsDirPosixFile)()?.nativePath,systemSettingsFile:(0,$.systemSettingsFile)(),librarySettingsFile:(0,G.librarySettingsFile)()?.nativePath,libraryPreviewsDir:(0,D.libraryPreviewsDirPosixFile)()?.nativePath,librarySyncReportsDir:(0,D.librarySyncReportsDir)()?.nativePath,cacheDir:(0,E.cacheDir)(),logDir:(0,x.logDir)(),toolsDir:(0,R.toolsDir)()?.nativePath,osToolsDir:(0,R.osToolsDir)()?.nativePath,ffmpeg:await(0,V.ffmpegNativePath)(),sqlite:await(0,R.sqliteNativePath_)().catch((e=>"not found: "+(0,C.errorToS)(e)))},(0,se.isTrue)(t.health)?(e.healthSummary=await(0,N.getLocalHealthSummary)(),e.healthChecks=await Promise.all(B.HealthCheck.testResults())):(0,se.isTrue)(t.doctor)?(await(0,ve.libraryHealthCheckSetup)(),e.healthChecks=await B.HealthCheck.notOkResults()):e.healthSummary=Te??await(0,N.getLocalHealthSummary)(),e.wrongPsEnvValues=(0,J.verifyPsEnvSettings)(),(0,se.isTrue)(t.loadLibrary)&&(e.libraryMetrics=(0,oe.fromEntries)((await(0,ge.libraryMetrics)())?.map((e=>[(0,c.asObjectKey)(e.desc),e.count]))??[]),e.libraryDb=(0,oe.omit)(await(fe.Library.instance()?.dbModelSetup_()),"db","fslock")),e.volumesTTL=(0,M.fmtFullDuration)(await(0,me.calcVolumesTTL)()),e.nonDefaultSettings=(0,oe.fromEntries)((0,oe.values)(q.Settings).filter((e=>e.hasValue())).map((e=>[e.name,e.humanValue]))),Me(e)}if(2===i.length){const e=L.PosixFile.for(i[0]),t=L.PosixFile.for(i[1]),r=await(0,m.mkAssetFile_)(e),s=await(0,m.mkAssetFile_)(t),n=[];if(null==r&&n.push("Failed to read "+e),null==s&&n.push("Failed to read "+t),(0,ie.isNotEmpty)(n))return Me({errors:n});const a=(0,f.whyNotSimilarAssetFile)(r,s),l=null==a?"These two files will be aggregated into a single asset.":"These files represent different assets: "+a;let u,c;if(null==a){const e=(0,p.sortAssetFiles)([r,s]);u=e[0]?.nativePath,c=(0,o.zipPojos)(...await Promise.all(e.map(p.assetFileSortCriteriaPojo)))}const d={fileComparison:l,primary:u,a:await(0,Se.info)(e,Pe),b:await(0,Se.info)(t,Pe),cmpArr:c};return q.Settings.useImageHashes.valueOrDefault&&(d.imageHashComparison=(0,oe.omit)((0,j.compareImageHashes)(r,s),"a","b")),Me(d)}{const e=await(0,y.mapAsync)({name:"info",arr:i,f:e=>(0,Se.info)(e,Pe)}),t=(0,oe.fromEntries)(e?.map(((e,t)=>[t,e])));if(e.length>1){const e=(0,ie.compact)(await(0,y.mapAsync)({name:"mkAssetFile",arr:i,f:e=>(0,m.mkAssetFile_)(L.PosixFile.for(e)).catch((t=>{console.error("Failed to read "+e,t)}))})),r=await(0,h.aggregateAssetFiles)(e);t.clusters=r.map((e=>e.map((e=>e.uri))))}return Me(t)}}()}catch(e){(0,F.onError)((0,A.toWrappedError)("Failed",{cause:e,fatal:!0}))}finally{await(0,g.exit)({reason:"done",status:0})}}},46854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.info=void 0;const r=i(50213),s=i(88158),n=i(13991),a=i(92434),o=i(85434),l=i(98314),u=i(92423),c=i(32144),d=i(95696),h=i(62105),f=i(17217),m=i(181),p=i(66106),g=i(78984),y=i(4936),v=i(47783),w=i(16170),b=i(54979),S=i(22573),P=i(42659),_=i(45599),M=i(68708),T=i(20214),E=i(64526),k=i(19113),D=i(88224),x=i(54017),C=i(94448),F=i(3996),A=(0,_.defer)((()=>(0,r.mkLogger)("info.InfoImpl")));t.info=async function(e,t){try{const i=d.PosixFile.for(e),r=await(0,b.readMimeType)(i);if(null==r)return{nativePath:i.nativePath,error:`Could not read mimetype for ${i.nativePath}`};if((0,c.isSidecarMimetype)(r))return{nativePath:i.nativePath,mimetype:r,error:"Skipping sidecar mimetype"};if(!await(0,w.isAssetFileMimeType)(i))return{nativePath:i.nativePath,mimetype:r,error:"Skipping non-asset file mimetype"};const l=i.parent();A().throwIfAborted_();const f=await(0,n.mkAssetFile_)(i),_=t?await g.Predicates.explain(l,...(0,u.notExcludedDirPredicates)(l)):void 0,I=t?await g.Predicates.explain(i,...(0,k.libraryFileFiltersFor)(i,{validateFile:!0})):void 0,O=f.dominantColors?.filter((e=>null!=e?.color?.name)).map((e=>({rgb:e.rgbhex,name:e.color?.name,pct:e.pct}))),L=await(0,D.tagAsset)({primaryVariation:i,files:[],priorTagPaths:[],capturedAts:[],uris:[await i.uri_()]}),R=null==(0,C.modelDb)()?void 0:await new F.AssetFileFinder(i).prior(),N=await(R?.matchesFile()),B=await(0,T.thenCollect)(x.AssetFile.sameShaInLibrary(i),(e=>e.getNativePath()));A().throwIfAborted_();const j=await(0,v.readTags)(i),z=j?.capturedAt,V=(0,h.whyRejectFile)(i,!0===E.Library.instance()?.isReadySync()?(0,k.libraryFileFiltersFor)(i):void 0),W=(0,M.compactValues)({...(0,o.omitModeData)(f),capturedAtRaw:z?.rawValue,...(0,M.pick)(j,"tz","tzSource","errors","inferred","duration"),dirFilters:_,dominantColors:O,fileFilters:I,needsTranscoding:await(0,p.needsTranscoding)(i),pathsInLibrary:B,pathToLibraryAsset:(0,y.pathToLibraryAsset)((0,P.localToDate)(f.capturedAtLocal),i),priorAssetFile:R?.toJSON(),priorIsInSync:N,sidecars:(await i.existingSidecars()).map((e=>e.base)),tagResult:L,validFile:(0,S.notBlankOr)(await(0,m.whyInvalidFile)(i.nativePath),"OK"),variantSortCriteria:(0,a.assetFileSortCriteriaPojo)(f),whyExcludedDirectoryRecursive:await(0,u.whyExcludedDirectoryRecursive)(l),whyRejected:V});return(0,M.compactValues)({nativePath:i.nativePath,mimetype:r,...(0,s.sortedKeys)(W)})}catch(t){return{nativePath:(0,f.toNativePath_)(e),error:(0,l.errorToS)(t)}}}},43487:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(48884),c=i(19851),d=i(50213),h=i(88158),f=i(45393),m=i(56519),p=i(89724),g=i(38835),y=i(74128),v=i(79847),w=i(28874),b=i(47783),S=i(38010),P=i(40958),_=i(76790),M=i(75761),T=i(38639),E=i(11371),k=i(98553),D=i(55835),x=i(31586),C=i(20214),F=i(59455),A=i(64526),I=i(4407),O=i(54017),L=i(48722),R=i(37094),N=i(45295),B=i(39604),j=i(48723),z=i(41507),V=i(72761),W={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class U extends V.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,b.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,T.isTrue)(t.shown)})}const t=R.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(W):e.andWhere(W)}static findUnhiddenById(e){return(0,x.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return A.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{unlinkAssetFiles:i});const l=n.getAssetFiles({refresh:!0});if(t){(0,B.upsertToShaBlockslist)(...l.map((e=>e.sha)));for(const e of l)(0,y.syncReport)().onProgress({from:"Asset.remove",path:await e.getNativePath()??e.uri,state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}N.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),R.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&j.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,v.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(N.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,x.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,x.gte)(this.rating,w.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,L.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:j.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,P.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return j.Tag.ops().all(j.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??N.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:j.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:j.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,P.uniq)((0,F.toA)(e.tagIdsToAdd).filter((e=>(0,x.gt0)(e)&&!t.includes(e)))),r=(0,P.uniq)((0,F.toA)(e.tagIdsToRemove).filter((e=>(0,x.gt0)(e)&&t.includes(e))));if((0,P.isEmpty)(i)&&(0,P.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&j.Tag.deltaAssetCountAndAncestors(t,-1),(0,P.isEmpty)(i)||N.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,P.isEmpty)(r)||N.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,P.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&j.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,z.coalesceStreams)((0,P.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,_.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,T.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,x.gt0)(this.id)&&(0,x.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,k.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,T.isTrue)(e.shown)))??this.getAssetFiles({refresh:!0})?.find((e=>(0,T.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,E.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,F.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,x.gte)(this.rating,w.Settings.likeRating.valueOrDefault),hidden:(0,T.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=U,s=U,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("Asset.version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},U.$tableName="Asset",U.$uniqueColumnName="id",U.$booleanFields=["shown","hidden"]},54017:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(76760),o=i(19851),l=i(88158),u=i(45393),c=i(68852),d=i(81168),h=i(13991),f=i(54296),m=i(56519),p=i(76490),g=i(89724),y=i(98314),v=i(38835),w=i(8769),b=i(29882),S=i(95696),P=i(62105),_=i(74128),M=i(35721),T=i(69589),E=i(28874),k=i(28544),D=i(16170),x=i(45200),C=i(34238),F=i(87001),A=i(42233),I=i(21404),O=i(40958),L=i(17586),R=i(22573),N=i(38639),B=i(42659),j=i(33374),z=i(50357),V=i(75240),W=i(11371),U=i(55835),H=i(31586),q=i(68708),G=i(34666),$=i(89937),J=i(75020),K=i(64526),Y=i(41844),Z=i(43487),X=i(48723),Q=i(94710),ee=i(72761);class te extends ee.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>C.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=Z.Asset.shownUnhidden(e.q).join("AssetFile","AssetFile.assetId","Asset.id").where("AssetFile.version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("AssetFile.updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("AssetFile.mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("AssetFile.uri",i+"%");return t})).orderBy("AssetFile.id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,A.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,A.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("AssetFile.id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,H.gt0)(e)?te.ops().first(Z.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Z.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,R.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(te.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=te.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=te.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:te.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,q.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith($.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,q.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,U.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,F.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,H.closeTo)(i.mtime,this.mtime,2*B.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return E.Settings.forceSync.valueOrDefault?E.Settings.forceSync.key+"=true":this.version!==u.AssetFileVersion?"AssetFileVersion: "+this.version+" != "+u.AssetFileVersion:this.whyNotMatchesFile(e)}async inSyncWithFile(e){const t=await this.whyNotInSyncWithFile(e);return this.logger().tap({msg:"inSyncWithFile()",result:null==t,meta:{whyNotInSync:t}})}async fileFields_(e){const t=e??await this.posixFile_();return null==t?void 0:await(0,h.assetFileStatFields_)(t)}isInLibrary(){return this.uri.startsWith($.PS_LIBRARY_PROTOCOL)}async isNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){const t=await this.whyNotNoop(e);return this.logger().tap({msg:"isNoop()",result:null==t,meta:{whyNotNoop:t}})}async whyNotNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){if(!0===e.forceSync)return"forceSync is true";if(!(0,H.gt0)(this.id))return"missing .id";if(!(0,H.gt0)(this.assetId))return"missing .assetId";{const e=await this.whyNotInSyncWithFile();if(null!=e)return e}if(await(0,Y.mayCopyAssetsToLibrary)()){const e=K.Library.instanceRequired_().assetFileRepository(),t=e.whyNotCopyFile(await this.posixFile_());if((0,R.blank)(t)&&null==await e.existingLibraryAssetFile(this))return"need to copy into library"}this.syncState=_.AssetFileSyncStates.noop}isVersionUpToDate(){return(0,G.gte)(this.version,u.AssetFileVersion)}async siblingCount(){return te.dbl.pluckFirstf((e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=(0,T.forceContextOrSetting)()){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,H.gt0)(this.id)&&!t.forceSync)return void(null==this.syncState&&(this.upsert(),this.syncState??(this.syncState=_.AssetFileSyncStates.noop)));const i=await this.isFileDeleted();if(!0===i)return this.syncState=_.AssetFileSyncStates.deleted,this.delete(),!0!==t.skipAssetRepair&&Q.Task.addOne("repairAsset",{assetId:this.assetId}),this;if(!1===i){const i=await this.updateFromFile_(e,t);return this.syncState??(this.syncState=null==i?_.AssetFileSyncStates.noop:_.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=_.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,q.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e,t=(0,T.forceContextOrSetting)()){const i=Date.now(),r=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&!0!==t.forceSync&&await this.matchesFile(e))return void r.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=_.AssetFileSyncStates.deleted,void r.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,R.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,q.assignAllFields)(this,(0,q.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=_.SyncFileStates.synced,r.elapsed("finished",Date.now()-i,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,q.assignFields)(this,(0,q.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...te.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,H.gt0)(this.assetId)?Z.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,x.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,R.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,F.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,R.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,R.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),k.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,M.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,j.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,N.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===W.ReducerNames.fit)).map((e=>(0,M.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=C.URI.parse(this.uri),t=(0,U.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=C.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,L.at)((0,L.at)(e,-1)?.tagPath,-1)}(0,z.eql)(e[0]?.tagPath,[J.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===$.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,L.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===J.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===$.PS_LOCAL_FILE_SCHEME){const t=C.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,q.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,N.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:ie(this.createdAt),updatedAtLocale:ie(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function ie(e){return(0,U.map)(e,(e=>(0,V.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=te,r=new WeakSet,s=function(){if((0,R.blank)(this.uri))return"blank uri";if((0,R.blank)(this.sha))return"blank sha";if(!(0,H.gt0)(this.width))return"missing width";if(!(0,H.gt0)(this.height))return"missing height";if(!(0,H.gt0)(this.capturedAtLocal))return"missing capturedAtLocal";if(!(0,H.gte0)(this.capturedAtPrecisionMs))return"missing capturedAtPrecisionMs";if(E.Settings.useImageHashes.valueOrDefault){const e=[];for(const t of["dctHash","diffHash","meanHash"])(0,R.blank)(this[t])&&e.push(t);if(1===e.length)return"missing image hash: "+e[0];if(e.length>1)return"missing image hashes: "+e.join(", ")}return this.isVersionUpToDate()?void 0:"outdated version"},te.$tableName="AssetFile",te.$uniqueColumnName="uri",te.$booleanFields=["shown"],te.$transientFields=["nativePath","syncState"]},48722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(76596),s=i(31586);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},37094:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},45295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},61204:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(19851),s=i(50213),n=i(97352),a=i(75020),o=i(4407),l=i(48723),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},31687:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(38835),s=i(42659),n=i(31586),a=i(72761);class o extends a.TimestampedModel{static ping(e){return o.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){if(null==o.db())throw new Error("no library is open"+r.NoLibraryErrorFlag);try{o.ping(e);const t=o.ops().findOneBy({name:e});if(null==t||t.name!==e||(0,n.lt)(t.updatedAt,Date.now()-20*s.secondMs))throw new Error("Heartbeat row wasn't inserted")}finally{try{o.dbl.runf((t=>t.delete().where({name:e})))}catch{}}}}t.Heartbeat=o,o.$tableName="Heartbeat",o.$uniqueColumnName="name",o.$useCache=!1},95700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(19851),s=i(56038),n=i(28874),a=i(42659),o=i(41400),l=i(69032),u=i(61204),c=i(49796);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h());try{await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())}catch{}};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},55046:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(57975),n=i(50213),a=i(7282),o=i(65211),l=i(40958),u=i(38639),c=i(45599),d=i(31586),h=i(68708),f=i(34666),m=i(54993),p=i(57038),g=i(94448),y=i(33572),v=i(63872);class w{constructor(){this.$instanceId=(0,a.isTest)()?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if((0,a.isProd)())throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}update(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("update()",{self:this.toJSON()}),this.class().ops().updateOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},94448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},33572:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(50213),s=i(40958),n=i(22573),a=i(38639),o=i(97790),l=i(51926),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},63872:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(48884),m=i(19851),p=i(50213),g=i(81168),y=i(48299),v=i(12943),w=i(38835),b=i(34102),S=i(28874),P=i(40958),_=i(76790),M=i(22573),T=i(50357),E=i(96249),k=i(98553),D=i(55835),x=i(31586),C=i(68708),F=i(59455),A=i(86859),I=i(33572);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,I.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new A.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,k.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,k.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,D.mapOr)(this.db(),(e=>e.isOpen),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,_.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,k.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,D.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,k.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,M.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,M.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);if(null==s)return;return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,k.stringify)(e))}reload(e){const t=[],i=this.allf((i=>{for(const r of e){const e=this.model.hasId(r)?this.model.pickId(r):this.$pickModelUcn(r);null!=e?(t.push([r,e]),i=i.orWhere(e)):h(this,s,"f").warn("reload(): given insufficient partial model",{fragment:r})}return i})),n=[];for(const[e,a]of t){const t=i.find((e=>(0,T.eqlSubset)(a,e)));if(null==t)h(this,s,"f").warn("reload(): failed to find result in db",{prior:e,dbArr:i});else{const i=h(this,r,"m",u).call(this,e);h(this,r,"m",l).call(this,i,t),i!==e&&h(this,r,"m",l).call(this,i,t),n.push(t)}}return n}upsert(e){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const t=this.columnNames(),i=[];for(const s of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=new Map,n=new Set,a=(0,P.compact)(s.map((e=>this.fromJSON(e))));for(const t of a){const i=(0,k.stringify)(this.$pickModelUcn(t));e.set(i,t),this.model.hasId(t)||n.add(i),t.$beforeUpsert()}h(this,r,"m",c).call(this,a.map((e=>e.$toDbJSON(t))));const o=this.reload(a),l=new Map(o.map((e=>[(0,k.stringify)(this.$pickModelUcn(e)),e])));for(const e of a){const t=(0,k.stringify)(this.$pickModelUcn(e)),r=l.get(t)??e;n.has(t)&&r.$afterInsert(),r.$afterUpsert(),i.push(r)}}return i}delete(e){const t=(0,F.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,k.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},20958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(19851),s=i(50213),n=i(88158),a=i(99331),o=i(70025),l=i(8769),u=i(22573),c=i(98553),d=i(50989),h=i(72761);t.OperationNames=(0,d.strEnum)("rebuildLibrary","forceRestartSync");const f=(0,r.lazy)((()=>(0,s.mkLogger)("model.Operation")));class m extends h.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(m.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return m.getFirstPendingOp(e)??m.ops().insertOne(e)}static getFirstPendingOp(e){return f().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,u.blank)(e?.name)?f().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return f().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce_(e,t,i=n.identity){const r=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=r)return void f().debug("applyOnce(): already done",{priorCompleted:r});const s=this.ops().insertOne(e);try{const e=await t(s);return(0,a.ending)()||s.markCompleted(),e}catch(t){if((0,o.isRedoableError)(t))return void f().info("applyOnce(): redoable error",{crit:e,error:t});throw(0,l.onError)("Operation.applyOnce(): "+(0,c.stringify)(e),t),t}}markCompleted(){null==this.completedAt&&(this.completedAt=Date.now(),this.upsert())}}t.Operation=m,m.$tableName="Operation",m.$uniqueColumnName="id",m.$useCache=!1},49796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.toPct=void 0;const r=i(48161),s=i(1708),n=i(48884),a=i(50213),o=i(28874),l=i(40958),u=i(42659),c=i(45599),d=i(98553),h=i(55835),f=i(31586),m=i(68708),p=i(67478),g=i(51926),y=i(59455),v=i(54993),w=i(76386),b=i(33572),S=i(55009),P=i(72761),_=(0,c.defer)((()=>(0,a.mkLogger)("model.Progress")));function M(e){return null==e||!(0,f.isNumber)(e)||e<0||e>100?void 0:(0,f.sigFigs)(e,3)}t.toPct=M;const T=(0,g.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function E(){const e=o.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*u.dayMs}t.defaultMinCreatedAt=E;class k extends P.TimestampedModel{static vacuum(e=o.Settings.progressRetentionDays.valueOrDefault*u.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t)));for(const e of(0,n.batches)(i,o.Settings.dbBatchSelectSize.valueOrDefault))S.ProgressMeta.dbl.runf((t=>t.whereIn("progressId",e).delete())),k.dbl.runf((t=>t.whereIn("id",e).delete()))}static countCompletedDirectorySyncs(){return this.dbl.pluckFirstf((e=>e.where({state:"done"}).whereNotNull("completedAt").where("uri","like","ps%")))}static times(){return _().tap({msg:"times()",result:this.dbl.all({sql:T})})}static insertNew(e){const t=(0,h.map)(e.dek,d.stringify);return this.ops().insertOne({...(0,m.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&this.assignFromPojo(e),super.upsert()}$beforeUpsert(){super.$beforeUpsert(),null==this.id&&(this.pid??(this.pid=s.pid),this.hostname??(this.hostname=(0,r.hostname)())),"done"===this.state&&(this.completedAt??(this.completedAt=Date.now())),this.completePct=M(this.completePct),this.incompletePct=M(this.incompletePct),this.scanningPct=M(this.scanningPct)}$afterUpsert(){super.$afterUpsert(),(0,w.tellWebProgressUpdated)()}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,l.compactBlanks)((0,p.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,d.stringify)((0,l.compactBlanks)((0,y.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,m.omit)(e,"volume","uri"))}getMeta(){return S.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncomplete(e=E()){return this.logger().tap({msg:"priorIncompleteProgress()",result:k.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc")))})}getLastCompletedAt(e=E()){return k.dbl.pluckFirstf((t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e)))}getLastIncompleteStartAt(){return k.dbl.pluckFirstf((e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0)))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),S.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,l.diff)(t.map((e=>e.name)),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),S.ProgressMeta.ops().upsert((0,m.entries)(e).map((([e,t])=>({progressId:this.id,name:e,value:(0,v.toS)(t)})))),(0,l.isNotEmpty)(i)&&S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).whereIn("name",i).delete()))}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),S.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,m.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=k,k.$tableName="Progress",k.$uniqueColumnName="id"},55009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},39604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(19851),s=i(50213),n=i(95696),a=i(40958),o=i(22573),l=i(86859),u=i(94448),c=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),d=(0,r.lazy)((()=>new l.DbRequest(u.modelDb,"ShaBlocklist")));function h(e){return null!=(0,u.modelDb)()&&!(0,o.blank)(e)&&c().tap({msg:"isShaBlockslisted",result:null!=d().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}function f(...e){if(null==u.modelDb.prior())return;const t=(0,a.uniq)(e).map((e=>({sha:e})));return(0,a.isEmpty)(t)?void 0:d().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,u.modelDb)())return null;const t=h(await n.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=h,t.upsertFileToShaBlockslist=async function(e){if(null==(0,u.modelDb)())return;const t=await n.PosixFile.for(e).sha();return null==t?void 0:f(t)},t.upsertToShaBlockslist=f},48723:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(56038),o=i(34102),l=i(19851),u=i(50213),c=i(36372),d=i(97352),h=i(28874),f=i(81168),m=i(42231),p=i(75020),g=i(40958),y=i(22573),v=i(42659),w=i(41400),b=i(50357),S=i(55835),P=i(31586),_=i(34666),M=i(20214),T=i(51926),E=i(59455),k=i(12168),D=i(6186),x=i(57038),C=i(21074),F=i(7656),A=i(43487),I=i(48722),O=i(45295),L=i(98784),R=i(41507),N=i(72761),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:A.Asset.dbl.pluckFirst(A.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset(),this.ops().clearDbCache()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{r.clear();for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.update({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.RecursiveAssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),this.ops().upsertOne(i)}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return A.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,M.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();return(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)})),r.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(A.Asset.dbl.all(t).map(I.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return A.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,k.fmt)(e.length)+" of ")+(0,k.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.RecursiveAssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?A.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(A.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(I.toAssetId))));for(const t of r)t.assetIdA.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(this.id??0),"Asset.id",i)).limit(t))).map(I.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!0,z.cmp=(e,t)=>(0,_.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=A.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(D.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e}),B);const V=(0,l.lazy)((()=>A.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},98784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(38156),s=i(3127),n=i(40958),a=i(41400),o=i(94715),l=i(55046),u=i(48723);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=new r.PushProgressObserver({op:"Rebuilding tag search index"},u.Tag.dbl.pluckFirstf((e=>e.count("*")))),t=this.dbl.db();o.Migrations.create_tag_fts(t.db),await u.Tag.ops().batched({qb:e=>e,onResults:t=>(this.$logger().throwIfAborted_(),this.insertFts(t),e.incrProgress(t.length),(0,a.delay)(1))}),e.completed()}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},41507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},94710:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Task=t.StaleTaskError=t.InvalidTaskError=t.TaskNames=t.Tasks=t.testTask=void 0;const c=i(78474),d=i(22454),h=i(23560),f=i(12089),m=i(76740),p=i(22911),g=i(99331),y=i(31562),v=i(38835),w=i(70025),b=i(8769),S=i(74128),P=i(28874),_=i(37692),M=i(40958),T=i(22573),E=i(42659),k=i(45599),D=i(98553),x=i(49769),C=i(68708),F=i(50989),A=i(59455),I=i(58723),O=i(34274),L=i(90901),R=i(61989),N=i(93755),B=i(69032),j=i(55046);t.testTask=(0,f.shim1)({name:"testTask",impl:async e=>{}}),t.Tasks={applyDeleted:I.applyDeleted,applyExcluded:I.applyExcluded,runTagMaintenance:B.runTagMaintenance,updateAssetFile:N.updateAssetFile_,repairAsset:async function(e){e.forceSync=!0,e.skipPreviews=!0,e.skipAssetTagging=!0;const t=await(0,R.updateAsset_)(e);return(0,M.isNotEmpty)(t?.assetIdsToUpdate)&&H.add(t?.assetIdsToUpdate.map((t=>({fn:"repairAsset",args:{...e,assetId:t},priority:W.repairAsset+1})))),null!=t&&!0!==t.deleted&&(0,T.blank)((0,A.toA)(t.rejected).join(""))&&(0,T.blank)(t.error)&&H.addOne("assetPostUpsertTasks",(0,C.omit)(e,"skipPreviews","skipAssetTagging")),t},assetPostUpsertTasks:L.assetPostUpsertTasks,syncFile:O.importFileToResult_,testTask:t.testTask},t.TaskNames=(0,F.strEnum)(...(0,C.keys)(t.Tasks));class z extends Error{}t.InvalidTaskError=z;class V extends Error{}t.StaleTaskError=V;const W={applyDeleted:16,applyExcluded:16,runTagMaintenance:14,updateAssetFile:13,repairAsset:12,assetPostUpsertTasks:10,syncFile:0,testTask:-1},U=["repairAsset"];class H extends j.Model{constructor(){super(...arguments),r.add(this),o.set(this,(0,k.defer)((()=>new m.Abortable)))}static countTaskNames(){const e={};for(const t of s.dbl.allf((e=>e.select("fn").count().groupBy("fn"))))e[t.fn]=t["count(*)"];return e}static orderBy(e){return e.orderBy([{column:"priority",order:"desc"},{column:"retries",order:"desc"},{column:"id",order:"asc"}])}static count(){return s.dbl.pluckFirstf((e=>e.count("id")))}static freeSlots(){return P.Settings.taskListCap.valueOrDefault-s.count()}static countByFn(e){return s.dbl.pluckFirstf((t=>t.where({fn:e}).count("id")))}static nextByFn(e,t=(e=>e)){return s.ops().allf((i=>s.orderBy(t(i.where({fn:e})))))}set args(e){this.argsJSON=(0,D.stringify)(e)}get args(){const e=(0,D.parseJSON)(this.argsJSON);return(0,C.notEmptyObj)(e)&&(e.halt=u(this,o,"f").call(this)),e}get isSerial(){return U.includes(this.fn)}toString(){return`Task#${this.fn}(${this.argsJSON})`}static addOne(e,t){return s.add([{fn:e,args:t}])[0]}static add(e,t=!1){if((0,M.isEmpty)(e))return[];const i=s.ops().upsert(e.map((e=>({fn:e.fn,argsJSON:(0,D.stringify)(e.args)})),t));return s.ee.emit("added",i),(0,h.isTaskListManager)()||(0,_.addStateEvent)("checkTasks"),i}$beforeUpsert(){this.priority??(this.priority=W[this.fn]),this.retries??(this.retries=P.Settings.maxRetries.valueOrDefault)}donePromise(){return(0,h.isTaskListManager)()?(0,x.getOrSet)(u(s,s,"f",n),this.id,(()=>new p.Deferred(this.toString(),{payload:this}))):(0,y.untilTrue)((()=>null==s.ops().findById(this.id)),{intervalMs:E.secondMs})}abort(e){this.logger().warn("aborting task",{reason:e,task:this}),u(this,o,"f").call(this).abort(e),this.delete(),(0,T.blank)(this.args.path)||(0,S.syncReport)().onProgress({path:this.args.path,from:this.fn,state:S.SyncFileStates.failed,details:e})}async _run(){if(this.retries<0)throw this.logger().warn(".run(): too many retries"+v.InternalErrorFlag,{job:this}),this.delete(),new z;if(!u(this,r,"m",l).call(this))throw this.logger().warn(".run(): someone already started this task",{job:this}),new V;try{const e=Date.now(),i=await t.Tasks[this.fn](this.args);return this.logger().throwIfAborted_(u(this,o,"f").prior()),s.taskResolvedCounts.incr(this.fn),s.ee.emit("resolved",this,i,Date.now()-e),this.delete(),u(s,s,"f",n).get(this.id)?.resolve(i),i}catch(e){if((0,g.ending)())throw this.logger().info("task failed, but we're ending. We'll leave it for next time.",{task:this}),e;throw s.taskRejectedCounts.incr(this.fn),(0,w.isRedoableError)(e)?(this.retries++,this.priority--,this.upsert()):!0===(0,w.isRetriableError)(e)&&this.retries>=0?this.logger().warn("run failed, but we can retry it later",{task:this,error:e}):(s.ee.emit("rejected",this,e),this.delete(),u(s,s,"f",n).get(this.id)?.reject(e),(0,b.onError)(this.toString()+" failed",e)),e}finally{u(s,s,"m",a).call(s)}}}t.Task=H,s=H,o=new WeakMap,r=new WeakSet,a=function(){for(const[e,t]of u(this,s,"f",n).entries())t.isSettled&&u(this,s,"f",n).delete(e)},l=function(){const e=this.retries;if(1===s.dbl.runf((t=>t.where({id:this.id,retries:e}).update({retries:e-1}))).changes)return--this.retries,!0;{const e=this.toJSON(),t=this.reload();return this.logger().warn(".#decrRetries(): someone already started this task",{before:e,reloaded:t}),!1}},H.$tableName="Task",H.$uniqueColumnName="fn,argsJSON",H.$useCache=!1,H.taskResolvedCounts=new d.CountingSet,H.taskRejectedCounts=new d.CountingSet,H.ee=new c.EventEmitter,n={value:new Map}},72761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),this.createdAt??(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},58723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyExcluded=t.applyDeleted=void 0;const r=i(50213),s=i(43487),n=(0,r.mkLogger)("ops.ApplyRemovable");async function a(e,t,i){const r=e?"Deleting":"Excluding",a=e?"deletedAt":"excludedAt";await s.Asset.dbl.batched({qb:e=>e.select("id").where("shown",0).andWhere(a,"<=",t),onResults:async t=>{for(const a of t){n.throwIfAborted_(i);try{await s.Asset.remove({assetId:a,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){n.error(r+" failed",{assetId:a,error:e})}}}})}t.applyDeleted=function(e){return a(!0,e.createdAt,e.halt)},t.applyExcluded=function(e){return a(!1,e.createdAt,e.halt)}},76386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)((()=>(0,s.mkLogger)("progress.Progress")));t.ProgressRateMs=(0,r.lazy)((()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:1.5))),t.tellWebProgressUpdated=(0,r.lazy)((async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch((e=>h().warn(".tellWebProgressUpdated: failed",{error:e})))}),(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},3996:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const a=i(19851),o=i(50213),l=i(79781),u=i(56519),c=i(56038),d=i(59189),h=i(38835),f=i(95696),m=i(48368),p=i(181),g=i(69589),y=i(28874),v=i(28544),w=i(47783),b=i(87001),S=i(40958),P=i(76790),_=i(22573),M=i(42659),T=i(55835),E=i(31586),k=i(43487),D=i(54017);t.isFileInSync=async function(e){return new C(f.PosixFile.for(e)).alreadySynced()};const x=new d.SerialLaterQueue;class C{constructor(e,t=(0,g.forceContextOrSetting)()){this.file=e,this.ctx=t,r.set(this,void 0),this.rejectedAssetIds=new Set,this.rejectedSiblingIds=new Set,this.alreadySynced=(0,c.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>n(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,c.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new D.AssetFile).updateFromFile_(this.file);return null==e?n(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,a.lazy)((async()=>{const e=await(0,w.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,a.lazy)((()=>y.Settings.useImageHashes.valueOrDefault?(0,m.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,a.lazy)((()=>(0,u.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,a.lazy)((async()=>{const e=await this.capturedAt_();return n(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,c.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,_.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return n(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await x.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return n(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new k.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,c.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,p.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtAndImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,c.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return n(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;n(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw n(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),s(this,r,(0,o.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f")}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),n(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}n(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(e=this.file){const t=await e.uri_();if(null!=t)return D.AssetFile.ops().firstf((e=>e.whereIn("uri",[...(0,b.uriEncodingVariants)(t),this.file.fileuri()])));n(this,r,"f").warn("byUri() uri is null",{file:e})}async assetByNormalizedPathUri(){const e=await this.file.normalize();return e.nativePath===this.file.nativePath?void 0:(await this.byUri(e))?.getAsset()}async assetBySha(){const e=await this.file.sha_();return k.Asset.findFirstByFile((t=>(t=t.where("AssetFile.sha",e),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds))),this.rejectedSiblingIds.size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),t)))}async assetByCapturedAtAndImageHash(){const e=await this.capturedAt_();if(null==e)return n(this,r,"f").throw("Cannot import, capturedAt is null"+h.InternalErrorFlag);if(y.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(D.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=y.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=D.AssetFile.query();return(0,E.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(M.secondMs,y.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,c.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)n(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(y.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void n(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const a=await this.dominantLabhashes();if((0,S.isNotEmpty)(a)){const t=e.localBoundaries({delta:4*s});if(null==t)n(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",a).orWhereIn("mode1",a).orWhereIn("mode2",a))));if(null!=e)return e}}const o=this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash));if(null!=o)return o;if(y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const r={};for(let e=0;e0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds)));const i=await this.firstSimilarAsset(D.AssetFile.ops().all(t));return null!=i&&n(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const s=(0,P.sortBy)(e.filter((e=>!this.rejectedSiblingIds.has(e.id)&&!this.rejectedAssetIds.has(e.assetId))),(e=>[(0,T.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of s)if(null!=e){await e.getNativePath();const i=D.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const s=(0,l.whyNotSameAsset)(t,e,i);if(null==s)return n(this,r,"f").info("Found sibling AssetFile",e),k.Asset.ops().findById(e.assetId);this.rejectedSiblingIds.add(e.id),n(this,r,"f").debug("Contemporary assetFile not similar: "+s,e?.uri)}}}t.AssetFileFinder=C,r=new WeakMap},34274:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult_=void 0;const u=i(19851),c=i(50213),d=i(73568),h=i(38835),f=i(95696),m=i(62105),p=i(74128),g=i(181),y=i(69589),v=i(28874),w=i(40958),b=i(22573),S=i(38639),P=i(59455),_=i(64526),M=i(19113),T=i(94710),E=i(3996),k=i(90901);t.importFileToResult_=async function(e){const t=_.Library.instanceRequired_();return(0,p.syncReport)().wrap_({path:e.path,from:"AssetFileImporter",fn_:()=>new D(f.PosixFile.for(e.path),t.assetFileRepository(),e).apply_()})};class D{constructor(e,t,i){r.add(this),this.file=e,this.repo=t,this.start=Date.now(),s.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else if(this.ctx.forceFilters||null==await this.prior()){const t=await(0,m.whyRejectFile)(this.file,(0,M.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,s,"f").throwIfAborted_();const i=await this.prior();if((0,w.isNotEmpty)(e)&&null!=i&&(l(this,s,"f").info("Deleting prior AssetFile",{rejected:e,prior:i}),i.delete(),this.ctx.skipAssetRepair?l(this,s,"f").info("Skipping asset repair",{assetId:i.assetId}):(l(this,s,"f").info("Scheduling asset repair",{assetId:i.assetId}),T.Task.addOne("repairAsset",{assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)}))),null!=i){const t=i.getAsset();null!=t?.deletedAt&&e.push("Asset is marked as deleted"),null!=t?.excludedAt&&e.push("Asset is marked as excluded")}if(l(this,s,"f").throwIfAborted_(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,b.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,s,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,s,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,s,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,r,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,s,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new E.AssetFileFinder(e,this.ctx),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=D,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(){l(this,s,"f").throwIfAborted_();const e=await l(this,s,"f").tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if((0,w.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,s,"f").throwIfAborted_();const t=await l(this,s,"f").tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,s,"f").throwIfAborted_();const i=await l(this,s,"f").tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return l(this,s,"f").throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return l(this,s,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,s,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,s,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;await l(this,s,"f").tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault}),l(this,s,"f").throwIfAborted_();try{o=await(0,k.assetPostUpsertTasks_)({asset:a,...this.ctx})}catch(e){e instanceof d.AbortError?l(this,s,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,s,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:r,assetFile:i,asset:a,uri:n,uris:[n,...(0,P.toA)(o?.newAssetFileUris)]}}},41844:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(50213),c=i(74128),d=i(81674),h=i(57902),f=i(4936),m=i(28874),p=i(47783),g=i(14245),y=i(67083),v=i(16170),w=i(54979),b=i(98604),S=i(40958),P=i(22573),_=i(98553),M=i(68708),T=i(89937),E=i(59455),k=i(54017),D=i(94710);t.mayCopyAssetsToLibrary=async function(){return m.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,u.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!0!==m.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,d.l)())return"no active subscription";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(m.Settings.libraryDir.valueOrDefault))return e+" already contained by "+m.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,m.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,E.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(k.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),D.Task.addOne("repairAsset",{assetId:t,forceSync:!0})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,_.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return a.addAssetFile(d),(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,p.readCapturedAt)(e),i=(0,f.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,p.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,p.readTags)(e);if(null!=i){if(m.Settings.writeGeolocationTagsToLibraryCopies.valueOrDefault){const e=(0,g.geolocationToXmp)(i);(0,M.isEmptyObj)(e)||await(0,p.writeTags_)(t,e)}return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred)}this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},90901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const r=i(50213),s=i(92434),n=i(73568),a=i(99331),o=i(39250),l=i(38835),u=i(57159),c=i(48604),d=i(66106),h=i(69589),f=i(40958),m=i(45599),p=i(23838),g=i(31586),y=i(64526),v=i(88224),w=i(43487),b=i(41844),S=i(68640),P=(0,m.defer)((()=>(0,r.mkLogger)("sync-file.AssetPostUpsertTasks"))),_=(0,m.defer)((()=>new o.LastOneInWins("Asset tasks")));async function M(e){const t=e,i=e,r=(0,g.toGt0)(t.asset?.id)??(0,g.toGt0)(i.assetId);if(null==r)throw new Error("assetPostUpsertTasks_(): unexpected null assetId"+l.InternalErrorFlag);const o=(0,h.forceContextOrSetting)(e),m=P().addContext(`.postUpsertAssetTasks_(Asset:${r})`);if(m.abortable=o.halt,o.skipPreviews&&o.skipAssetTagging)return void m.info("skipped (skipPreviews && skipAssetTagging)");const M=t.asset??w.Asset.ops().findById(r);if(null==M)return m.throw("unexpected null asset",{asset:M});try{return await _().enqueue({key:r,abortable:m.abortable,fn:()=>async function(e,t,i){const r=(0,h.forceContextOrSetting)(i),n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted_(),(0,f.isEmpty)(a)&&(await w.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,b.mayCopyAssetsToLibrary)())for(const[t,i]of(0,p.groupBy)(a,(e=>e.sha)).entries()){e.throwIfAborted_();try{for(const r of i)r.isInLibrary()&&await r.exists()&&e.debug("no-op for file SHA: already in library.",{sha:t,uri:r.uri});for(const e of i)if(await e.exists()){const t=await y.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,r);if(null!=t){o.newAssetFileUris.push(t.uri);continue}}}catch(r){e.warn("Failed to copy variation to library, but we'll try to continue",{sha:t,uris:i.map((e=>e.uri)),error:r})}}e.throwIfAborted_();const l=r.skipPreviews?void 0:await(0,S.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...r}),u=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?P().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,s.bestExistingAssetFile)(e.getAssetFiles())}(t,l);if(null==u)return e.throw("null primaryOrShownAssetFile_()",{asset:t});const m=await u.posixFile_();if(!0!==r.skipPreviews&&t.isVideo()){if(null==m)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});o.transcoded=null!=await(0,d.transcode_)(m,c.Previews.instance().ap(n).mp4(),{force:r.forceRebuildPreviews,halt:r.halt})}return e.throwIfAborted_(),t.markShownAndUpsert_(u),r.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,v.tagAndUpsertAsset_)(t),o}(m,M,{...e,...o})})}catch(e){if(e instanceof n.AbortError)return void m.warn("aborted, next caller will clean up my mess",{error:e});const t=[e];if(!(0,a.ending)()){m.error("failed, marking asset unshown",{error:e});try{M.markUnshownAndUpsert()}catch(e){m.error("failed to mark asset unshown",{upsertError:e}),t.push(e)}}throw new u.WrappedError("Failed to post-process assset "+M.id,{causes:t})}}t.assetPostUpsertTasks=function(e){try{return M(e)}catch(e){if(e instanceof n.AbortError)return void P().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=M},61989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset_=t.updateAsset=void 0;const r=i(48884),s=i(50213),n=i(45393),a=i(79184),o=i(79781),l=i(92434),u=i(56519),c=i(70417),d=i(69589),h=i(28874),f=i(40958),m=i(22573),p=i(38639),g=i(50357),y=i(43487),v=i(54017),w=i(3996),b=i(90901);async function S(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,r=(0,s.mkLogger)(`sync-file.UpdateAsset(${i})`);r.abortable=t.halt;const S=y.Asset.ops().findById(i);if(null==S)return r.throw("no such asset");const _=S.getAssetFiles({refresh:!0});if((0,f.isEmpty)(_))return r.warn("No asset files: deleting."),S.delete(),{asset:S,rejected:"Empty asset (no AssetFiles)"};const M=S.$clone(),T=S.getShown()?.$clone();for(const e of _)r.throwIfAborted_(),await e.upsertIfNeeded_(void 0,t);_.some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&S.clear(),await P(r,_);const E=(0,l.sortAssetFiles)(_),k=E?.[0];if((0,f.isEmpty)(E)||null==k)return r.warn("No existing files. Skipping for now."),S.markUnshownAndUpsert(),{asset:S,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!k.isVersionUpToDate())return r.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:k}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${k.id}, could not be updated. Un-showing Asset:${i}`};const D=await k.capturedAt();if(null==D)return r.warn("Best file failed to extract a captured-at",{bestAcceptedAF:k}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${k.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const x=new Set,[C,F]=await(0,u.partitionAsync)(E,(e=>(0,o.isSimilarAssetFile)(e,k)));if(r.throwIfAborted_(),(0,f.isNotEmpty)(F)){const e=await(0,a.aggregateAssetFiles)(F);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});x.add(e.id);for(const i of t)e.addAssetFile(i);v.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),r.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function A(e){return(0,f.uniq)(C.map((t=>t[e])))}const I=await Promise.all(C.map((e=>e.capturedAt()))),O=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,L=I.map((e=>e?.localBoundaries({delta:O}))),R=(0,c.min)(L.map((e=>e?.start)))??D.localBoundaries({delta:O})?.start,N=(0,c.max)(L.map((e=>e?.end)))??D.localBoundaries({delta:O})?.end,B=v.AssetFile.ops().all(v.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${k.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",A("sha")),null==R||null==N?r.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:R,endBoundary:N}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[R,N]),e.orWhereIn("AssetFile.meanHash",A("meanHash")).orWhereIn("AssetFile.diffHash",A("diffHash")).orWhereIn("AssetFile.dctHash",A("dctHash"))))));if(r.throwIfAborted_(),h.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const e=await k.posixFile();if(null==e)r.info("bestAcceptedAF has no posixFile, cannot expand query for fuzzy dates",{bestAcceptedAF:k});else{const i=new w.AssetFileFinder(e,t);for(const e of[...C,...B])i.rejectedAssetIds.add(e.assetId),i.rejectedAssetIds.add(e.id);let s=h.Settings.maxContemporaryAdoptionAssets.valueOrDefault;for(;--s>0;){r.throwIfAborted_();const e=await i.assetByCapturedAtAndImageHash();if(null==e){r.info("allowFuzzyDateImageHashMatches(): no additional assets found to adopt");break}if(r.info("allowFuzzyDateImageHashMatches(): found asset with similar image",{a:e}),null!=e){i.rejectedAssetIds.add(e.id);for(const t of e.getAssetFiles())r.info("found asset file by fuzzy date and image hash",{uri:t.uri,assetId:e.id}),B.push(t),i.rejectedAssetIds.add(t.id)}}}}r.info("asset file candidates for adoption: ",B.map((e=>e.posixPathFromGrandparent)));const j=[];for(const e of B){r.throwIfAborted_();try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,k)&&(r.info("adopting similar asset file",{af:e}),x.add(e.assetId),e.shown=!1,S.addAssetFile(e),e.upsert(),j.push(e))}catch(t){r.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}}r.info("fetched expansion",{retainAFs:C.map((e=>e.id)),rejectAFs:F.map((e=>e.id)),externalAssetFiles:B.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:j.map((e=>e.posixPathFromGrandparent))}),await P(r,[...C,...j]),t.skipPreviews&&t.skipAssetTagging?(r.info("skipping previews and tagging",t),S.upsert()):await(0,b.assetPostUpsertTasks_)({...t,asset:S});const z=!(0,g.eql)(M,S),V=!(0,g.eql)(T,S.getShown()),W=!(z||V||t.forceRebuildPreviews||t.forceSync);return r.tap({msg:"updateAsset() result",level:"info",result:{asset:S,assetIdsToUpdate:Array.from(x),assetFiles:S.assetFiles,skipped:W},meta:{ctx:t,assetChanged:z,primaryAssetFileChanged:V}})}async function P(e,t){const[i,s]=(0,r.partition)(t,(e=>e.isVersionUpToDate()));for(const t of s){e.throwIfAborted_();const r=i.find((e=>e.sha===t.sha));if(null!=r){e.info("backfilling",{sibling:r,dest:t});const i=await t.updateFromShaSibling_(r);null!=i&&i.upsert()}}}t.updateAsset=async function(e){try{const t=await S(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}},t.updateAsset_=S},93755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t.updateAssetFile_=t.updateAssetFile=void 0;const r=i(50213),s=i(92434),n=i(98314),a=i(74128),o=i(69589),l=i(87001),u=i(40958),c=i(22573),d=i(68708),h=i(43487),f=i(54017),m=i(94710);async function p(e){const t=Date.now(),i=e,s=e,n=s.af?.id??i.assetFileId,u=(0,r.mkLogger)(`updateAssetFile(${n})`),d=s.af??f.AssetFile.ops().findById(n);if(null==d)return u.throw("db record not found",{assetFileId:n});const h=await d.posixFile_(),p=(0,o.forceContextOrSetting)(e),v={id:n,assetFileId:n,path:h?.nativePath,uri:d?.uri};if(null==h){const e=["cannot resolve URI"];return(0,c.blank)(d.mountpoint)||e.push("is "+d.mountpoint+" mounted?"),(0,a.syncReport)().onProgress({path:d.uri,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:e.join(": "),state:a.SyncFileStates.skipped}),{...v,error:"file for URI not found"}}const w=await(h?.isDeletedUri(d.uri));if(null==w)return u.info("no-op: file URI points to an unmounted volume",v),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:((0,c.toNotBlank)(d.mountpoint)??"volume")+" is not currently mounted",state:a.SyncFileStates.skipped}),{...v,skipped:!0};const b=e.whyReject??await d.whyRejected();if(w||!(0,c.blank)(b)){const e={...v,rejected:b,deleted:w};return u.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:w?"file no longer exists":"rejected: "+b,state:a.SyncFileStates.deleted}),d.delete(),!0!==p.skipAssetRepair&&m.Task.addOne("repairAsset",{assetId:d.assetId}),e}const S=await h.uri_();if(!await(0,l.uriIsEquivalent)(S,d.uri)){const e=await g(d,S,p);if(null!=e)return{...v,...e}}return!p.forceSync&&await d.matchesFile()?(u.info("no-op: file already matches db record",v),d.touch(),{...v,skipped:!0}):{...v,...await y(d,p)}}async function g(e,t,i){const n=(0,r.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,u.uniq)([...(0,l.uriEncodingVariants)(e.uri),...(0,l.uriEncodingVariants)(t)]);n.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const o=f.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,u.isNotEmpty)(o)){n.warn("Found other AssetFiles with equivalent URIs.",{afIds:o.map((e=>e.id))});const t=[e,...o],r=(0,s.sortAssetFiles)(t);if((0,u.isEmpty)(r))return n.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,d.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const l=t.map((e=>e.id));for(const e of r)if(await e.exists()){f.AssetFile.dbl.runf((t=>t.whereIn("id",l.filter((t=>t!==e.id))).delete()));const r=y(e,i);return h.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,u.uniq)(t.map((e=>e.assetId)))))),r}}n.info("no-op, no duplicate URIs.")}async function y(e,t){const i=Date.now();return null!=await e.upsertIfNeeded_(void 0,t)&&h.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:await e.getNativePath(),elapsedMs:Date.now()-i,from:"updateAssetFileIfNeeded()",state:e.syncState??a.SyncFileStates.unknown}),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await p(e)}catch(t){return{id:e.assetFileId,...e,error:(0,n.errorToS)(t)}}},t.updateAssetFile_=p,t.handleAssetFileUriChange=g,t.updateAssetFileIfNeeded=y},68640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const r=i(99331),s=i(38835),n=i(48604),a=i(50213),o=i(69589),l=i(87001),u=i(40958),c=i(45599),d=i(50357),h=i(31586),f=i(68708),m=i(59455),p=i(43487),g=(0,c.defer)((()=>(0,a.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,m.toA)(e.assetFiles).find((e=>(0,h.gt0)(e.assetId)))?.assetId,i=(0,o.forceContextOrSetting)(e),a=g().addContext(".Asset:"+t);if(i.skipPreviews)return void a.warn("skipPreviews is true: no-op");if(!(0,h.gt0)(t))return a.throw("invalid assetId",{assetId:t});const c=e.asset??p.Asset.ops().findById(t);if(null==c)return a.throw("Asset:"+t+" not found");a.throwIfAborted_(i.halt);try{const e=await c.getExistingAssetFiles();if((0,u.isEmpty)(e))return void a.warn("no existing assetFiles",{asset:c});const r=n.Previews.instance().ap(t),o=await r.readInfo();a.throwIfAborted_(i.halt);const h=await(0,n.buildAssetPreviews_)({...i,assetId:t,assetFiles:e}),m=e.find((e=>e.id===h?.assetFileId))??e.find((e=>(0,l.uriIsEquivalent)(h?.uri,e.uri)));a.info("buildAssetPreviews_()",{result:h,primaryAssetFile:m});const p=await(m?.posixFile_());if(null==m||null==p||!0!==await(p?.exists()))return a.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:h,assetFiles:e.map((e=>(0,f.pick)(e,"id","uri"))),primaryAssetFile:m,primaryPosixFile:p});const g=(0,d.eql)(o,h),y=null==h||g;return{...h,noop:y}}catch(e){throw(0,r.ending)()||(a.warn("Failed to update previews. Un-showing asset "+t,{error:e}),c.markUnshownAndUpsert()),e}}},94019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(87290),o=i(34102),l=i(16287),u=i(45969),c=i(43334),d=i(28874),h=i(45200),f=i(69375),m=i(7014),p=i(41400),g=i(31586),y=i(92244),v=i(46832);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const w=(0,r.lazy)((async()=>{const e=[];for(const t of await(0,m.volumes)()){if(!0===t.ignorable||!1===t.ok||(c.isMac||(0,u.isDocker)())&&"/"===t.mountpoint||(0,f.isExcludedMountpoint)(t.mountpoint)||!(0,g.gt0)(t.size))continue;const i=await(0,v.toUriPath)(t.mountpoint,(0,h.nativePath2uri)(t.mountpoint,t));null!=i&&e.push(i)}return e}));async function b(){const e=[],i=[],r=d.Settings.argvScanPaths.toNotEmpty()??d.Settings.scanPaths.values;for(const s of r)if(await(0,l.isReadableDirectory)(s)){const r=await(0,v.toUriPath)(s);null==r?(e.push(s),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",s)):i.push(r)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",s);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,p.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];if(d.Settings.argvScanPaths.isNotEmpty()){for(const i of d.Settings.argvScanPaths.values){const r=await(0,v.toUriPath)(i);null!=r?e.push(r):(0,t.logger)().warn("pathsToSync(): Ignoring scanPath element: failed to create URI path",i)}return e}e.push(...(await b()).result),!0===d.Settings.scanAllDrives.value&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:d.Settings.libraryDir.valueOrDefault,originalsDir:d.Settings.originalsDir.value})));d.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),d.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},98622:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runTimeIsStale=t.SyncCron=void 0;const r=i(1708),s=i(17415),n=i(28874),a=i(41400),o=i(30301),l=i(31586);t.SyncCron=(0,o.lazy)((()=>{const e=n.Settings.syncCronTZ.valueOrDefault??(0,s.toValidIanaZone)(r.env.TZ);return n.Settings.syncCron.cron(null==e?void 0:{timezone:e})})),(0,a.later)((()=>{n.Settings.syncCron.watchLater((()=>t.SyncCron.unset())),n.Settings.syncCronTZ.watchLater((()=>t.SyncCron.unset()))})),t.runTimeIsStale=function(e){return null==e||(0,l.lte)((0,t.SyncCron)().nextRun(new Date(e))?.getTime(),Date.now())}},92244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.isStale=t.bestPathToSync=t.stalePathsToSync=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(23560),o=i(22277),l=i(87290),u=i(57902),c=i(28874),d=i(40958),h=i(76790),f=i(42659),m=i(75240),p=i(31586),g=i(20958),y=i(49796),v=i(94019),w=i(98622),b=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));t.nativePathBlocklist=new o.TTLSet(10*f.minuteMs);const S=10*f.minuteMs;async function P(){const e=await(0,v.pathsToSync)(),t=c.Settings.forceSync.valueOrDefault?[]:await y.Progress.times();return b().tap({msg:"pathsAndTimesToSync()",level:u.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}function _(e,t){return null==e.lastStartedAt||null==e.lastCompletedAt||(0,p.lte)(e.lastStartedAt,t)||(0,w.runTimeIsStale)(e.lastCompletedAt)}function M(){return g.Operation.getFirstPendingOp({name:g.OperationNames.forceRestartSync})}async function T(e){const t=M(),i=t?.createdAt,s=e.filter((e=>_(e,i)));if((0,d.isEmpty)(s))return(0,a.isSyncService)()&&t?.markCompleted(),b().tap({msg:"bestStable(): No stale paths to sync!",level:"info",result:void 0,meta:{arr:e,forceRestartOp:t}});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,p.gt)(e.lastUpdatedAt,Date.now()-10*f.minuteMs))return b().tap({msg:"bestStable(): returning most recently updated",level:"info",result:{...e,why:"recently updated"}})}const n=(0,r.leastBy)(s,(e=>[e.lastStartedAt??0,e.lastCompletedAt??0]));return b().tap({msg:"bestStable(): returning least-recently-started or least-recently-completed:",level:"info",result:null==n?void 0:{...n,why:"least recently started or completed"},meta:{stale:s}})}function E(e,t){return null==e.lastStartedAt?"new":null==e.lastCompletedAt?"todo":(0,p.gt)(e.lastUpdatedAt,Date.now()-f.minuteMs)?"syncing":_(e,t)?"stale":"synced"}function k(e){return null==e?void 0:new Date(e).toISOString()}function D(e){if(null==e)return;const t=Date.now()-e;return t<2*f.secondMs?"just now":(0,m.fmtDuration)(t)+" ago"}t.pathsAndTimesToSync=P,t.stalePathsToSync=async function(){const e=await P(),t=M(),i=t?.createdAt,r=e.filter((e=>_(e,i)));return(0,h.sortBy)(r,(e=>[null!=e.lastUpdatedAt&&Date.now()-Se.nativePath)),t=await T(e),i=(0,l.libraryOriginalsDirPosixFile)()?.nativePath,r=M()?.createdAt;return e.map((e=>({path:e.nativePath,library:i===e.nativePath,status:E(e,r),isNext:e.nativePath===t?.nativePath,lastStartedISO:k(e.lastStartedAt),lastStarted:D(e.lastStartedAt),lastCompletedISO:k(e.lastCompletedAt),lastCompleted:D(e.lastCompletedAt)})))}},46832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.posixFileToUriPath=t.toUriPath=void 0;const r=i(53265),s=i(45200),n=i(22573),a=i(68708),o=i(54993);async function l(e,t){if((0,a.isObject)(e)&&!(0,n.blank)(e.nativePath)&&!(0,n.blank)(e.uri))return e;const i=(0,r.resolve)((0,o.toS)(e)),l=await t??await(0,s.nativePath2uri)(i);return null==l?void 0:{nativePath:i,uri:l.toString()}}t.toUriPath=l,t.posixFileToUriPath=function(e){return l(e.nativePath,e.uriObject_())}},7656:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.DirectAssetCountForTagQuery=t.RecursiveAssetCountForTagQuery=t.nonLeafTagIds=void 0;const r=i(50213),s=i(56038),n=i(95704),a=i(38156),o=i(42659),l=i(45599),u=i(41400),c=i(31586),d=i(51926),h=(0,l.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function f(e){return e.prepare((0,d.compressWhitespace)("SELECT"," t1.id,"," count(t2.id) AS cnt","FROM"," Tag t1"," JOIN Tag t2 ON t1.id = t2.parentId","GROUP BY"," 1","HAVING"," cnt > 0")).pluck().all()}async function m(e,i=[]){const r=e.prepare(t.RecursiveAssetCountForTagQuery).pluck(),o=e.prepare(t.DirectAssetCountForTagQuery).pluck(),l=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId"),c=new Set(f(e)),d=new a.PushProgressObserver({op:"Rebuilding tag asset counts"},e.prepare("SELECT count(*) FROM Tag").pluck().get());await(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e){const e=!c.has(t);(0,s.timeSync)("db.rebuildTagAssetCounts("+(e?"leaf":"cte")+")",(()=>{const s=(e?o:r).get({tagId:t});l.run({tagId:t,assetCount:s,updatedAt:Date.now()}),d.incrProgress(),h().debug("_rebuildTagAssetCounts()",{isLeaf:e,whereClauses:i,tagId:t,assetCount:s})})),t%10==0&&(h().throwIfAborted_(),await(0,u.delay)(1))}}}),d.completed()}t.nonLeafTagIds=f,t.RecursiveAssetCountForTagQuery=(0,d.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.DirectAssetCountForTagQuery=(0,d.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," AssetTag"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," AssetTag.tagId = :tagId"," AND Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL;"),t.rebuildTagAssetCounts=async function(e,t=o.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>m(e,["assetCount IS NULL"]))),(0,c.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rm(e)))}},69032:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(1728),c=i(56038),d=i(34102),h=i(49076),f=i(69589),m=i(28874),p=i(42231),g=i(85087),y=i(98770),v=i(59107),w=i(63870),b=i(7014),S=i(22573),P=i(42659),_=i(41400),M=i(75240),T=i(31586),E=i(34666),k=i(51926),D=i(75020),x=i(54017),C=i(48723),F=i(98784),A=i(7656),I=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return I().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=((0,o.isTest)()?5:30)*P.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=I().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.throwIfAborted_(i?.halt),await L(),i.recountAllTags&&(s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)(),s.info("rebuilding tag asset counts..."),await(0,A.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0))}catch(e){I().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,T.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),I().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const L=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{I().info("updating tag mountpoints...");const e=C.Tag.findByPath([D.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await N(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function R(){t.tagFtsRebuild.unset(),L.unset()}async function N(e){if(null==e||2!==e.depth||!e._path.startsWith(D.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===D.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,M.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,_.later)((()=>{(0,d.ee)().on("clearCache",R),m.Settings.libraryDir.watchLater(R)})),t.fixFileRootTag=N,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,k.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,_.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},87550:e=>{"use strict";e.exports=require("better-sqlite3")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},66150:e=>{"use strict";e.exports=require("fast-xml-parser")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},31832:e=>{"use strict";e.exports=require("knex")},51168:e=>{"use strict";e.exports=require("luxon")},93973:e=>{"use strict";e.exports=require("ml-kmeans")},4927:e=>{"use strict";e.exports=require("papaparse")},83058:e=>{"use strict";e.exports=require("picomatch")},22915:e=>{"use strict";e.exports=require("platform-folders")},57272:e=>{"use strict";e.exports=require("plist")},90595:e=>{"use strict";e.exports=require("punycode")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},93944:e=>{"use strict";e.exports=require("source-map-support")},49378:e=>{"use strict";e.exports=require("trash")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},76982:e=>{"use strict";e.exports=require("crypto")},34589:e=>{"use strict";e.exports=require("node:assert")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=86801);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463:(e,t,i)=>{const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,s),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223:e=>{const t=36e5,i=24*t,r=7*i,s=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const n=s.exec(e);if(!n)throw new TypeError(`invalid time period format ("${e}")`);const a=parseFloat(n[1]);switch(n[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*a);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*a);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(a*t);case"day":case"days":case"d":return Math.round(a*i);case"week":case"weeks":case"w":return Math.round(a*r);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*a)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227:(e,t,i)=>{const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120:(e,t,i)=>{const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827:(e,t,i)=>{const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015:(e,t,i)=>{const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return _(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function M(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function D(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=M,t.least=function(e){return M(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=k,t.collectBatched=function(e,t,i){const s=[];for(const n of k((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of k((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await D(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),b=i(99331),S=i(95937),P=i(98314),_=i(38835),M=i(70025),T=i(8769),E=i(43334),k=i(95402),D=i(28874),x=i(63870);class C extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>n(this,r,"m",s).call(this)),i,"worker"===e?(0,x.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,k.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,S.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&k.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,b.ending)()||!0===(0,M.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,T.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,r=new WeakSet,s=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(E.isWin?3:1)*c.minuteMs,maxTasksPerProcess:D.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:D.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:D.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,x.commandTimeoutMs)(),taskTimeoutMillis:D.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,s.set(this,void 0),n.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,s,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]=t))}get length(){return u(this,n,"f")}set length(e){l(this,n,(0,d.clamp)(0,u(this,n,"f"),e),"f")}clear(){this.length=0}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,n,"f")),e<0||e>=u(this,n,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,s,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,n,"f"){u(this,s,"f")[e]=c}));return u(this,n,"f")}pop(){return u(this,r,"m",o).call(this,u(this,n,"f")-1,(e=>{var t;return l(this,n,(t=u(this,n,"f"),--t),"f"),u(this,s,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,n,"f"){u(this,s,"f")[e]=c,l(this,a,e,"f")}));return u(this,n,"f")}shift(){return u(this,r,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,n,(i=u(this,n,"f"),--i),"f"),u(this,s,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",o).call(this,u(this,n,"f")-1-e,(e=>{const i=u(this,s,"f")[e];u(this,s,"f")[e]=u(this,s,"f")[t],u(this,s,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=n(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),s=i(31586),n=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),s=i(65843),n=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),s=i(20014),n=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)((()=>!1))},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),s=i(98553);var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},19851:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?M():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const _={timeoutMs:10*a.secondMs};async function M(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function T(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=M,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),s=i(32105),n=i(14593);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),s=i(55835),n=i(59455),a=i(48884);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),s=i(54557);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},26033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._isSupportedNode=t.RequiredNodeRange=t.isSupportedNode=void 0;const r=i(45599),s=i(76280);function n(e=process.versions.node){return(0,s.semverSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange="18||20||21",t._isSupportedNode=n},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),s=i(42659),n=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,s]of(0,l.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,l.keys)(e))if(r[n]=t(n,e[n]),s++,(0,o.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,n.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),s=i(73024),n=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function _(){return"ubuntu"===(0,t.osDistributionLinux)()}function M(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=_,t.hasApt=function(){return P()||_()},t.isFedora=M,t.isAlpine=T;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},k={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return D(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":D(e,k);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(_())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(M())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},45393:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=4},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),s=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),s=i(56409),n=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return s.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),s=i(54993);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),b=i(24399),S=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>T.prior()?.clear()))));const _=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let M=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),M)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;M=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(1708)),n=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),s=i(57150),n=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,n.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,s.logStartup)())}},28850:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),s.set(this,void 0),n(this,r,e,"f")}_call(){return(0,l.time)(a(this,r,"f")+(null==a(this,s,"f")?"(local)":"(remote)"),null==a(this,s,"f")?this.impl():a(this,s,"f").call(this))}setShim(e){n(this,s,e,"f")}hasShim(){return null!=a(this,s,"f")}clearShim(){n(this,s,void 0,"f")}}r=new WeakMap,s=new WeakMap},12089:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=a,s.set(this,void 0),n.set(this,void 0),l(this,s,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",a).call(this,e),(()=>u(this,r,"m",o).call(this,e)))}setShim(e){l(this,n,e,"f")}hasShim(){return null!=u(this,n,"f")}clearShim(){l(this,n,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",a).call(this,e))}}s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,s,"f")+(null==u(this,n,"f")?"(local)":"(remote)"),null==u(this,n,"f")?this.impl(e):u(this,n,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return s(this,r,"f")[Symbol.iterator]()}get length(){return s(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=s(this,r,"f").length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),a=this.valueOf(s(this,r,"f")[n]);if(e===a)return{found:!0,index:n};e>a?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&s(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...s(this,r,"f")];const a=t=>t<0||t>s(this,r,"f").length-1?null:(i??this.diff)(s(this,r,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return s(this,r,"f").shift()}at(e){return(0,a.at)(s(this,r,"f"),e)}toA(){return[...s(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===s(this,r,"f").length-1){const e=[...s(this,r,"f")];return s(this,r,"f").length=0,e}return s(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return s(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),s=i(82328),n=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),s=i(95705);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" …(+"+s+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function M(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=M;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(M(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['‘’].*['‘’]$/,k=/^["“”„«»〃].*["“”„«»〃]$/;function D(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||k.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=_;const M=/[^\da-z]+/gi;function T(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(M,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),s=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},75387:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},65211:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(19851),s=i(76790),n=i(22573),a=i(54993),o=i(7282),l=i(55222);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!(0,o.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),u=0}},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),s=i(55835),n=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},79184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(59455),s=i(48884),n=i(22859),a=i(28874),o=i(79781),l=i(92434);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(50357),o=i(55835),l=i(31586),u=i(68708),c=i(12168),d=i(23467),h=i(73168),f=i(50213),m=i(86580),p=i(48368),g=i(80361),y=i(28874),v=i(28544),w=i(75767),b=i(16170),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} ≠ ${o}`}function _(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function M(e,t){return[_(e),_(t)]}function T(e,t,i){const r=(0,w.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.aKey}:${r.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=v.CapturedAt.fromAssetFile(e),f=v.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const _=a.isFuzzy||f.isFuzzy;if(_&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",M)??P(e,i,"model",M);if(null!=E)return E;const k=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),D={cameraId:T(e,i,"cameraId")??null,imageId:T(e,i,"imageId")??null,lensId:T(e,i,"lensId")??null,exposureSettings:(0,w.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(k,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(k)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:D});const x=(0,s.compact)((0,u.values)(D));if((0,s.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:_});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(D).filter((e=>null==D[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos ≠ images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=E(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},13991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(19851),s=i(55835),n=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),v=i(14036),w=i(45200),b=i(34238),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function _(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>M(e*t)))}function M(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=_,t.sortScale=M,t.mtime2sort=T;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function k(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function D(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=_(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=D(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=k,t.assetFileSortCriteriaPojo=D,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of k(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),s.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,n(this,s,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return n(this,s,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,n(this,s,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=n(this,r,"f")&&clearTimeout(n(this,r,"f")),a(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,s=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(87997)),n=i(31586);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),b=i(45599),S=i(26905),P=i(55835),_=i(31586),M=i(68708),T=i(20214),E=i(57153),k=i(85556),D=i(50213),x=i(70025),C=i(95937),F="TIMEOUT",A=(0,b.defer)((()=>(0,D.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,_.gt0)(t)?new s(F).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const s=i[r];if(s.isSettled){if(s.name===F)return void A().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield s.value}}if(i.every((e=>e.name===F)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,M.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new k.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,s=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,s.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,s=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},39250:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(23838),a=i(54993),o=i(15674),l=i(73568),u=i(76740),c=i(99331),d=i(42638);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new d.Promises(e,t)}vacuum(){return s(this,r,"f").filterInPlace(((e,t)=>t.isPending&&!0!==t.payload?.aborted)),s(this,r,"f").valueCount()}enqueue({key:e,abortable:t,fn:i}){for(const t of s(this,r,"f").get(e)??[])t.payload?.abort("aborted by new work");if(this.vacuum(),(0,c.ending)())throw new l.AbortError("ending");const n=t??new u.Abortable,o=this.p.serial((0,a.toS)(e),(()=>i(n)),n);return s(this,r,"f").add(e,o),o}},r=new WeakMap},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new b(e,t,i,r)};class b extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,n,0,"f"),d(this,s,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,r,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,n,"f")}isStale(){return null==c(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,s,"f")?void 0:Date.now()-c(this,s,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,n,(i=c(this,n,"f"),++i),"f")}},u=function(e){d(this,s,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),s=i(80049);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},22781:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),s.set(this,!1),n.set(this,!1)}_call(){return a(this,s,"f")?(o(this,n,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,r,"f")):(o(this,s,!0,"f"),o(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,s,!1,"f"),!0===this.runLaterIfBusy&&a(this,n,"f")&&(o(this,n,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,s,"f")}prior(){return a(this,r,"f")}async force(){return await a(this,r,"f"),this._call()}}r=new WeakMap,s=new WeakMap,n=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var b=i(20214);async function S(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,l.gt0)(s)?(0,c.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function M({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const u=a??(o.length<=s?w.PermissivePromises:new w.Promises(i,(()=>s))),d=(0,l.gt0)(n)?e=>(0,c.thenOrTimeoutError)(t(e),n):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=S,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await S(s);r.push(...await S(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=M,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await M({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await M({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await M({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){s=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await M({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),b=i(73614);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function M(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),r=t();return M(e,Date.now()-i),r},t.pushTime=M,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>_(e,t)),i)}},42638:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),b=i(82647),S=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},59189:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(1708)),n=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),b=i(88158),S=i(45969),P=i(43334),_=i(28874),M=i(3790);function T(e){return E().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const E=(0,n.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,b.sortedKeys)((0,l.filter)((0,d.env)(),(e=>T(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const k=["HOME","LANG","USER"],D=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?k:D),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,S.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,_.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,o.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(s.default.env,(e=>T(e)||!(0,M.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:A({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let F=!1;function A({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,g.childProcLocale)():{},...C(r),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(s);if((0,y.isLogged)("debug")&&!F){F=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(s).map((([e,t])=>[e,(0,M.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>T(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return s}t.childEnv=A},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),b=i(22911),S=i(4867),P=i(73614),_=i(70025),M=i(57159),T=i(36868),E=i(66184),k=i(45643),D=i(95402),x=i(9727),C=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function A(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,D.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,k.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{D.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,D.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,k.waitForPidExit)(i,5e3)}function I(e,i,r,s=0){const a=new Date,o=[];return(0,v.niceable)(i,r)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&A(e)}),s-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,D.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,E.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new b.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,T.endStream)(a.stdin);const v=new d.Latch;null==a.stdout?v.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==a.stderr||s?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,S.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,S.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,S.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const E=p.join("");(0,l.notBlank)(E)&&g.push(new Error(E)),!r&&(0,o.isNotEmpty)(g)&&C().warn(f+" resulted in errors:",g);const k=i.isIgnorableError??_.isIgnorableError,D=g.filter((e=>!0!==k(e)));if(D.length>0)throw 1===D.length?D[0]:new M.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!n&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:E}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,D.killPid)(a.pid,!0),e}}t.endProcess=A,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),s=i(41400),n=i(19851),a=i(28874);(0,s.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,n.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},34330:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),b=i(25764),S=i(99331),P=i(42638),_=i(38835),M=i(8769),T=i(57159),E=i(66003),k=i(50213),D=i(45643),x=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,k.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,M.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,M.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,M.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),s=i.sibling(r);if(s.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",s.posixPathFrom((0,l.examples)()));const n=(0,d.originalsDir)();if(s.isSelfOrDescendantOf(n))return a.join("$library",s.posixPathFrom(n));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",s.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(6858),a=i(1708),o=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return s(this,r,"f").push(...e),this}async parse(e=a.argv,t){let i=(0,m.addHelpFooter)(new n.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of s(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":o.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,a.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of s(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),s=i(38639),n=i(17181),a=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,s.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),a.Settings.logColor.envValue=e,(0,n.setupLogFormatter)()}))}}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(1708)),n=i(22573),a=i(38639);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},53978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},43380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(28874),s=i(2858),n=i(22573),a=i(38639),o=i(46292);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},54772:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return _(w(e))}function y(e){return(0,f.clampRGB)(T(M(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function M(e){const[t,i,r]=v(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=_,t.lab2xyz=M,t.xyz2rgb=T,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const k=new Map;function D(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return F(x(e))}function F(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function A(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function I(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(k,e,(()=>D(e,t))):D(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(A(e))},t.hsv2hsl=F,t.hsl2hsv=A,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},42079:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(31586),s=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),v=(0,s.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let _=y*v==0?0:b-w;_-=2*(_>Math.PI?1:0)*Math.PI,_+=2*(_<-Math.PI?1:0)*Math.PI;const M=2*(0,s.sqrt)(y*v)*Math.sin(_/2),T=(i+c)/2,E=(y+v)/2;let k;y*v==0?k=w+b:(k=(w+b)/2,k-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,k+=2*(k<0?1:0)*Math.PI);const D=(T-50)**2,x=1-.17*Math.cos(k-Math.PI/6)+.24*Math.cos(2*k)+.32*Math.cos(3*k+Math.PI/30)-.2*Math.cos(4*k-63*Math.PI/180),C=1+.015*D/(0,s.sqrt)(20+D),F=1+.045*E,A=1+.015*E*x,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*k-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*I)*O;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(M/(o*A),2)+L*P/(a*F)*M/(o*A))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(40958),s=i(31586),n=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},32848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(48884),o=i(31843),l=i(70417),u=i(3048);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},40401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),v=i(85810),w=i(3048),b=i(76490),S=i(1971),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=M[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function D(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(_.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...T,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&D(g-1);const n=s.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n),2);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),k(a,t);const A=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),I=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:A,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:A,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const _=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],M={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},T=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:M[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function k(e,t){const i=e.countSum,r=e.size;D(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function D(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=k,t.mergeLabhashes=D,t.mergeNearCentroids=x},85409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(31586),s=i(68708),n=i(50989);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),v=i(21330),w=i(928),b=i(54261),S=i(73389),P=i(51275),_=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function M(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function k(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void _().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=M,t.toDated=function(e){return M(e)?e:void 0},t.mapDated=function(e,t){return M(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):k(e)},t.datedToDateTime=k,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=D(e)),r??(r=D(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,v.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),s=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),s=i(31586),n=i(54557),a=i(91655),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),s=i(40958),n=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),v=i(79842),w=i(66649),b=i(98247),S=i(98725),P=i(928),_=i(54261),M=i(73389),T=i(89724),E=i(17415),k=i(88600),D=i(51275);function x(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,k.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(S.ISO_YMD_RE.exec(e)?.groups??S.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tx(e))).join("-")}toLocal(){return(0,T.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function F(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,_.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,E.zoneToTzOffsetMinutes)((0,w.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(s=>(0,d.map)((0,P.getDay)(e),(n=>(0,d.map)((0,P.getHour)(e),(a=>(0,b.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,h.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${x(n)}:${x(a)}`},t.toExifDateTime=F,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,M.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,_.hasTime)(e)||(i??(0,v.datedToPrecisionMs)(e))>=c.dayMs?O(e):F(e,(0,D.getZoneName)(e))?.toISOString({includeOffset:t})};const A="yyyy:MM:dd HH:mm:ss.SSS",I=A+"ZZ";function O(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>x(e))).join(t)}function L(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(w.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,v.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,D.hasZone)(t)?I:A):void 0},t.datedToYMD=O,t.toFuzzyDate=L,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,w.datedToMillis)(e)||null==(0,w.datedToMillis)(t))return;const[s,n]=[e,t].map((e=>(0,w.datedToMillis)(e))).sort(),o=(n-s)/(r+1),l=(0,D.getZoneName)(e),u=l===(0,D.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,_.hasTime)(e)))?L(c):c},t.setZone=function(e,t,i){const r={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,D.hasZone)(e)},s=(0,E.normalizeZone)(t);return null!=e&&null!=s&&(0,_.hasTime)(e)?e instanceof y.DateInterval?e.setZone(s,r):F(e)?.setZone(s,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,v.datedToDateTime)(e);if(null==i)return;const r=(0,D.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),v=i(68852),w=i(4001),b=i(28874),S=i(24689),P=i(79842),_=i(66649),M=i(98247),T=i(21330),E=i(54261),k=i(73389),D=i(16400),x=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,_.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,k.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function A(e,t,i){try{const r=(0,M.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,M.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,M.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:M.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>A(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const e of n){const t=a(e);if(null!=t&&(0,x.isValidDate)(t))return t}}t.parseDated=I;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),s=i(31586),n=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),s=i(31586),n=i(68708);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),s=i(19851),n=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,s.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?M(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(M(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function _(e,t){return M(Date.now()-e,t)}function M(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=_,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:_(i)};const M=/\b(?Z|UTC|GMT)\b/,T=/(?[-±+−])/,E=/[-−]/,k=/(?[01]\d)/,D=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return v(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),M,new m.RegExpEscaped("|"),T,k,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const A=/\b(?(?:Etc\/)?GMT)\b/,I=(0,n.lazy)((()=>(0,m.concatRegexp)([A,T,D,m.RegExpOptional.from(x)])));function O(e){return F(I().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return _(i);if(null!=t){const i=S(e);if(null!=i)return _(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),v=(0,s.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),w=(0,s.lazy)((()=>(0,n.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),b=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,p.datedToISO)(e)))))),S=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,y.datedToLocal)(e)))))),P=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,m.datedToMillis)(e))))));function _(e){if(null==e)return!1;const t=T(e);return v().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return _(e)?e:void 0},t.isValidDate=_;const M=String(new Date("bad"));function T(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===M)return M;const t=(0,n.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,E())&&s.push("year is in the future"),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):S().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):b().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(t)).join("; "))}catch(t){return v().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=T;const E=(0,s.lazy)((()=>r.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return _(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==T({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),s=i(31586),n=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},82261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},92407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(19851),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},55332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(19851),s=i(50213),n=i(76187),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},91872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i,r){const a=Date.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}))}},12943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(79842),s=i(66649),n=i(40958),a=i(68708);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},65753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(19851),s=i(7282),n=i(28874);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*((0,s.isTest)()?.25:5))))},80632:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(54993),u=i(50213),c=i(23560),d=i(65211),h=i(29882),f=i(53265),m=i(66430),p=i(66184),g=i(28874),y=i(15674),v=i(87550);function w(){const e=g.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,a.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=g.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=g.Settings.logSql.valueOrDefault}){e=(0,f.resolve)(e),(0,h.mkdirpSync_)((0,r.dirname)(e));const b=(0,h.posixPathFromGrandparent)(e),S=(0,m.nativePathSizeSync)(e),P=(0,u.mkLogger)("db.mkdb("+b+")");if(null!=S){const E=Math.round(S/o.MiB),k=Math.ceil(1.5*E);k>g.Settings.dbCacheSizeMb.valueOrDefault&&(P.info("Dynamically setting dbCacheSize to "+g.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:E}),g.Settings.dbCacheSizeMb.envValue=k);const D=Math.round(1.5*E);D>g.Settings.maxMemoryMb.valueOrDefault&&(P.warn("Large database: setting maxMemoryDb to "+D+"MB",{dbFileSizeMb:E,"Settings.maxMemoryMb":g.Settings.maxMemoryMb.valueOrDefault}),g.Settings.maxMemoryMb.envValue=D)}P.info("Opening "+e+"...");const _={fileMustExist:!1,readonly:!1};if((0,a.gt0)(t)&&(_.timeout=Math.ceil(t)),i){const x=(0,u.mkLogger)("SQLite("+b+")"),C=(0,p.defaultLogLevel)();function F(e,...t){var i;(0,n.blank)(e)||x.log(C,(i=e,(0,l.toS)(i).replace(/\s{2,}/g," ")),{args:t})}_.verbose=F}const M=new v(e,_);P.info("Open. Setting PRAGMAs...");for(const A of(0,s.compact)(['encoding = "UTF-8"',"threads = "+(0,y.maxCpus)(),"foreign_keys = ON","page_size = "+w(),"trusted_schema = 0","cache_size = -"+Math.round(g.Settings.dbCacheSizeMb.valueOrDefault*o.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL",(0,a.gt0)(g.Settings.dbBusyTimeoutMs.valueOrDefault)?"busy_timeout = "+g.Settings.dbBusyTimeoutMs.valueOrDefault:null,"temp_store = MEMORY","synchronous = "+g.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,c.isDbJanitorService)()?(0,l.toS)(g.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+g.Settings.dbAutoVacuumMode.valueOrDefault]))P.tapThunk({msg:"PRAGMA "+A,result:()=>M.pragma(A)});const T=M;return T.__uid=(0,d.uid)(),T},t.pageSizeBytes=w},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},95704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(40958),s=i(31586),n=i(59455),a=i(65753),o=i(51040);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},76187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(17217),s=i(87391),n=i(7311);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},51040:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+$/gm,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(19851),s=i(50357),n=i(30976),a=i(50213),o=i(95696),l=i(80632),u=i(76187),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},87391:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},27180:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(5916),s=i(84777),n=i(89966),a=i(63870),o=i(87550);t.sqliteVersion_=(0,r.lazyAsync)({desc:"db.sqliteVersion",later:async function(){let e;try{e=new o(":memory:");const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,n.sqliteNativePath_)(),r=(await(0,s.stdout_)(i,["-version"],{timeoutMs:(0,a.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:r.split(/\s+/,1)[0],fullToolVersion:r,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,a.commandTimeoutMs)()})},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),b=i(29882),S=i(45969),P=i(43334),_=i(28874),M=i(41692),T=i(32774),E=i(80612),k=i(32551),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function x(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function C(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:T.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:T.DefaultDockerLibraryDir},...x()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,k.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,k.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,k.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...x()),i}t.tmpCacheDirs=x,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:x(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:C(),desc:"cache"})));const F=(0,d.lazy)((()=>{(0,M.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(A)}));function A(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{F();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,b.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=A},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),s=i(45969),n=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},79960:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(45255),o=i(84777),l=i(16287),u=i(57902),c=i(43334),d=(0,r.lazy)((()=>(0,n.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,o.stdout_)("defaults",h,{timeoutMs:a.ShortCommandTimeoutMs});if((0,s.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),s=i(45969),n=i(32774);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),s=i(96706),n=i(29882);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),s=i(49776),n=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},48195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotLibraryDir=t.isLibraryDir=void 0;const r=i(19851),s=i(22573),n=i(98553),a=i(12168),o=i(50213),l=i(15056),u=i(98314),c=i(17217),d=i(16287),h=i(2858),f=i(87290),m=(0,r.lazy)((()=>(0,o.mkLogger)("dir.IsLibraryDir")));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),s=i(54993),n=i(29882),a=i(28874);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),s=i(55835),n=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e),!1)}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function M(e){return y(_(e))}async function T(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await M(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=M,t.setupLibraryDbDir_=T},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),s=i(7282),n=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),s=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),b=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,n.join)((0,m.homeDir)(),".psenv"));const t=(0,b.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,d.debom)(s.default.readFileSync((0,g.resolve)(r))),n=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(n))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),s=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(1708)),n=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),s=i(19851),n=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),s=i(26905),n=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),s=i(38639),n=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function b(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function S(e){return!!((0,s.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||b(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=b,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===S(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=S;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),s=i(31586),n=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),s.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(n(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),s=i(19851),n=i(15197);t.ee=(0,s.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new n.CapturingEventEmitter(e)}))},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(73024)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(76760)),n=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),s=i(76760);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),v=f(i(1708)),w=i(46466),b=f(i(57975)),S=f(i(38522)),P=i(19851),_=i(40958),M=i(5233),T=i(22573),E=i(42659),k=i(50357),D=i(96249),x=i(98553),C=i(55835),F=i(31586),A=i(68708),I=i(97790),O=i(39926),L=i(51926),R=i(59455),N=i(54993),B=i(48884),j=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),H=i(76850),q=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Y=i(43334),Z=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),se=i(89968),ne=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),be=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const Se=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const s=(0,fe.resolve)(i),n=new Pe(s,t);return Se().set(i,n),Se().set(s,n),n}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,k.eql)(["."],e)||e.every(T.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,H.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,be.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,A.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,M.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Z.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),_e)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,n=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*E.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),s=i(88840),n=i(14036),a=i(29882);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,n.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),b=i(16287),S=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class M{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new M(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new M(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return M.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new M(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>M.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new M(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=M},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),v=i(54557),w=i(50213),b=i(88158),S=i(56519),P=i(46292),_=i(32551),M=i(35280),T=i(87290),E=i(96706),k=i(57902),D=i(43334),x=i(78984),C=i(33995),F=i(28874),A=i(21144),I=i(83278),O=i(48313),L=i(85772),R=i(78133),N=i(46356),B=i(17217),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?k.LogLevels.debug:k.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class H{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const q=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new H;e.push(G,q);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((D.isWin?"*":"")+"/"+t.s+"/",t.desc));if(D.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}D.isLinux&&e.push(new U(`${(0,_.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ne,whyNoMedia:L.whyNoMedia,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ne}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Z=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Z:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return F.Settings.disableAllFilters.valueOrDefault?void 0:x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ne(e){return!(0,M.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),...F.Settings.argvScanPaths.values,...F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,A.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ne},88561:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},79267:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const c=i(19851),d=i(40958),h=i(42659),f=i(31586),m=i(71371),p=i(50213),g=i(7282),y=i(409),v=i(78406),w=i(25764),b=i(99331),S=i(91655),P=i(34102),_=i(89968),M=i(85772);class T{static for(e){return new T(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,a,d=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=a,this.minRetained=d,s.set(this,void 0),this.intervalMs=(0,c.lazy)((()=>(0,f.clamp)((0,g.isTest)()?0:5*h.minuteMs,h.dayMs,this.staleMs/2))),n.set(this,void 0),this.cleanup=(0,y.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>u(this,r,"m",o).call(this)}),l(this,s,(0,p.mkLogger)("fs.FileCleanup("+e+")"),"f")}scheduleInterval(){return(null==u(this,n,"f")||u(this,n,"f").ended)&&l(this,n,new v.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:w.EndableRanks.first}),"f"),u(this,n,"f")}cancelInterval(){u(this,n,"f")?.end(),l(this,n,void 0,"f")}}t.FileCleanup=T,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(e){if(!(0,f.gt0)(this.minRetained))return new Set;const t=new m.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},o=async function(){try{if((0,b.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await _.DirectoryEntry.for(e);if(null==t)return[];u(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,S.fmtFullDuration)(this.staleMs," ")});const i=await u(this,r,"m",a).call(this,t),n=Date.now()-this.staleMs,o=new Set,l=[],c=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,M.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,f.gte)(e.mtimeMs(),n)))if(e.isDirectory())try{await e.rmdir_(),c.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(u(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,P.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&u(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),l.push(e.nativePath),o.add(e.dir)}catch(t){u(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const h=[...l,...c];return(0,d.isNotEmpty)(h)&&t.clear(),u(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:l.length,pruned_dir_count:c.length}),h}catch(e){return void u(this,s,"f").error("cleanup() failed",{error:e})}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,n.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),s=i(17217),n=i(16287),a=i(68284);async function o(e){return(0,r.pick)(await(0,n.stat_)((0,s.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,s.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),s=i(19851),n=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,s.set(this,[]),n.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,n,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,s,"f").push(e)}close(){u(this,n,"f").close()}}t.FileWatcher=m,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,s,"f"))t(e,this.nativePath)}}},13829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(55835),s=i(13538),n=i(81168),a=i(37628),o=i(46292),l=i(73209),u=i(95696);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},73209:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const _=i(58587),M=P(i(44652)),T=i(87997),E=i(40958),k=i(17586),D=i(42659),x=i(50357),C=i(75240),F=i(55835),A=i(31586),I=i(30976),O=i(13538),L=i(54993),R=i(7282),N=i(68852),B=i(23560),j=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),H=i(55222),q=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,s,Math.max(Date.now(),b(this,s,"f",n)+1),"f",n),(0,E.compactBlanks)([H.TokenRadix.encode(b(this,s,"f",n)),B.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,A.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return b(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>b(this,r,"m",w).call(this)),e.endableRank??j.EndableRanks.postdb,(0,q.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=s,s,(i=b(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(b(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await b(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+b(this,l,"f")),this.staleMs=(0,A.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),b(s,s,"f",o).push(this)}get acquired(){return b(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await b(this,r,"m",f).call(this,e)??b(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,k.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,x.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==b(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:D.secondMs);S(this,c,setInterval((()=>b(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=b(this,c,"f")&&(clearInterval(b(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(b(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),S(this,u,!1,"f"),(0,F.map)(b(this,d,"f"),(e=>(0,T.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?b(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>b(this,r,"m",v).call(this)),(0,A.toGt0)(this.staleMs)??D.secondMs),"f"),b(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(b(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,A.gt0)(this.staleMs)&&Date.now()>b(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await b(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await b(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,A.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,A.gt0)(t)&&!(0,_.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),b(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await b(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await b(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,E.filterInPlace)(b(s,s,"f",o),(e=>b(e,l,"f")!==b(this,l,"f")))},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),s=i(51926),n=i(54993),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(73024)),n=i(57075),a=i(46466),o=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44652)),n=r(i(73024)),a=i(46466),o=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(n.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),s=i(42659),n=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),s=i(54993),n=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,n.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,n.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,n.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,n.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(51926),n=i(54993);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(76760)),n=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},61704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(21144),s=i(17217);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=n(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),b=i(88561),S=i(65238),P=i(16287),_=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),M="NoMedia",T=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+M+"$","im"),E=Object.freeze(["."+M,M]),k=Object.freeze((0,u.flatten)(E.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function D(e){return null!=T.exec(e)}t.isNoMediaName=D;const x=(0,o.lazy)((()=>new b.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=v.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return D(i.base)||await(0,w.isCachedirTagFile)(i)?x().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await x().getOrSetAsync(i.nativePath,(()=>F(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function F(e){if(D(e.base))return x().set(e.parent().nativePath,e.nativePath),_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,S.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([A(e.nativePath,i),(0,S.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,w.isCachedirTagDirectory)(e)?_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function A(e,t){for(const i of g.isCaseSensitiveFs?k:E){if(!0===t?.aborted)return null;const r=a.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return _().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(D(r.basename))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,r.basename))});if(r.basename===w.CACHEDIR_TAG){const t=(0,a.join)(e,r.basename);if(await(0,w.isCachedirTagFile)(t))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=F,t._dirHasNoMediaChild=A},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),b=i(17217),S=i(16287),P=i(66430),_=i(5545);function M(e){return((0,b.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return C(e).some(M)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!M(e)))},t.resolveSimpleFile=function(e){return(0,b.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return E((0,v.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return n.default.dirname((0,b.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const T=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=T.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function k(e){const t=n.default.parse((0,b.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,n.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,b.toNativePath_)(e.ancestor),i=(0,b.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function x(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(y.isLinux?r===s:(0,p.equalsIgnoreCase)(r,s))}function C(e){return(0,b.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function F(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function A({p:e,maxLength:t}){const i=(0,b.toNativePath_)(e);if(i.length<=t)return i;const r=C(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),O([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),O([...s,...n])}function I(e){return e.startsWith("\\\\")}function O(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),y.isWin?"":n.default.sep)}t.parseNativePath=E,t.parentBasename=k,t.grandParentBasename=function(e){return k(n.default.parse((0,b.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return x(b.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return x(b.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return x(b.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=F,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,b.toNativePath_)(e),r=(0,b.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,v.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=A,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(A({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;if(F(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await s.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,b.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,b.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),b=i(16287),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function M(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,...M()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),b=i(22573),S=i(42659),P=i(26905),_=i(75240),M=i(55835),T=i(31586),E=i(68708),k=i(13538),D=i(89937),x=i(12168),C=i(54993),F=i(48884),A=i(50213),I=i(45255),O=i(81168),L=i(56519),R=i(56038),N=i(31562),B=i(84777),j=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),H=i(43334),q=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Y=i(34238),Z=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),se=i(73209),ne=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,A.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),r=new fe(i,t);return(0,O.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,M.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,M.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,M.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,k.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,T.clamp)(I.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,M.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,M.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),H.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,M.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),v=i(83278),w=i(19748),b=i(92423),S=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):null}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function k(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function D(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function A(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function I(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:A}]}function O(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:_},{notVideoTooShort:M},{notVideoTooLong:T},{notRejectedRating:k},{notExcludedKeyword:D}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=_,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=A,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(76760)),n=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(s.default.join((0,p.execDir)(),"resources"),s.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=s.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),s=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),s=i(84542);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(51455)),n=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),b=i(88561),S=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function _(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const M=(0,a.lazy)((()=>new b.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function T(e){(0,l.blank)(e)||M.prior()?.delete(e)}async function E(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await M().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=k(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(s===f.Timeout&&(0,g.onTimeout)({soft:!1}),s!==f.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=T,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),M.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():T(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!M().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){T(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=M().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?E(e):k(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return M().get(e)},t.readdirUncached_=k},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const s=i(73024),n=r(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=n.default.resolve(t,...e);if((0,s.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??n.default.resolve(...e))},t.execDir=(0,l.defer)((()=>n.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(22454),s=i(28874),n=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),s=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const s=r(i(73024)),n=r(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function S(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(S(r),S(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}t.stat_=v,t.statMaybe=w,t.statToType=b,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),s=i(56409);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(57075)),n=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),v=i(19851),w=i(40958),b=i(22573),S=i(42659),P=i(98553),_=i(31586),M=i(68708),T=i(50989),E=i(51926),k=i(85556),D=i(54993),x=i(89788),C=i(23467),F=i(7282),A=i(23560),I=i(77377),O=i(71567),L=i(73568),R=i(25764),N=i(38836),B=i(99331),j=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),H=i(5012),q=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Y=i(84542),Z=i(73428);t.AssetFileSyncStates=(0,T.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,T.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,T.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,T.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const X={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,M.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,T.strEnum)(...(0,M.keys)(new class{constructor(e,t,i,r,s,n,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,v.lazy)((()=>(0,Z.writeTextfile_)(re().nativePath,(0,E.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(X)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=S.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,q.isCsvExt)(e)&&(0,_.gte)(e.mtimeMs(),t)))},t.syncReport=(0,v.lazy)((()=>new se));class se extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new x.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,s,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,b.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,H.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,D.toS)(e.path),state:e.state,details:(0,D.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:t,at:new Date(t).toISOString(),...i,...(0,M.pick)(e,"from","elapsedMs","url")};(0,M.isEmptyObj)(e.meta)||(s.meta=(0,P.stringify)(e.meta)),(0,F.isTest)()&&process.stdout.write((0,P.stringify)(e)+Y.Newline),f(this,r,"m",u).call(this,s)}}maybeSystemData(e){(0,A.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:n}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,B.ending)()||r instanceof L.AbortError?t.SyncFileStates.canceled:r instanceof k.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return f(this,n,"f")??f(this,r,"m",h).call(this)}async flushClose(){return f(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,n,"f");return m(this,n,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,s,"f")}}t.SyncReport=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,r,"m",c).call(this,i):(f(this,r,"m",c).call(this,{...i,details:(0,w.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Y.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,s,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,j.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,s,"f").nativePath),this.logger.info("Opening new report: "+f(this,s,"f")),(0,F.isTest)()&&(0,O.stdoutWrite)({syncReport:f(this,s,"f").nativePath},!1),m(this,n,(0,g.createWriteStream)(f(this,s,"f").nativePath),"f"),f(this,n,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Y.Newline),f(this,n,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(48161)),n=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44652)),n=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},79847:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkFileUri=t.trashOrUnlinkFileUris_=void 0;const o=n(i(51455)),l=a(i(49378)),u=i(40958),c=i(22573),d=i(13538),h=i(83104),f=i(45255),m=i(31562),p=i(98314),g=i(34102),y=i(28874),v=i(45200),w=i(63870),b=i(16287),S=i(74128),P=i(84258),_="fs.Trash";async function M(e){const t=Date.now(),i=(0,w.commandTimeoutMs)(),r=(0,c.toNotBlank)(e.nativePath)??await(0,d.thenOrTimeout)((0,v.uri2nativePath)(e.uri,e.mountpoint),i);if((0,c.blank)(r)||r===h.Timeout)return(0,S.syncReport)().onProgress({from:_,state:"failed",details:"Could not convert URI to native path",path:e.uri,elapsedMs:Date.now()-t}),{uri:e.uri,unlinked:!1};const s=await(0,b.statMaybe)(r);if(null==s)return(0,S.syncReport)().onProgress({from:_,state:"noop",details:"Failed to delete: no such file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(!s.isFile())return(0,S.syncReport)().onProgress({from:_,state:"noop",details:"Failed to delete: not a file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(y.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,d.thenOrTimeoutError)((0,l.default)(r,{glob:!1}),i),await function(e){return(0,m.untilTrue)((async()=>null==await(0,b.statMaybe)(e)),{timeoutMs:f.ShortCommandTimeoutMs})}(r))return(0,S.syncReport)().onProgress({from:_,state:"deleted",details:"Moved file to trash",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0};(0,P.logger)().warn("soft-delete("+r+") didn't seem to work: the file is still there?")}catch(e){(0,S.syncReport)().onProgress({from:_,state:"note",details:"Failed to soft-delete file to trash: "+(0,p.errorToS)(e),path:r,elapsedMs:Date.now()-t}),(0,P.logger)().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}try{return await(0,d.thenOrTimeoutError)(o.unlink(r),i),(0,g.ee)().emit("fileChanged",r),(0,P.logger)().info("unlink("+r+") successful"),(0,S.syncReport)().onProgress({from:_,state:"deleted",details:"Permanently deleted file",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0}}catch(i){return(0,S.syncReport)().onProgress({from:_,state:"failed",details:"Could not move file to trash or delete: "+(0,p.errorToS)(i),path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!1}}}t.trashOrUnlinkFileUris_=async function(e){const t=[];for(const{uri:i,mountpoint:r}of(0,u.uniqBy)(e,(e=>e.uri)))try{t.push(await M({uri:i,mountpoint:r}))}catch(e){t.push({uri:i,unlinked:!1,error:e})}return t},t.trashOrUnlinkFileUri=M},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),s=i(41400),n=i(55835),a=i(92782),o=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),h=i(87128),f=i(95696);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=n(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await a.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(76760)),n=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},60526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(47783),a=i(63335),o=i(18454);t.exiftoolHealthCheck=(0,s.defer)((()=>o.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifTool…",settings:[],later:async()=>{const e=await(0,n.exiftoolVersion_)();return{level:"ok",msg:["ExifTool is OK","ExifTool "+(0,a.ver)(e),(0,r.tt)((0,n.exiftool)().options.exiftoolPath)],meta:{exiftoolVersion:e}}}})))},19652:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const a=i(51455),o=n(i(22915)),l=i(40958),u=i(82950),c=i(22573),d=i(45599),h=i(12168),f=i(50213),m=i(79960),p=i(32551),g=i(98314),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,p.homeDir)(),o.getHomeFolder(),o.getPicturesFolder(),o.getVideosFolder(),o.getDesktopFolder(),await(0,m.defaultApplePhotosLibrary)()]).sort(),t=new Map,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,a.readdir)(e,{withFileTypes:!0})}catch(i){if(["ENOTDIR","ENOENT"].includes(i?.code))continue;t.set(e,i)}const r=0===t.size?{level:"ok",msg:["Default media directories are OK","The following directories are readable:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Error reading "+(0,h.plur)(t.size,"media directory")+":",(0,u.li)([...t.entries()].map((([e,t])=>(0,u.tt)(e)+":"+(0,g.errorToS)(t,{maxLen:80}))))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},79483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(45599),s=i(45969),n=i(19652),a=i(18454);t.externalDirsHealthCheck=(0,r.defer)((()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",pendingMsg:"Checking default photo directories…",settings:[],later:n.externalDirectoryCheck})))},63664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const r=i(22573),s=i(45599),n=i(41400),a=i(50268),o=i(98553),l=i(50213),u=i(23560),c=i(45255),d=i(5916),h=i(28874),f=i(34238),m=i(51140),p=i(4988),g=i(18454),y=(0,s.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({desc:"health.getRemoteHealthSummary",later:async()=>{try{if((0,u.isWebService)())return;const e=await(0,p.get_)(f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}),{timeoutMs:c.ShortCommandTimeoutMs}),t=(0,o.parseJSON_)(e.data);if(m.HttpStatusIs.ok(e.statusCode)&&(0,a.isHealthCheckSummary)(t))return"ready"===t.state&&(0,r.toNotBlank)(t.libraryDir)!==(0,r.toNotBlank)(h.Settings.libraryDir.valueOrDefault)&&(y().error("getHealthSummary(): libraryDir mismatch! Switching to that library directory...",{local:h.Settings.libraryDir.valueOrDefault,remote:t.libraryDir}),h.Settings.libraryDir.value=t.libraryDir),y().debug("getHealthSummary()",{response:e}),t;y().warn("getHealthSummary(): invalid response",{response:e})}catch(e){y().warn("Failed to get health check summary from web service",{error:e})}}}),t.getLocalHealthSummary=(0,d.lazyAsync)({desc:"health.getLocalHealthSummary",later:()=>g.HealthCheck.awaitSettled()}),(0,n.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},18454:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b,S,P,_=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},M=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const T=i(19851),E=i(40958),k=i(76790),D=i(22573),x=i(41400),C=i(50357),F=i(26905),A=i(50268),I=i(55835),O=i(68708),L=i(30976),R=i(51926),N=i(13538),B=i(42279),j=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),H=i(50213),q=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Y=i(77740),Z=i(98314),X=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),se=i(21525),ne=i(82638),ae=(0,T.lazy)((()=>(0,H.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{_(this,s,"f",l).push(e+": failed: "+(0,Z.errorToS)(t)),this.onResultChange()})),_(this,s,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return _(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){_(this,s,"f",l).push((0,R.isString)(e)?e:(0,Z.errorToS)(e)),this.onResultChange()}static lastErrors(){return _(this,s,"f",l).toA()}static addLoadingMsg(e){_(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,E.compact)((0,j.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:_(this,s,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[_(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=_(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>_(this,s,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return _(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,A.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=_(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=s.summary();if(e.pendingCount>0){const t=await Promise.all(s.testResultsCritical());e=s.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){s.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,F.shortStack)());else{this.onResultChange(),_(this,s,"f",l).clear(),_(this,s,"f",d).clear(),_(this,s,"f",h).clear(),_(this,s,"f",c).clear(),this.summary.clear(),M(this,s,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new s(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return _(this,s,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,n,o,l,u,c,d,h,f,m,S,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=n,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=S,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),w.set(this,(0,T.lazy)((async()=>{await _(this,p,"f").prior(),(0,C.eql)(_(this,g,"f"),_(this,r,"m",v).call(this))||(this.onReset?.(),await this.refresh(),_(this,w,"f").unset())}))),this.refresh=(0,T.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await _(this,p,"f").prior();const e=_(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,H.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[A.HealthCheckSections.ordinal(this.section),l??999,this.id],M(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>_(s,s,"f",a).enqueue({name:this.id,l:()=>_(this,r,"m",b).call(this,o)}),ttlMs:S}),"f"),this.isCritical&&_(this,p,"f").watchLater({onChange:s.onCriticalResult,onError:s.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>_(this,w,"f").call(this)))}isStale(){return _(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return _(this,p,"f").settledCount()}reset(){return _(this,p,"f").unset(),this.onReset?.(),M(this,g,{starting:!0},"f"),this}setTTL(e){_(this,p,"f").setTTL(e)}result(){return _(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return _(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return _(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??_(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,E.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,E.isNotEmpty)(i)&&(r.links=(0,E.uniqBy)(i)),(0,E.isNotEmpty)(t)&&(r.buttons=(0,E.uniqBy)(t)),r}t.HealthCheck=oe,s=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,w=new WeakMap,r=new WeakSet,o=function(){return(0,E.filterInPlace)(_(this,s,"f",n),(e=>!e.isPending)),_(this,s,"f",n)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,ne.summarizeHealthChecksSync)({errors:_(this,s,"f",l),skipPending:_(this,s,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&M(this,s,!0,"f",u),i.state!==_(this,s,"f",c).last?.state&&_(this,s,"f",c).push({state:i.state,ts:Date.now()}),i},v=function(){return(0,O.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},b=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,F.shortStack)()}),M(this,g,_(this,r,"m",v).call(this),"f");try{if((0,Y.getDevEnvFlag)("PS_SLOMO")&&await(0,x.delay)((0,L.randomInt)(.3*i,.7*i)),this.isSkipped())return _(this,r,"m",S).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const s=await(0,N.thenOrTimeoutError)(e(),i);return _(this,r,"m",S).call(this,{test:s,elapsedMs:Date.now()-t})}catch(e){return _(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},S=function({test:e,src:t="#toResult",elapsedMs:i}){var r,n;const a=s.normalizeMsg(e.msg),o=e.level??((0,z.toS)(a).toLowerCase().includes("error")?"error":(0,z.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,E.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(M(this,y,(n=_(this,y,"f"),r=n++,n),"f"),r),(0,$.ending)()?u:this.logger.tap({level:se.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const s=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,D.toNotBlank)((0,Z.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,X.isFatalError)(e)&&s.toLowerCase().includes("warn")?"warn":"error"),_(this,r,"m",S).call(this,{test:{msg:s,level:t},src:"#toErrorResult",elapsedMs:i})},n={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new U.CountingSet},f={value:[]},oe.all=(0,T.lazy)((()=>Object.freeze((0,k.sortBy)(_(s,s,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,q.debounce)((()=>{ae().info("onCriticalResult()",s.summary.refresh())}),250),oe.summary=(0,T.lazy)((()=>_(s,s,"m",m).call(s))),oe.resetDebounced=(0,q.debounce)((()=>s.reset()),50)},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},88625:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=t.testHealthCheck=void 0;const r=i(19851),s=i(82950),n=i(45599),a=i(50268),o=i(50213),l=i(7282),u=i(44198),c=i(34102),d=i(2858),h=i(60526),f=i(79483),m=i(18454),p=i(39214),g=i(86403),y=i(42482),v=i(35675),w=i(89035),b=i(31974),S=i(20752),P=i(85200),_=i(37301),M=i(65756),T=i(15024),E=i(3956),k=i(29332),D=i(61274),x=i(38372),C=i(49913),F=i(84728),A=i(7245),I=i(16264),O=(0,n.defer)((()=>(0,o.mkLogger)("health.HealthCheckSetup")));t.testHealthCheck=(0,n.defer)((()=>m.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,settings:[],pendingMsg:"Test check…",later:async()=>{const e=a.HealthCheckLevels.validOrElse((0,u.env)().PS_TEST_HEALTH_CHECK_LEVEL,a.HealthCheckLevels.ok);return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,s.b)("details")}:`,(0,s.li)("alpha",(0,s.tt)("bravo"),"charlie")]}}}))),t.healthCheckSetup=(0,r.lazy)((()=>{(0,h.exiftoolHealthCheck)(),(0,p.heifHealthCheck)(),(0,y.libraryDirectoriesCheck)(),(0,v.libraryFreeSpaceCheck)(),(0,E.settingsEnvHealthCheck)(),(0,D.settingsSystemHealthCheck)(),(0,k.settingsLibraryHealthCheck)(),(0,f.externalDirsHealthCheck)(),(0,w.memoryHealthCheck)(),(0,b.nodejsHealthCheck)(),(0,S.notInDMGHealthCheck)(),(0,P.osHealthCheck)(),(0,_.powershellHealthCheck)(),(0,x.sharpHealthCheck)(),(0,g.jpegtranHealthCheck)(),(0,T.securityHealthCheck)(),(0,M.sqliteHealthCheck)(),(0,C.systemLoadHealthCheck)(),(0,A.videoHealthCheck)(),(0,I.volumeHealthCheck)(),(0,F.versionHealthCheck)(),(0,l.isProd)()||(0,t.testHealthCheck)();let e=(0,d.libraryHasSettings)();d.libraryHasSettings.watchLater((t=>{null!=t&&e!==t&&(O().info("libraryHasSettings changed. Resetting health checks.",{newValue:t}),e=t,m.HealthCheck.resetDebounced())}));for(const e of["volumesChanged","mountpointsChanged","error"])(0,c.ee)().on(e,(()=>{O().debug("Clearing health check cache",{event:e}),m.HealthCheck.resetDebounced()}));(0,c.ee)().on("fatal",(e=>m.HealthCheck.addError(e)))}))},39214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(41400),a=i(55835),o=i(34102),l=i(277),u=i(45969),c=i(63335),d=i(18454);t.heifHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-heif",pendingMsg:"Checking HEIF/HEIC tooling…",settings:["heifConvertPath"],links:[{text:"Read how to set up HEIF support with PhotoStructure",url:"https://photostructure.com/getting-started/heif-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getHeifSupportDetails)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["HEIF images will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.heifHealthCheck.prior()?.reset()))}))},86403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testJpegtran_=t.jpegtranHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(55835),a=i(98314),o=i(89966),l=i(51210),u=i(76280),c=i(63335),d=i(18454);async function h(){const e=await(0,o.jpegtranNativePath_)(),t=await(0,l.jpegtranVersion_)();return{nativePath:e,version:t,satisfies:(0,u.semverSatisfies)(t,">=1.5")}}t.jpegtranHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,pendingMsg:"Checking "+(0,r.tt)("jpegtran")+"…",settings:[],later:async()=>{try{const e=await h();return{level:"ok",msg:["jpegtran is OK",(0,n.map)(e.version,c.ver),(0,n.map)(e.nativePath,r.tt)]}}catch(e){return{level:"error",msg:["Something's amiss with jpegtran",(0,a.errorToS)(e)]}}}}))),t.testJpegtran_=h},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},42482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(98553),o=i(31586),l=i(94174),u=i(87290),c=i(98314),d=i(29882),h=i(45969),f=i(43334),m=i(28874),p=i(2858),g=i(59107),y=i(18454),v=i(42495);async function w(){const e=await(0,u.setupLibraryDirs_)();return(0,p.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,r.li)(...e.map((e=>(0,r.tt)(e))))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}t.libraryDirectoriesCheck=(0,n.defer)((()=>y.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directories…",settings:["libraryDir","originalsDir","previewsDir","cacheDir"],ttlMs:s.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,h.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],okLinks:[{type:"button",text:"Run library maintenance jobs",url:"/admin/run-maintenance",method:"POST",icon:"handyman"}],later:async()=>(await(0,p.readSettings)(),(0,h.isDocker)()?async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,r.tt)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,r.tt)(m.Settings.libraryDir.toEnvLine(m.Settings.libraryDir.defaultValue))}`]};const t=await(0,g.mountpoints_)(),i=(0,d.bestMountpointForDir)(e,t);if(null==i||"/"===i)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,r.tt)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[v.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,r.tt)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`];return null!=t&&(0,o.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,r.tt)(t.uid)+", groupid "+(0,r.tt)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[v.DockerVolumeLink]}}return await w()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,l.userDesc)()}.`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[v.DockerVolumeLink]}}}():async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"no-library",msg:["No PhotoStructure library is open",(0,a.stringify)(m.Settings.libraryDir.getState())]};if(!(0,p.libraryHasSettings)())return{level:"no-library",msg:["No PhotoStructure library is open",m.Settings.libraryDir.hasValue()?(0,r.tt)(m.Settings.libraryDir.toEnvLine()):void 0]};try{return await e.isReadWriteExecutable_()?await w():{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(t){return{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,l.userDesc)()}`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}())})))},35675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(31586),l=i(68708),u=i(12168),c=i(87290),d=i(77740),h=i(28874),f=i(7014),m=i(18454);t.libraryFreeSpaceCheck=(0,a.defer)((()=>(0,l.tap)(m.HealthCheck.for({section:"Library",id:"library-free-space",settings:["libraryDir","minDiskFreeGb","originalsDir","previewsDir","cacheDir"],pendingMsg:"Checking free space on library volume(s)…",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,c.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(e)} is not a directory`};const t=[];for(const e of await(0,c.setupLibraryDirs_)()){const i=await(0,f.bestVolumeForPath)(e);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.tt)(e)}`};let r=t.find((e=>e.vol.mountpoint===i.mountpoint));null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*u.GB,n=[];for(const{vol:e,paths:a}of t){const t=(0,s.b)(`Volume ${(0,s.tt)(e.mountpoint)} has ${(0,u.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.li)((0,r.uniq)(a).sort().map(s.tt))}`;if(e.available{for(const t of["minDiskFreeGb","libraryDir","originalsDir","configDir"])h.Settings[t].watchLater((()=>e.reset()))}))))},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},31974:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(1708)),n=i(82950),a=i(45599),o=i(26033),l=i(63335),u=i(18454);t.nodejsHealthCheck=(0,a.defer)((()=>u.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.js…",settings:[],links:[{text:"Read about PhotoStructure NodeJS support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e="You're running Node.js "+(0,l.ver)(s.default.versions.node)+".\nPhotoStructure requires "+(0,n.tt)(o.RequiredNodeRange)+".";return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",e]}:{level:"warn",msg:["Node.js is not a supported version",e]}}})))},20752:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(45599),s=i(43899),n=i(43334),a=i(18454);t.notInDMGHealthCheck=(0,r.defer)((()=>n.isMac&&n.isElectron?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure installation directory…",settings:[],later:async()=>s.ProjectPath.isInDMG()?{level:"error",msg:"PhotoStructure cannot run directly from a DMG disk image. Please drag and drop the PhotoStructure icon onto your Applications folder to install.",checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure isn't running directly from a DMG disk image"}}):void 0))},85200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const r=i(45599),s=i(96175),n=i(18454);t.osHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating system…",settings:[],links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,s.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,s.osFullName)()]}:{level:"warn",msg:["Operating system is not supported",(0,s.osFullName)()+" was detected, but only "+e+"."]}}})))},37301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(98314),a=i(43334),o=i(24399),l=i(63335),u=i(18454);t.powershellHealthCheck=(0,s.defer)((()=>a.isWin?u.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShell…",settings:["powerShellArgs"],ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,o.checkPowerShell_)();return{level:"ok",msg:["PowerShell is OK",(0,l.ver)(e)],meta:{version:e}}}catch(e){return{level:"error",msg:"PowerShell failed: "+(0,n.errorToS)(e)}}}}):void 0))},65756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(27180),a=i(98314),o=i(63335),l=i(18454);t.sqliteHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLite…",settings:[],links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await n.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,r.li)(["embedded: "+(0,o.ver)(e.libraryVersion),(0,r.tt)(e.sqliteNativePath)+": "+(0,o.ver)(e.toolVersion)])]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,a.errorToS)(e)}}}})))},15024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(31586),o=i(94174),l=i(77740),u=i(44198),c=i(59958),d=i(43334),h=i(18454);t.securityHealthCheck=(0,n.defer)((()=>{const e=d.isWin?"an administrator":"root";return h.HealthCheck.for({section:"System",id:"proc-not-superuser",pendingMsg:"Checking user permission level…",settings:[],later:async()=>{if("0"===(0,u.env)().PUID)return{level:"disabled",msg:`Admin health check is disabled (${(0,s.tt)("PUID=0")}).`};const t=(0,r.compact)([(0,a.gte0)((0,o.userid)())?"Current user id: "+(0,s.b)((0,s.tt)((0,o.userid)())):void 0,(0,a.gte0)((0,o.groupid)())?"Current group id: "+(0,s.b)((0,s.tt)((0,o.groupid)())):void 0,"Current user name: "+(0,s.b)((0,s.tt)(await(0,o.username)()??"(unknown)"))]);return!0===await(0,o.isRootUser)()||(0,l.getDevEnvFlag)(c.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK)?{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]}:{msg:["PhotoStructure is not running as "+e,...t],level:"ok"}}})}))},3956:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(12168),a=i(28874),o=i(63225),l=i(18454);t.settingsEnvHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settings…",settings:[],links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,a.allSettings)())if(t.hasValue()&&null!=t._envValue()){const i=!0===t.opts.sensitive?"********":t.toEnvValue(t._envValue());null!=i&&e.push((0,r.tt)(t.key+"="+i))}const t=[(0,n.plur)(e.length,"environment setting"),(0,r.li)(e)],i=(0,o.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,r.li)(i.map((e=>(0,r.tt)(e.envKey)+": "+e.msg))),"---",...t]}:{level:"ok",msg:t}}})))},29332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(45599),s=i(2858),n=i(18454),a=i(61274);t.settingsLibraryHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settings…",settings:["libraryDir"],links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")})))},61274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=t.validateSettingsToml=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(12168),o=i(81168),l=i(98314),u=i(95696),c=i(2858),d=i(32707),h=i(18454);async function f(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.tt)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.tt)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,a.plur)(i.settings.length,t+" setting override"),(0,s.b)("Source:"),(0,s.tt)(e),(0,s.b)("Settings:"),(0,s.li)(i.settings.map((e=>(0,s.tt)(e.key+"="+e.toEnvValue(e.value)))))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,l.errorToS)(t)}}}t.validateSettingsToml=f,t.settingsSystemHealthCheck=(0,n.defer)((()=>h.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settings…",settings:[],links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>f(u.PosixFile.forMaybe((0,d.systemSettingsFile)()),"system")})))},38372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpHealthCheck=void 0;const r=i(45599),s=i(98314),n=i(21473),a=i(18454);t.sharpHealthCheck=(0,r.defer)((()=>a.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharp…",settings:[],later:async()=>{try{return await(0,n.testSharp_)(),{level:"ok",msg:["Sharp is OK","Image processing is working as expected."]}}catch(e){return{level:"error",msg:["Something's amiss with Sharp",(0,s.errorToS)(e)]}}}})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},49913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(31586),o=i(28874),l=i(14854),u=i(18454);t.systemLoadHealthCheck=(0,n.defer)((()=>u.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system load…",settings:["cpuBusyPercent"],ttlMs:s.minuteMs,later:async()=>{if(o.Settings.cpuBusyPercent.valueOrDefault<=0)return{level:"ok",msg:["CPU utilization is not monitored",(0,r.tt)(o.Settings.cpuBusyPercent.key)+" is set to <= 0"]};const e=l.CpuUsage.instance().busyPct(),i=(0,l.isTooBusy)();return(0,t.systemLoadHealthCheck)().setTTL((i?6:60)*s.secondMs),{level:i?"stop-sync":"ok",msg:"CPU utilization is "+(0,a.fmtPct)(e)+"\n"+(i?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause if CPU utilization exceeds")+" "+(0,r.tt)(o.Settings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(o.Settings.cpuBusyPercent.valueOrDefault)}}})))},84728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(40044),a=i(18454);t.versionHealthCheck=(0,s.defer)((()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure version…",settings:["autoUpdateCheck","configDir","libraryDir","optOut"],ttlMs:r.hourMs,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:n.checkVersion_})))},7245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(41400),a=i(55835),o=i(34102),l=i(66106),u=i(45969),c=i(63335),d=i(18454);t.videoHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-video",pendingMsg:"Checking video tooling…",settings:["ffmpegPath"],links:[{text:"Read how to set up video support with PhotoStructure",url:"https://photostructure.com/getting-started/video-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getVideoToolDetails_)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["Videos will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["Videos will not be imported","No video tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.videoHealthCheck.prior()?.reset()))}))},16264:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(13538),l=i(83104),u=i(12168),c=i(48884),d=i(45255),h=i(43334),f=i(69108),m=i(48165),p=i(63870),g=i(7014),y=i(18454);t.volumeHealthCheck=(0,a.defer)((()=>y.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,pendingMsg:"Checking volumes…",settings:[],links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:h.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=Date.now(),i=await(0,o.thenOrTimeout)((0,g.volumes)(),(0,p.commandTimeoutMs)());if(i===l.Timeout){const i=await(0,o.thenOrTimeout)(h.isWin?(0,m.getLocalVolumesWin_)():(0,f.dfPosixRawLocal_)(),d.ShortCommandTimeoutMs);return(0,t.volumeHealthCheck)().logger.warn("volumes() timed out, retrying in 5m"),setTimeout((()=>(0,t.volumeHealthCheck)().refresh()),5*n.minuteMs),{level:"warn",msg:[i===l.Timeout?"Something seems wrong with your computer's volumes":"Something seems wrong with one or more remote filesystem mounts","Gathering volume metadata took longer than "+(0,n.fmtAgo)(e,"")+"."]}}const a=i.filter((e=>!1===e.ok));if((0,r.isNotEmpty)(a))return{level:"warn",msg:["One or more volumes are not healthy","Check the following:",(0,s.li)(a.map((e=>(0,s.tt)(e.mountpoint))))]};const[y,v]=(0,c.partition)(i,(e=>!0===e.remote)),w=["Storage volumes are OK"];return(0,r.isNotEmpty)(v)&&w.push((0,s.b)((0,u.plur)(v.length,"local volume")+":"),(0,s.li)(...v.map((e=>(0,s.tt)(e.mountpoint))))),(0,r.isNotEmpty)(y)&&w.push((0,s.b)((0,u.plur)(y.length,"remote volume")+":"),(0,s.li)(...y.map((e=>(0,s.tt)(e.mountpoint))))),{level:"ok",msg:w}}})))},95242:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),v=i(57159),w=i(83278),b=i(95696),S=i(62105),P=i(84258),_=i(38156),M=i(69589),T=i(28874),E=i(47783),k=i(29990),D=i(16047),x=i(42725),C=i(4192),F=i(32876),A=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class O{constructor(e,t,i){r.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,M.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(r=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,S.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await n(this,r,"m",s).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:n,height:a,sha:l,mimetype:u}=t;if(null==s||null==n||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:n,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(x.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(r,s)){const n=(0,k.fitSizes)(e,e.mimetype),a=(0,o.diff)(r,s);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=n.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:n});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=O,s=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},x.ImageSize.sq().length+x.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:x.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,D.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,k.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=x.ImageSize.largestSq(),b=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,h.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of l){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&r.reducer===F.Fit&&T.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of x.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=T.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(r)+" -> "+(0,u.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,C.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),v=i(70417),w=i(35721);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},33106:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(9288)),n=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(e);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(40958),s=i(33374),n=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),s=i(54993),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),s=i(19851),n=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(9288)),n=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),v=i(88561),w=i(95696),b=i(17217),S=i(50213),P=i(23624),_=i(28874),M=i(12089),T=i(16170),E=i(1078),k=i(33106),D=i(86580),x=i(78011),C=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const A=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,D.fitToResolution)(i.dimensions,Math.round(_.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,D.fitToResolution)(i.dimensions,_.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?k.dctHash:k.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,M.shim1)({name:"img.imageHash",cache:A,impl:I}),t._imageHash_=I,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},80361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(33374),l=i(57924),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(21605),m=i(48884),p=i(50213),g=i(97352),y=i(85810),v=i(3048),w=i(32848),b=i(82647),S=i(38812),P=i(70417),_=i(23624),M=i(28874),T=i(86580),E=i(48368),k=i(2090),D=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function F(e,t,i=E.HashDim){const r=(0,_.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function A({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,r),l=F(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));D().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function I(e,t,i="debug",r={}){return D().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=A({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(r,s)}),m=A({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=A({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void D().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,v=(0,T.aspectRatio)(r),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let _=0,x=0;n&&(x+=M.Settings.imageHashFuzzyDateDelta.valueOrDefault,_+=M.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=M.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,_+=M.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(_+=M.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=M.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((_+(i.minImageCorr??M.Settings.minImageCoeffPct.valueOrDefault))/100),I=R((x+(i.minColorCorr??M.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,k.fmtAspectRatio)(v)} vs ${(0,k.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=I,z=j&&N.avg>=F;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:_,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:I,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return D().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=F(e,t,i);return f.Rotations.map((e=>(0,_.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=A,t.isSimilarImage=I,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return I(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},42725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},4192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},78011:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(9288)),n=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},48604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),s=i(31586),n=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(9288)),n=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,n.lazy)((()=>{s.default.simd(l.Settings.enableSIMD.valueOrDefault),s.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),s.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(77988),n=r(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),v=i(56519),w=i(56038),b=i(57159),S=i(95696),P=i(17217),_=i(28874),M=i(47783),T=i(16170),E=i(95141),k=i(54979),D=i(1078),x=i(63870),C=i(86580),F=i(277),A=i(16047),I=i(13940),O=i(5733),L=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,M.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await z(e,t))?.nativePath}async function j(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes<_.Settings.maxEmbeddedBuffer.valueOrDefault;try{const t=await B(e,i,l);if(null==t)return;const s=(0,n.default)(t,{failOn:_.Settings.imageFailOn.valueOrDefault}),o=await s.metadata(),u=(0,C.aspectRatio)(o);if(null!=a&&null!=u&&!(0,h.closeTo)(a,u,.2))return void N().info("imgFromExif("+e+", "+i+"): rejecting (aspect ratio mismatch)",{fileAspectRatio:a,renderedAspectRatio:u});const c=(0,C.lteBoth)(r,o);return N().debug("imgFromExif("+e+", "+i+")",{valid:c,minDim:r,useBuffer:l,fileAspectRatio:a,renderedAspectRatio:u,dim:(0,f.pick)(o,"width","height")}),c?{sharp:s,file:(0,m.isString)(t)?S.PosixFile.for(t):void 0}:void 0}catch(t){return void N().info("Failed to read image from EXIF tag "+i,{src:e,error:t})}}async function z(e,t){const i=t.toLowerCase().endsWith("tiff")?".tiff":".jpg";try{const r=await(0,I.tmpImageFile_)({src:e,tag:t,ext:i});return await r.applyIfEmpty_({retries:2,fn_:i=>(0,M.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=j,t.toSharp=function(e){const t=e;if((0,O.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:_.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=N().addParameterContext(e.nativePath);(0,O.setupSharp)();const n=await(0,k.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,D.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const I=(0,C.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),z=(0,T.isSharpMimeType)(n)&&null==t,V=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||z||V)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:z,isMirrorOrientation:V});else{const i=!1,n=await(0,M.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[..._.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(..._.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>j(e,n,t,x,I)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,F.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,F.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,L.isVideoSupported)())try{return await(0,v.thenMap)((0,L.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,w.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=z},21473:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=void 0;const s=r(i(34589)),n=i(76760),a=r(i(9288)),o=i(50357),l=i(98553),u=i(68708),c=i(23560),d=i(43899),h=i(28874),f=i(5733);t.testSharp_=async function e(t){try{(0,f.setupSharp)();const e=t??(0,n.join)(d.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(e,{failOn:"error"}),r=await i.resize(24,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,o.eql)((0,u.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:24,height:32,channels:3}),"Unexpected sharp output: "+(0,l.stringify)(r.info))}catch(i){if(!(0,c.isWorkerService)()&&h.Settings.enableSIMD.valueOrDefault)return h.Settings.enableSIMD.envValue=!1,e(t);throw i}}},181:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(9288)),n=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),v=i(54979),w=i(63870),b=i(5733),S=i(50961),P=i(66106),_=i(51210),M=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void M().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=M().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&M().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(M().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,_.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))M().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),v=i(56038),w=i(31562),b=i(98314),S=i(34102),P=i(88561),_=i(95696),M=i(17217),T=i(74128),E=i(31843),k=i(70417),D=i(33847),x=i(28874),C=i(94678),F=i(43207),A=i(47783),I=i(16170),O=i(95141),L=i(1078),R=i(63870),N=i(89782),B=i(13940),j=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,j.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,E.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function H(e){return await(0,t.isVideoSupported)()?_.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0}async function q(e,t){const i=V("extractVideoFrame",e),r=_.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,j.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,B.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,A.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,N.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,F.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,j.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,A.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,j.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,A.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,F.extractDurationSec)(i);if(!(0,c.gt)(n,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=H,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await G())return;const n=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,A.readTags)(e),h=(0,L.extractSizeInfoFromTags)(d),m=(0,F.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,A.readRawTags)(t),r=await(0,A.readRawTags)(e),s=(0,F.extractDurationSec)(r),n=(0,F.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),s=x.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,C.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,v.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:r.halt,...g},m=x.Settings.transcodeMaxDim.valueOrDefault,p=(0,k.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,j.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-n})}catch(t){throw(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:Date.now()-n}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await H(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,j.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),v=i(84258),w=i(28874),b=i(76280),S=i(63870),P=i(19769),_=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function M(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:w.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=M;const T=/ffmpeg version n?(?\S+)/i,E=(0,u.lazy)((async()=>{const e=await M();if(null==e)return void _().info("failed to find ffmpeg in $PATH",{ffmpegPath:w.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=T.exec(t.result)?.[1];return _().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){E.unset(),t.ffmpegVersionDescription.unset()}function D(e){const t=e?.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function x(e){const t=[...w.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(w.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=w.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(E(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",k),(0,g.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await E.prior()??E.refresh()},t.isFFmpegSupported=async function(){return null!=await E()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await M(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=x,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await M(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...x(t),...F(t),...D(t),"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){_().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,v.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return _().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return _().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await M(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(19851),s=i(42659),n=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),v=i(89782),w=i(13940),b=i(42725),S=i(19769),P=(0,r.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,w.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>k(e,t)})};const _=["-T"],M=["-Z","-"],T=["-o","1"],E=["-t","0","-j"];async function k(e,t){const i=await(0,v.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=b.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[..._,...M,...T,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],w={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:w});const k=(0,c.execFile)(g,y,void 0,w),D=[];function x(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});D.push(r)}}if(k.on("error",x),k.stderr.on("data",x),await t.writeStream_(k.stdout),(0,s.isNotEmpty)(D))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:D,path:e.nativePath});(0,c.endProcess)(k)}t.dcraw_emu_=k},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),v=i(50213),w=i(56519),b=i(76596),S=i(46292),P=i(87290),_=i(77740),M=i(34102),T=i(83278),E=i(28874),k=i(37692),D=i(71706),x=i(83950),C=i(72042),F=i(33603),A=i(48132);t.k=(0,y.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,C.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,_.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function L(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:x.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,F.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await L((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,A.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function B(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=L,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await L(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof x.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,_.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,F.sids)({timeoutMs:A.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),s=(n=(0,l.flatten)((await(0,w.someOrTimeout)([()=>function(e){return L(E.Settings[(0,t.k)().L].value,"Settings",A.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:A.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,f.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l))),(e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,o.later)((()=>{(0,M.ee)().on("clearCache",(()=>t.m.unset())),(0,M.ee)().on((0,t.k)().c,(()=>t.m.unset())),k.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=B,t.l=async function(){try{return await B()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await B()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},84194:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(40958),a=i(76790),o=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),h=i(19851),f=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(45599),o=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),h=i(50213),f=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),v=i(45879),w=i(70854),b=i(57902),S=i(72308),P=i(43334),_=i(24399),M=i(7014),T=i(30933),E=i(71706),k=i(84194);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const D=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,k.toUID)(k.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function A(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(F)))}async function I(){return P.isLinux?(await A("lm")).map((e=>(0,k.toUID)(k.S.lm,e))):void 0}async function O(){return P.isLinux?(await A("lp")).map((e=>(0,k.toUID)(k.S.lp,e))):void 0}async function L(){return P.isLinux?(await A("lb")).map((e=>(0,k.toUID)(k.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,k.toUID)(e,t)))}catch(e){return void D().warn((0,t.k)().i+" failed",e)}}async function N(){return(await _.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,k.toUID)(k.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,k.toUID)(k.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,k.toUID)(k.S.bm,(0,r.compactBlanks)(await A("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,k.toUID)(k.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,k.toUID)(k.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,k.toUID)(k.S.nm,e)))}async function H(){return(0,c.toA)(await(0,M.volumes)()).map((e=>(0,k.toUID)(k.S.vl,e.uuid)))}const q=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,I,O,L,B,U,H],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)q.add(e);return D().tap({msg:"sids()",result:(0,k.sortUids)([...q,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,f.isTest)())for(const t of e)q.add(t)},t.clearSids=function(){(0,f.isTest)()&&q.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),s=i(23560),n=i(66184),a=i(72210);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),s=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),s=i(42659),n=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},12495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(19851),s=i(42659),n=i(23560),a=i(79267),o=i(32144),l=i(28874);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isLogExt)(e.ext)})))},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),s=i(31586),n=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),s=i(57902);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,s.set(this,[]),n.set(this,(0,l.lazy)((()=>{o(this,s,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,s,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,n,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,r,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,r,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){if(null==e||0===o(this,s,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,s,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),s=i(50989),n=i(28874);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=n.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),s=i(76760),n=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),b=i(38836),S=i(99331),P=i(42638),_=i(76596),M=i(98314),T=i(89968),E=i(29882),k=i(28874),D=i(28981),x=i(20839),C=i(21727),F=i(66184),A=i(57902),I=i(72210),O=i(98192);function L(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,k.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(A.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,M.errorToS)(t))))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,_.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,M.errorToS)(e))))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,M.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),s=i(82328),n=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),b=i(23560),S=i(81168),P=i(78406),_=i(25764),M=i(20197),T=i(14977),E=i(36868),k=i(28874),D=i(32105),x=i(20839),C=i(21727),F=i(66184),A=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:_.EndableRanks.logger,unref:!0,onEnd:()=>c(this,s,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,A.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,M.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),k.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),s=i(84542),n=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),s=i(76790),n=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),s=i(41400),n=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),b=i(24068),S=i(43705),P=i(51879);function _(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),M();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new S.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,n.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&b.LogTail.instance()}function M(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=_,t.setupLogFormatter=M,(0,s.later)((()=>{h.Settings.logStdout.watchLater(_),h.Settings.logDir.watchLater(_),h.Settings.tailLogs.watchLater(_),h.Settings.logColor.watchLater(M),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},82647:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p69(){return n(this,r,"m",s).call(this,.5)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,s=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},44983:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(76790),s=i(93973);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},36372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(76790),s=i(42659),n=i(31586),a=i(97238),o=i(50597),l=i(9103),u=i(55222);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},38812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(21605);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}×${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),s=i(65713);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),s=v(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(38522),s=i(22573),n=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(48161)),n=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),b=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==b.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=S.exec(e)}function _(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=_,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=_(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void M().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const M=(0,s.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=_(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return M().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(M().warn("No name found for "+e),e):i}catch(t){return M().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),s=i(19851),n=i(54993);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(22573),s=i(51926),n=i(83556);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),s=i(59455),n=i(31562);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),b=i(54993),S=i(54557),P=i(19851),_=i(50213),M=i(88158),T=i(409),E=i(78406),k=i(25764),D=i(99331),x=i(56519),C=i(46292),F=i(8769),A=i(83278),I=i(32144),O=i(29882),L=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),j=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,O.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,T.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??L.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,f.isEmpty)(s))return B().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,N.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){B().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!z(r,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:r}),a.push(W(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,F.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,s,"f").delete(l),o(this,s,"f").getOrSet(l,(async()=>{const i=o(this,r,"m",n).call(this,e.pid),s=(0,v.opt)((0,M.Try)((()=>(0,O.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:s,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,s,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,r,"m",n).call(this,e);return(0,x.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new E.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:k.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=U,s=new WeakMap,a=new WeakMap,r=new WeakSet,n=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new U(A.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const s=i(31421),n=i(48161),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),b=i(56519),S=i(84777),P=i(8103),_=i(45879),M=i(43334),T=i(24399),E=i(45643),k=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){if(M.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,_.readFileMaybe)("/proc/"+i+"/stat")));return k().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,E.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,M.isWin?I:N)).filter((e=>D(e)&&t.includes(e.pid)));return k().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=D,t.pidInfo=async function(e){return(0,b.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,b.thenMap)((0,E.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const C="Get-Process",F="| Select-Object -Property Id,ProcessName,StartTime";function A(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(T.PowerShell.instance().ended)return R(e);const t=[C,"-Id",A(e),"-ErrorAction SilentlyContinue",F].join(" ");return(0,b.thenMap)(T.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===a.default.pid))||r.push({pid:a.default.pid,start:new Date(v.StartTs),cmd:"node "+a.default.title}),r}async function N(e){return t=(await(0,S.stdoutResult_)("ps",["-p",A(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(M.isLinux)return(0,c.toGt0)((0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){k().warn("clk_tck failed",{error:e})}return 100})),j=(0,g.lazy)((()=>Date.now()-(0,n.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,s=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(s)?{pid:i,cmd:r,start:new Date(j()+s/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),s=i(42659),n=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),b=i(31562),S=i(84777),P=i(34102),_=i(43334),M=i(28874),T=i(63870),E="{ready}",k=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",M.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(M.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:M.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),M.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(M.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,k),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,k),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),s=i(91655),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874),l=(0,n.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,s.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,s.pick)(e??{},"retries","halt","path"),...(0,s.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),s=i(22573),n=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){_(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&M()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(m.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const b=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],S={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function _(e){for(const t of b)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:S;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function M(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=_,t.disableExternalNetworkRequests=M},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),s=i(53265),n=i(87652);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},4936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(55835),l=i(51926),u=i(50213),c=i(81168),d=i(79842),h=i(21330),f=i(51275),m=i(29882),p=i(28874),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+e.replace(/'/g,"′")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),s=i(83556);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),b=i(44198),S=i(96706),P=i(34102),_=i(28283),M=i(81075),T=i(98778),E=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?n(this,r,"m",s).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?n(this,r,"m",s).call(this,e??t)+": "+i:null==this.fromEnv(e)?n(this,r,"m",s).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,S.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,b.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return M.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,b.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&S.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,b.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&S.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,S.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],E.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],E.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+r],E.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,T.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,T.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,T.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,s=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),s=i(51168),n=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),b=i(7282),S=i(12801),P=i(4328),_=i(70488),M=i(84248),T=i(5531),E=i(99315),k=i(34365),D=i(34580),x=i(96706),C=i(50274),F=i(33866),A=i(52086),I=i(48584),O=i(45969),L=i(43334),R=i(24540),N=i(70379),B=i(71300),j=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),H=i(30577),q=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Y=i(71988),Z=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),se=i(57039),ne=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(b.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function be(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:be}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:be}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new se.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>q.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:q.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>q.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),minDelayBetweenSpawnMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ne.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:M.AutoVacuumModes,defaultValue:M.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:T.CheckpointTypes,defaultValue:T.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:k.SynchronousModes,defaultValue:k.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,O.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:F.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:H.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":s.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new ne.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:A.CropStrategies.attention,strEnum:A.CropStrategies}),videoFrameAtSec:new ne.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>j.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new se.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ne.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new ne.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function Se(e){const i=((0,u.blank)(e)?"":e).split(n.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(n.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=Se,t.pathWithDefaults=(0,a.lazy)((()=>Se((0,x.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(31586),n=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{w.Settings.configDir.opts.defaultValue=o.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,n.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,n.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,s.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),b=i(81168),S=i(83556),P=i(87290),_=i(98314),M=i(34102),T=i(83278),E=i(95696),k=i(60865),D=i(4175),x=i(83179),C=i(81075),F=i(28874),A=i(41692),I=i(84438),O=i(32707),L=i(6707),R=i(98778),N=i(55018),B=i(10357),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,O.systemSettingsFile)()){if(null!=e)return X(T.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,L.readTomlFile_)((0,O.systemSettingsFile)()))?.[F.Settings.libraryDir.name])}catch{return}}function U(e){return(0,L.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function H(){return U((0,O.systemSettingsFile)())}function q(e){return U(z(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:F.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,M.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,x.settingsToObj)(i),wip:r}),r){const t=await(0,L.readTomlFile_)(s),i=await(0,L.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function K(e=(0,O.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,F.persistedSystemSettings)()),t}function Y(e){return X(z(e))}async function Z(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,F.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,F.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function Q(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,L.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,F.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,F.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}})));return t.info("loaded",{settings:(0,x.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,D.handleDeprecatedSettings)(),(0,D.handleMetaSettings)(a),{settings:a,warnings:n}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Y()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return F.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=H,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await H()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await q()&&await Z()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,M.ee)().on("clearCache",G),(0,M.ee)().on("settingsChanged",G),F.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,k.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(E.PosixFile.for(e),(0,F.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=Z,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([F.Settings.noNetwork,F.Settings.httpPort,F.Settings.license,F.Settings.logStdout,F.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(F.Settings))ee().has(e.key)||e.unset();(0,M.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),F.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(E.PosixFile.forMaybe((0,O.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,M.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${k.versionMajorMinor}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,s=e.strEnum,(0,r.compact)((0,a.splitStringArray)(i)?.map((e=>s.getCI(e))));var i,s},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),s=i(55835),n=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),s=i(44652),n=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},63225:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=void 0;const r=i(68708),s=i(81168),n=i(44198),a=i(59958),o=i(28874);t.verifyPsEnvSettings=function(e=(0,n.env)(),t=.25){const i=[];for(const n of(0,r.keys)(e).filter((e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!a.IgnorableEnvKeys.includes(t)}))){const r=e[n],a=(0,o.ciSettings)().lookup(n);if(null!=a){const e=a.value.whyInvalidEnvValue(r);null!=e&&i.push({envKey:n,msg:e})}else{const e=(0,o.ciSettings)().lookupNearest(n,t);null==e?i.push({envKey:n,msg:`No setting was found like "${n}"`}):(0,s.equalsIgnoreCase)(e.key,n)||i.push({envKey:n,msg:`Did you mean setting "${e.value.key}"?`})}}return i}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),s=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),s=i(81168);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),v=i(81168),w=i(76596),b=i(79842),S=i(66649),P=i(21330),_=i(98725),M=i(928),T=i(54261),E=i(89724),k=i(17415),D=i(88600),x=i(51275),C=i(29882),F=i(17217),A=i(68284),I=i(57902),O=i(28874),L=i(65162),R=i(71300),N=i(14036),B=i(61424),j=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,b.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,F.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,b.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,A.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,_.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,k.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,k.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,w.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,x.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,T.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,M.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,x.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,k.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,b.datedToStartDateTime)(this.date)??(0,b.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,b.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function H(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],s=r;if((0,D.isValidDate)(t)){if((0,k.isValidZone)(e.tz)&&(!(0,x.hasZone)(t)||R.OverrideUTCZoneTags.includes(s))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,v.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,b.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,b.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,b.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,x.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function q(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,_.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,b.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,_.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,v.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",H(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??s("tags",H(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("stat+bname",await(0,B.extractStatBname)(e)))??(n?void 0:s("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",q(e,t)))??(n?void 0:s("path",G(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await $(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return H(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),s=i(97352),n=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(77988),n=r(i(76760)),a=r(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),v=i(12168),w=i(56038),b=i(4867),S=i(36557),P=i(98247),_=i(21330),M=i(98725),T=i(23467),E=i(88561),k=i(95696),D=i(17217),x=i(16287),C=i(50213),F=i(17921),A=i(7282),I=i(88158),O=i(23560),L=i(28874),R=i(12089),N=i(81168),B=i(63870),j=i(15674),z=i(28544),V=i(43207),W=i(72180),U=i(75767),H=i(12788),q=i(80495),G=i(14036),$=i(67083),J=i(3432),K=i(28630),Y=i(15912),Z=i(30748),X=i(16170),Q=i(95141),ee=i(7330),te=i(54979),ie=i(1078),re=i(61424),se=i(8791),ne=(0,o.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,S.batchClusterOptions)((0,A.isTest)()?8:(0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeoutError)({p:le().version(),timeoutMs:L.Settings.statTimeoutMs.valueOrDefault})},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,B.commandTimeoutMs)()})))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,N.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),s=await e.sidecar(),n=(0,X.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,X.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=k.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void ne().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ne().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,X.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,M.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values])if(!(0,W.isUtcTagName)(t)){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,_.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l)}const c=o?(0,Z.extractMakeAndModel)(n):await(0,re.inferMakeAndModel)(e,n);c.Make!==(0,Z.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,Z.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(n),h=await(0,z.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,q.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,V.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};(0,A.isTest)()&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=k.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("exiftool.overwriteTags:"+e,(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("exiftool.writeTags:"+e,(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await me(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=k.PosixFile.for(t),s=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:s}),await le().write(r.nativePath,s,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...L.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,G.isVideoExt)(n.default.extname(e))?[]:["-fast"]],r=await(0,w.time)("exiftool.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),ae&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ge},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function _(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function M(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([_(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(_)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=M,t.findInequalFields=function(e,i){const r=M(e),n=M(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),s=i(40958),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),s=i(45599),n=i(68708),a=i(50213),o=(0,s.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,n.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:s}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[s])&&(t[i]=t[s]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,n.pick)(e,"Directory","FileName"));for(const t of(0,n.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),v=i(50213),w=i(81168),b=i(66649),S=i(17415),P=i(29882),_=i(95696),M=i(17217),T=i(28874),E=i(47783);function k(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=k,t.mkHistoryRecord=D,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function A(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,M.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=_.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=A,t.ensureInferredHistoryRecords=async function(e,i,r){const s=k(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?A(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),I(i,s,n)},t.ensureHistoryRecords=I},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(53705)),n=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),w=i(14245),b=i(61424),S=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,w.omitInvalidGeolocationTags)(t);{const e=_(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=M(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function _(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return S().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function M(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,u.toDated)(t[r]);if(null==s||(0,f.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return S().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return S().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=_,t.inferTzOffsetMinutesFromFilename=M},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function _(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function M(e){return Array.isArray(e)&&e.every(M)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(M))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(M))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=_,t.isKeywordStruct=M,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=_(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(M(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},38010:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(50213),g=i(84885),y=i(66649),v=i(98725),w=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function _(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-_(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),s=i(54993),n=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},66039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(75020),u=i(59455),c=i(50213),d=i(68852),h=i(81168),f=i(70417),m=i(28874),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,v=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,w=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,v),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function _(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,w),null!=e&&(_(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const M=(0,s.compactBlanks)(t.split(/\s+/)),T=l.length,E=b.length;if(M.length>0)if(0===T&&E>0)l.push(...M);else if(0===E&&T>0&&1===M.length)b.push(...M);else if(1===M.length)l.push(...M);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?M.pop():M.shift()),l.push(...M)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function _(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function M(e,t,i){return _("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=_([t.modifier,t.lifespan]),r=_(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?_([r,e]):M(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),s=i(54993),n=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),s=i(40958),n=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,s.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},3127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(54993),s=i(42231);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),v=i(79842),w=i(21330),b=i(98725),S=i(51275),P=i(35280),_=i(19748),M=i(88561),T=i(95696),E=i(65238),k=i(17217),D=i(57902),x=i(28874),C=i(80496),F=i(65162),A=i(28544),I=i(47783),O=i(88840),L=i(30748),R=i(16170),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new M.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,_.extFilter)(O.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7,i=!0){if(!await j(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(r,(e=>(0,F.bname)(e))),n=(0,k.findFileIndex)(e,s);if(n<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),q(e,t,!1)):void 0;const l=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[s.slice(n-2*t,n),s.slice(n+1,n+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=H(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),s=i(22573),n=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),s=i(57975),n=i(57160),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(T(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function M(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?M:_;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:_(o,!1)),r}function k(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+k(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=T;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(D)?e.replace(D,(e=>k(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),s=i(40958),n=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),s=i(22573),n=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(9103),a=i(37628);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},50036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=void 0;const r=i(46292),s=i(95696);t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")}},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),s=i(30577);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),s=i(22573),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},27274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.semverGte=t.semverLatest=void 0;const r=i(54993),s=i(48884),n=i(76280),a=i(30577);function o(e){const t=(0,n.toSemver)(e),i=a.UpdateChannels.ordinal((0,a.extractUpdateChannel)((0,r.toS)(e)));return null==t?void 0:[t.major,t.minor,t.patch,i,...t.prerelease.slice(1)]}function l(...e){return(0,s.greatestBy)(e,o)}t.semverLatest=l,t.semverGte=function(e,t){return l(e,t)===e}},38244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateChannelVersion=void 0;const r=i(68708),s=i(51926),n=i(30577);t.isUpdateChannelVersion=function(e){return(0,r.isObject)(e)&&n.UpdateChannels.has(e.channel)&&(0,s.isString)(e.version)}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},63335:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=void 0;const r=i(22573);t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v|ver|version)?\s*/,"version ")}},40044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=t.checkVersion_=t.currentChannel=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(75240),l=i(17344),u=i(50213),c=i(37805),d=i(5916),h=i(46292),f=i(16287),m=i(43205),p=i(28874),g=i(63870),y=i(89372),v=i(50036),w=i(60865),b=i(27274),S=i(38244),P=i(30577),_=i(63335),M=(0,a.defer)((()=>(0,u.mkLogger)("VersionCheck")));t.currentChannel=function(){const e=[p.Settings.updateChannel.valueOrDefault,(0,w.channel)()].map((e=>P.UpdateChannels.ordinal(e))).sort()[0];return P.UpdateChannels.values[e]??p.Settings.updateChannel.valueOrDefault},t.checkVersion_=async function(e){if(p.Settings.noNetwork.valueOrDefault)return{level:"disabled",msg:["PhotoStructure version checking is disabled","Set "+(0,s.tt)(p.Settings.noNetwork.toEnvLine(!1))+" to enable."]};if(!p.Settings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===p.Settings.optOut.value?e.push("Set "+(0,s.tt)(p.Settings.optOut.toEnvLine(!1))+" to enable."):!1===p.Settings.autoUpdateCheck.value?e.push("Set "+(0,s.tt)(p.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.tt)(p.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,h.configDir)();if(null==i||!await(0,f.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const u=e?.installedVersion??c.version,d=(0,P.extractUpdateChannel)(u),m=(0,P.eligibleForChannel)(d),g=a.versions.filter((e=>m.includes(e.channel))).map((e=>e.version)),y=e?.latestVersion??(0,b.semverLatest)(...g);if(null==y)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+p.Settings.updateChannel.toEnvLine()]};const v=(0,P.extractUpdateChannel)(y),w="You are running "+(0,l.EditionName)()+" "+(0,_.ver)(u),S="The latest published "+(0,s.tt)(v)+" build is "+(0,_.ver)(y),M=v===d?void 0:"You should consider switching to the "+(0,s.tt)(v)+" channel.",T=Date.now()-a.updatedAt,E="Last checked "+(T{const e=(0,v.channelVersionsCache)(),i=await(0,y.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",headers:{"User-Agent":await(0,m.userAgent)()},cache:e,ttlMs:n.dayMs,preCacheTransform:e=>({versions:e,updatedAt:Date.now(),updatedByVersion:c.version})}),r=i.data;if(null==r||!Array.isArray(r.versions)||0===r.versions.length||r.versions.some((e=>!(0,S.isUpdateChannelVersion)(e)))||r.updatedByVersion!==c.version){if(i.fromCache)return M().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();M().throw("getChannelVersions_(): Invalid response",{result:r})}return M().tap({msg:"getChannelVersions_()",result:r})}})},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),s=i(9595),n=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},42233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(45200),s=i(98770),n=i(7014);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),s=i(22573),n=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),b=i(24541),S=i(60224),P=i(63870),_=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const M=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(M)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(T(e),(e=>e+":\\"))}function k(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=k,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function A(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function I(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(D)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(A)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=A,t.volumeInfoWin=I},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),b=i(16287),S=i(45969),P=i(43334),_=i(69108),M=i(98770),T=i(44224),E=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const k=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?k().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):k().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(k().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void k().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await D(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,E.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,M.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void k().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),s=i(5233),n=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),_=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),s=i(19851),n=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),b=i(8769),S=i(34102),P=i(17217),_=i(16287),M=i(43334),T=i(28874),E=i(8540),k=i(68884),D=i(44224),x=i(24541),C=i(69375),F=i(63870),A=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function O(e=(0,F.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function L(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{T.Settings.libraryDir.watchLater(I),T.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&T.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(M.isMac&&(e.info("Setting up Mac diskutil activity watcher"),O((0,F.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),M.isLinux){const i=(0,D.maybeWatchProcMounts)();await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),O((0,F.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),O((0,F.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",M.isWin?x.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,F.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(M.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return M.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,S.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),I()})),T.Settings.mountpointsTtlMs.watch(O)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>L(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),L()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!M.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,F.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>L(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),b=i(68884),S=i(59107),P=i(69375),_=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await k()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,b.isGioSupported)())try{await(0,c.thenMap)((0,b.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){_().warn("Failed to fetch gio volumes",e)}return e};const M="/proc/mounts";function T(e){return!v.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function k(e=M,t=T,i=E){if(y.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return _().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return _().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void _().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=T,t.readProcMounts=k,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(M)?new h.FileWatcher(M,{recursive:!1,persistent:!1},(()=>{_().info("detected change in "+M),(0,d.setUnrefTimeout)((()=>S.mountpoints.refresh()),n.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),s=i(42659),n=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await T()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function M(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,u.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=M;const T=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?M():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(_(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),s=i(12168),n=i(28874);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),b=i(28874),S=i(59107),P=i(63870),_=i(68995),M=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),T=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function E(e){return(0,a.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function k(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=k(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(b.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of b.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),r=await D(i).catch((e=>M().info("Failed to read "+i,{error:e})));if(null!=r)return M().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,_.volumeUuidSubpath)());if("/"===e.mountpoint)return M().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(b.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return M().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(b.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,_.writeVolumeUuid)(e);if(!(0,n.blank)(t))return M().tap({msg:"readVolumeUUID(): wrote new "+(0,_.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return M().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>T.clear())),S.mountpoints.watchLater((()=>T.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(E(e))return;if((0,a.isFalse)(e.ok))return;const t=await T().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>M().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=E,t.toVolumeUUID=k,t.readUuidFile_=D,t.readVolumeUUID=x},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),b=i(50213),S=i(7282),P=i(23560),_=i(28850),M=i(45255),T=i(81168),E=i(56519),k=i(4867),D=i(49776),x=i(9595),C=i(77740),F=i(44198),A=i(96706),I=i(8769),O=i(57159),L=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),j=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),H=i(43334),q=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Y=i(27461),Z=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=s.default.platform(),ne=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,ne),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,x.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ne.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:se}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))n.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:M.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,q.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==q.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function me(e,i){const r=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(r))return;const s=await(0,L.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function pe(e,t,i){const r=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,W.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,T.equalsIgnoreCase)(n,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,S.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,v.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,k.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,O.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if((0,S.isTest)()){const e=(0,p.toInt)((0,F.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeoutError)({p:H.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=q.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeoutError)({p:H.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,Z.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>H.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},89372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=void 0;const r=i(45599),s=i(98553),n=i(31586),a=i(50213),o=i(51140),l=i(4988),u=(0,r.defer)((()=>(0,a.mkLogger)("web.HttpGet")));t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,n.gt0)(await t.size())&&(0,n.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await(0,l.get_)(e.url,{headers:e.headers});o.HttpStatusIs.success(r.statusCode)||u().throw("Failed",{url:e.url,response:r});const a=(0,s.parseJSON_)(r.data),c=e.preCacheTransform?.(a)??a;return u().info("Fetch success. Caching",{args:e,json:c,cache:t}),await t.writeJson_(c),{data:c,updatedAt:Date.now(),fromCache:!1}}},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),h=i(34238),f=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const a=n(i(37067)),o=n(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),h=i(50213),f=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),v=(0,u.defer)((()=>(0,h.mkLogger)("net.get")));async function w(e,t){return b({...t,url:e})}async function b(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?a.request:"https"===t.scheme?o.request:v().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??f.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",h=e?.agent??!1,b=r(t.toString(),{method:c,headers:u,timeout:n,agent:h},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const a={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&y.HttpStatusIs.redirect(a.statusCode)&&!(0,l.blank)(e.headers.location)?(v().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(w(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(v().debug("complete",{...a,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(a))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||b.write(e.body),b.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=w,t.httpRequest_=b},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},14854:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(48161)),h=i(42659),f=i(45599),m=i(55835),p=i(31586),g=i(68708),y=i(19851),v=i(50213),w=i(7282),b=i(78406),S=i(25764),P=i(38835),_=i(74128),M=i(82647),T=i(43334),E=i(28874),k=i(30933),D=i(15674),x=(0,y.lazy)((()=>(0,v.mkLogger)("work.CpuUsage"))),C=(0,y.lazy)((()=>{const e=F.instance().busyPct();(0,_.syncReport)().maybeSystemData({from:"cpuUsage",state:"note",details:"Current system load is too high to schedule more work",meta:(0,g.compactValues)({loadCpuPct:I(),cpuBusyPct:e})}),x().warn("Current system load is too high to schedule more work",{cpuBusyPct:e,max:E.Settings.cpuBusyPercent.valueOrDefault})}),((0,w.isTest)()?15:60)*h.secondMs);t.isTooBusy=function(){if(E.Settings.cpuBusyPercent.valueOrDefault<=0)return!1;const e=F.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(4*E.Settings.cpuBusyPercent.valueOrDefault/3));return(0,p.gte)(e,t)?(C(),!0):(C.unset(),!1)};class F extends b.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,D.singleThreadedMode)()?60:T.isWin?20:10)*h.secondMs,rank:S.EndableRanks.first}),r.add(this),s.set(this,new M.Average(5)),n.set(this,new A),(0,p.mapFinite)(I(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??I()}}t.CpuUsage=F,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,I());const e=new A;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},F.instance=(0,f.defer)((()=>new F));class A{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?(0,p.sigFigs)(t/r*100,3):void x().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+P.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function I(){return T.isWin?void 0:(0,p.sigFigs)(d.default.loadavg()[0]/(0,k.cpuInfo)().length*100,3)}},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),s=i(37692);let n=!1;function a(){return n}function o(e=!0){l(e),(0,s.writeStateFile)({paused:e})}function l(e){e!==n&&(n=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=a,t.pause=o,t.resume=function(){return o(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return a()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),s.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=b,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(b()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(b()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=w();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,v());return t=(0,a.clamp)(1,s,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const s=r(i(78474)),n=i(40958),a=i(76790),o=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),h=i(87290),f=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),v=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let w;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new s.default;let b=0;function S(){const e=(0,h.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-b>o.minuteMs;i&&(b=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(w?.nativePath)||(w?.close(),w=void 0),r&&null!=e&&(w??(w=new f.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=S()?.readJsonSync();for(const i of e?.events??[])_.get(i.e)!==i.ts&&(v().info("emitting event "+i.e),t.stateEvents.emit(i.e),_.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const _=new Map;function M(e){const i=S();if(null==i)v().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),s=function(e){const t=Date.now()-10*o.minuteMs;return(0,n.uniqByLast)((0,a.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:s};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=M,t.addStateEvent=function(e){const t=Date.now();_.set(e,t),M({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),s=i(87997),n=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},75761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),s=i(31586),n=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),s=i(22573),n=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),s=i(73872);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s.hasPrior=()=>r,s}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),s=i(21605),n=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),s=i(68708),n=i(34666),a=i(32639);function o(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,n.isPrimitive)(e)||(0,n.isPrimitive)(t))return e===t;if(!(0,s.isObject)(e)||!(0,s.isObject)(t))return!1;for(const i of(0,s.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),s=i(42659),n=i(55835),a=i(31586),o=i(12168),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),s=i(50357),n=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class s extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=s},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,(t=>!e(i,t,s)));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),s=i(22573),n=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,s){return!(null==s||!o(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,s.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return o(e)&&e>0}function b(e){return o(e)&&e>=0}function S(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function M(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=S,t.map2Numeric=function(e,t,i){return S(e,(e=>S(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,n.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return S(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=M,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return M(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),s=i(30976),n=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),s=i(54993),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),s=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),s=i(68708),n=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let s=!0;const n=setTimeout((()=>{s&&(s=!1,i(a.Timeout))}),t);try{n.unref?.();const t=await e;s&&(s=!1,i(t))}catch(e){s&&(s=!1,r(e))}finally{clearTimeout(n)}}))}async function c(e,t,i=!0){const s=await u(e,t,i);if(s===a.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return s}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?a.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return c(e,s,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,n.tot)(i);const s=await u(e,t,r);return s===a.Timeout?(0,n.tot)(i):s}},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),s=i(30301),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(30301),s=i(54993);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},58939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(55835),s=i(31586);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),s=i(30301),n=i(31586),a=i(97238),o=i(29652);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return n(e)??[]},t.optToA=n},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),s=i(23541),n=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},98401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cancelFileAndProcCleanups=t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=t.maybeCleanup_=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(56519),o=i(76187),l=i(87290),u=i(79267),c=i(32144),d=i(13829),h=i(69734),f=i(95696),m=i(65238),p=i(70257),g=i(13940),y=i(12495),v=i(95402),w=i(28874),b=i(40958),S=i(42659),P=i(31586),_=i(64526),M=i(22526),T=i(69032),E=(0,r.lazy)((()=>(0,s.mkLogger)("library.Cleanup")));async function k(){const e=_.Library.instance();if(null==e)E().info("No library to vacuum.");else{E().info("Running tag and search maintenance...");try{await(0,T.runTagMaintenance)()}catch(e){E().warn("Failed to run tag maintenance",{error:e})}E().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,n.isDbJanitorService)()&&(E().info("Running database maintenance..."),await e.runDbBackup_())}E().info("Cleaning child processes..."),await(v.Pids.instance()?.killOldProcs()),E().info("Cleaning stale and temp files..."),await D(),await(0,a.mapAsync)({name:"fileCleanup",arr:j(),f:e=>e.cleanup()})}t.maybeCleanup_=(0,r.lazy)(k,5*S.minuteMs),t.cleanup_=k;const D=(0,r.lazy)((()=>(0,l.libraryDataDirPosixFile)()?.join("shared-state").rmrf())),x=(0,r.lazy)((()=>u.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:g.imageCacheDir_,staleMs:w.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ImageCacheName)}))),C=(0,r.lazy)((()=>u.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>f.PosixFile.for((0,m.readdirCacheDir)()),staleMs:w.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(m.ReadDirCacheName)}))),F=(0,r.lazy)((()=>u.FileCleanup.for({name:"previewWipCleanup",rootNativePath:l.libraryPreviewsDirPosixFile,staleMs:S.hourMs,isPrunable:e=>(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)}))),A=(0,r.lazy)((()=>u.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:d.defaultFsAdvisoryLockDir,staleMs:S.hourMs,isPrunable:h.isPsLockFileOrDir}))),I=(0,r.lazy)((()=>u.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,P.gt0)(w.Settings.syncReportRetentionCount.valueOrDefault)?(0,l.librarySyncReportsDir)():void 0,staleMs:S.hourMs,isPrunable:e=>(0,p.isWip)(e)||(0,c.isCsvExt)(e)})));function O(e){return(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)||(0,o.isSqliteFile)(e)}const L=(0,r.lazy)((()=>u.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,M.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:S.hourMs,isPrunable:O}))),R=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,M.libraryDbObjects_)().libraryDbBackupDir,staleMs:S.hourMs,minRetained:w.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:O})));async function N(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const B=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:N,staleMs:S.hourMs,minRetained:1,isPrunable:O})));function j(){return(0,b.compact)([x(),C(),F(),A(),(0,y.LogDirCleanup)(),I(),L(),R(),B()])}t.fileCleanups=j,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{v.Pids.instance()?.scheduleInterval();for(const e of j())e.scheduleInterval()})),t.cancelFileAndProcCleanups=function(){t.scheduleFileAndProcCleanups.unset(),v.Pids.instance()?.cancelInterval();for(const e of j())e.cancelInterval()}},64526:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(27395),u=i(25764),c=i(38836),d=i(99331),h=i(45608),f=i(15056),m=i(87290),p=i(38835),g=i(57159),y=i(61704),v=i(95696),w=i(18454),b=i(13940),S=i(48604),P=i(19851),_=i(23560),M=i(28874),T=i(2858),E=i(7014),k=i(63870),D=i(15674),x=i(22573),C=i(38639),F=i(42659),A=i(56409),I=i(68708),O=i(25470),L=i(22526),R=i(41844);class N extends c.EndableWrapper{static instance(){const e=M.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,_.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired_(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new A.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted_(),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted_();const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=M.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;M.Settings.maxConcurrentImports.hasValue()||(M.Settings.maxConcurrentImports.tmpValue=e,(0,D.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted_(),(0,_.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted_(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.previews=(0,P.lazy)((()=>(0,I.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new R.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,_.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.onEnd=(0,P.lazy)((async()=>{if(!(0,d.ending)())for(const{ea:e,t}of[{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,k.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise.then((()=>this))}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup_(){return(await this.dbModelJanitor())?.backup_()}}t.Library=N,r=N,n=new WeakMap,s={value:void 0}},19113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(62105),s=i(181),n=i(94448),a=i(39604);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},56992:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calcVolumesTTL=t.setVolumesTTL=void 0;const r=i(19851),s=i(50213),n=i(76596),a=i(87290),o=i(28874),l=i(2858),u=i(63870),c=i(7014),d=i(42659),h=i(31586),f=i(12168),m=(0,r.lazy)((()=>(0,s.mkLogger)("SetVolumesTTL")));async function p(){if(!(0,l.libraryHasSettings)())return;const e=[],t=await(0,c.volumes)(),i=o.Settings.minDiskFreeGb.defaultValue*f.GB;for(const r of[(0,a.libraryOriginalsDirPosixFile)(),(0,a.libraryPreviewsDirPosixFile)()]){const s=await(0,c.bestVolumeForPath)(r,t);if(null==s)return void m().warn("Can't find volume for "+r+", using default TTL for volumes()");if(s.available(0,l.mkLogger)("library.SuggestedLibraryDir")));class O{static async for(e,t){if((0,x.blank)(e))return;const i=await(0,E.bestVolumeForPath)(e,t);if(null==i)return void I().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:e});const r=await(0,p.isLibraryDir)(e);return new O(e,r,i)}constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=T.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=T.Settings.minDiskFreeGb.valueOrDefault*A.GB){if(this.isLibrary)return;const t=await(0,_.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,S.containsHiddenPathname)(this.nativePath))return I().tap({...i,result:"contains hidden path"});{const e=await(0,b.whyExcludedDirectoryRecursive)(w.BaseFile.for(this.nativePath));if(null!=e)return I().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,v.canRWXFirstExistingAncestor)(this.nativePath)?(0,C.gt0)(e)&&this.availableBytesnew O(e,!1,{mountpoint:"/test",available:A.GB})))});const l=[],d=[],h=await(0,F.thenOrTimeoutMaybe)(i,T.Settings.statTimeoutMs.valueOrDefault)??await(0,F.thenOrTimeoutMaybe)((0,E.volumes)(),T.Settings.statTimeoutMs.valueOrDefault);if(null==h||(0,k.isEmpty)(h))return I().warn("volumes() is empty: they don't get any suggestions."),[];async function v(t){const i=await O.for(t,h);if(null!=i)return i.isLibrary||i.isCurrentLibrary?(I().info("addSuggestion(): path is a library",i),void l.push(i)):void(null==await i.whyExcluded(e)&&d.push(i))}if(await v(T.Settings.libraryDir.value),(0,M.isDocker)())return[...l,...d];await v(await(0,g.picturesDir)());const w=[n.default.cwd(),...await(0,P.childDirectories_)(n.default.cwd())];(0,M.isDocker)()||w.push(...await(0,P.childDirectories_)((0,m.homeDir)())),(0,k.filterInPlace)(w,(e=>(0,S.isNotHiddenPosixPath)(e)));for(const e of w)await(0,p.isLibraryDir)(e)&&(I().info("current working dir is a library",e),await v(e));function b(){return Date.now()-r>c.ShortCommandTimeoutMs-500&&(I().debug("...ran out of time, stopping."),!0)}(0,M.isDocker)()||await v(s.default.join((0,m.homeDir)(),(0,a.AppName)())),await(0,f.mapAsync)({name:"suggestedLibraryDirs.addVolume",arr:h,f:e=>async function(e){try{if(await(0,p.isLibraryDir)(e.mountpoint))return I().info("addVolume(): vol.mountpoint is a library",e.mountpoint),void await v(e.mountpoint);for(const t of await(0,P.childDirectories_)(e.mountpoint)){if(b())break;if(await(0,p.isLibraryDir)(t))I().info("addVolume(): dir is a library",t),await v(e.mountpoint);else for(const i of await(0,P.childDirectories_)(t)){if(b())break;await(0,p.isLibraryDir)(i)&&(I().info("addVolume(): dir is a library",t),await v(e.mountpoint))}}const t=s.default.join(e.mountpoint,(0,a.AppName)());I().info("addVolume(): adding default suggestion",t),await v(t)}catch(t){I().warn("addVolume(): Failed to add suggestion",{err:t,vol:e})}}(e),timeoutMs:c.ShortCommandTimeoutMs}),I().debug("Finished gathering suggestions. Filtering...",{priorLibraries:l,suggestions:d});const _=l;for(const e of(0,D.sortBy)(d,(e=>[-e.availableBytes,-e.nativePath.length]))){if(_.length>=t)break;_.some((t=>t.nativePath===e.nativePath||t.mountpoint===e.mountpoint))||(I().debug("adding new path",e),_.push(e))}return(0,k.uniqBy)((0,D.sortBy)(_,(e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath])),(e=>e.nativePath))}t.SuggestedLibraryDir=O,t.suggestedLibraryDirs=(0,h.lazyAsync)({desc:"library.suggestedLibraryDirs",later:()=>L()}),t._suggestedLibraryDirs=L},77948:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemInformation=t.libraryMetrics=void 0;const r=i(21330),s=i(46296),n=i(17344),a=i(18454),o=i(81674),l=i(66184),u=i(96175),c=i(24540),d=i(23560),h=i(28874),f=i(2858),m=i(84968),p=i(94174),g=i(37805),y=i(14854),v=i(15674),w=i(40958),b=i(22573),S=i(38639),P=i(75240),_=i(55835),M=i(31586),T=i(20214),E=i(51926),k=i(12168),D=i(43487),x=i(54017),C=i(48723);async function F(){if(null==D.Asset.db())return;const e=[];e.push((0,k.plurMetric)(D.Asset.shownCount(),"asset"));const t=x.AssetFile.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,E.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,k.plurMetric)(i.assetFileCount,t+" file"))}return e.push((0,k.plurMetric)(C.Tag.rows(),"tag")),e}t.libraryMetrics=F;const A={pending:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"};t.systemInformation=async function(){const e=await(0,o.b)(),t=e?.l?.tier??"lite",i=a.HealthCheck.summary();return(0,w.compact)([{term:"Version",defn:g.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:A[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,S.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,_.mapOr)(e?.l?.exp,(e=>(0,r.toIsoDate)(e)),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,u.osFullName)()},{term:"CPUs",defn:(0,u.CPUs)()},{term:"System load",defn:(0,_.map)(y.CpuUsage.instance().busyPct(),(e=>(0,M.fmtPct)(e)+" busy"))??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(h.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,v.maxConcurrentImports)()} concurrent imports, ${(0,v.sharpThreadsPerProcess)()} gfx/process)`},(0,d.isWebService)()?{term:"Web uptime",defn:(0,P.fmtDuration)((0,m.runtimeMs)())}:void 0,(0,b.mapNotBlank)((0,c.procDeviceModel)(),(e=>({term:"Device",defn:e}))),{term:"Current user",defn:await(0,p.username)()+((0,M.gte0)((0,p.userid)())?"":" (userid: "+(0,p.userid)()+", groupid: "+(0,p.groupid)()+")")},(0,f.libraryHasSettings)()?{term:"Library path",defn:h.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,await(0,T.thenMap)(F(),(e=>({term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:e}))),{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,l.defaultLogLevel)()}]).filter((({term:e,defn:t})=>(0,b.notBlank)(e)&&(0,b.notBlank)(t)))}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},46628:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(47783),c=i(97573),d=i(42231),h=i(40958),f=i(22573),m=i(68708),p=i(75020),g=i(54993),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function v(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(v));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w},88224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(28874),o=i(42231),l=i(40958),u=i(20214),c=i(43487),d=i(46628),h=i(63175),f=i(4407),m=i(58886),p=i(32646),g=i(48144),y=i(60047),v=i(6186),w=i(42003),b=i(43723),S=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function P({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];if(t=(0,l.uniqBy)([e,...t],(e=>e.nativePath)),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,y.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),a.Settings.tagGeo.valueOrDefault)for(const e of t){const t=await(0,p.geoTagFile)(e);if(null!=t){u.push(t);break}}await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,b.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,g.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,w.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{S().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const P=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(v.normalizeTagRoot),o.joinTagPath)),_=await(0,v.tagDeltas)(i,P);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:P,result:_}),_}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await P({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=P},63175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(47783),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},4407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(47783),h=i(40958),f=i(55835),m=i(31586),p=i(75020),g=i(54993),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function _(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function M(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),_);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),M);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=_,t.dayTagRef=M,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(r.date)}},58886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(19851),s=i(50213),n=i(42231),a=i(21404),o=i(40958),l=i(89937),u=i(75020),c=i(54017),d=i(94448),h=i(69032),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},32646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTagFile=t.geoTag=void 0;const r=i(48884),s=i(56519),n=i(50213),a=i(28874),o=i(47783),l=i(14245),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)((()=>(0,n.mkLogger)("curators.GeoTagger")));function p(e){const t=a.Settings.tagGeoMaxDistanceKm.valueOrDefault;if(t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t))return void m().warn("geoTag(): GeolocationDistance too large, skipping geo tag",(0,f.pickDeep)(e,...l.GeolocationFields));const i=a.Settings.tagGeoSynonyms.synonymMap(),s=a.Settings.tagGeoTemplate.valueOrDefault.map((t=>(0,r.first)(i.get(t)??[t],(t=>(0,f.pluckDeep)(e,t)?.value)))),n=(0,c.compactBlanks)(s);return m().tap({msg:"geoTag",result:0===n.length?void 0:(0,c.compact)([u.TagRoots.Where,...n]),meta:{picked:s}})}t.geoTag=p,t.geoTagFile=function(e){return(0,s.thenMap)((0,o.readTags)(e),p)}},48144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(47783),h=i(97573),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),v=i(96249),w=i(55835),b=i(75020),S=i(54993),P=i(6186),_=i(43723),M=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),T=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return M().tap({msg:"extractDashDashTags()",result:(0,w.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,w.mapOr)(T(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function k(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>T.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=k;const D=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(D,(e=>(i.push(e),"")));s.push(...(0,w.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function F(e,t){const[i,s]=(0,r.partition)(x(e),_.isWhoTag),n=(0,v.flatten)(i.map(_.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return M().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=C,t.processKeywords=F,t.keywordTagFiles=async function(e,t){return F([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(k)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},60047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(56519),s=i(28874),n=i(47783),a=i(75020),o=i(40958),l=i(22573),u=i(55835);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},6186:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhereRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(50213),s=i(28874),n=i(42231),a=i(75020),o=i(40958),l=i(22573),u=i(45599);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.WhereRoot={name:a.TagRoots.Where,ordinal:5},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,t.WhereRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Where,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase()))),g=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhereRoot,...e.slice(1)]:g.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},42003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}t.friendlySubtype=y,t.fixCase=v},43723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(19851),s=i(50213),n=i(28874),a=i(47783),o=i(28630),l=i(66039),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(w)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function v(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function w(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=v,t.nameTag=w},98348:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(48884),d=i(19851),h=i(23560),f=i(25764),m=i(38836),p=i(99331),g=i(5916),y=i(12959),v=i(55332),w=i(91872),b=i(80632),S=i(51040),P=i(44955),_=i(15056),M=i(70025),T=i(57159),E=i(18454),k=i(28874),D=i(5233),x=i(42659),C=i(31586),F=i(68708),A=i(30976),I=i(17036),O=i(27134),L=i(35052);class R extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=x.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),k.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*x.secondMs),this.migrate_=(0,g.lazyAsync)({desc:"db.migrate",later:async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{await(0,O.verifyDb_)((()=>this.db))}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||k.Settings.dbForceRecover.valueOrDefault)&&(E.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new I.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e}}}),this.tableInfo_=(0,d.lazy)((()=>(0,L.localTableInfo)(this.db)))}toJSON(){return(0,F.pick)(this,"schema","dbFile")}get isOpen(){return!0===l(this,n,"f")?.open}get inTransaction(){return this.isOpen&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(t||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,b.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new T.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===k.Settings.dbAutoVacuumMode.valueOrDefault&&(0,C.gt0)(k.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%k.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&(this.logger.info("running incremental_vacuum..."),l(this,n,"f")?.pragma("incremental_vacuum")),l(this,n,"f")}async verify_(){await(0,O.verifyDb_)((()=>this.db))}assertHeartbeat_(){const e=(0,A.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{this.logger.info("closing db",l(this,n,"f")),await(0,D.retryOnReject_)((()=>{!0===l(this,n,"f")?.open&&l(this,n,"f")?.close()}),{timeoutMs:k.Settings.dbBusyTimeoutMs.valueOrDefault,maxRetries:5,errorIsRetriable:M.isSqliteBusyError,retryDelay:x.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,w.handleDbRetries_)("db.checkpoint",(()=>this.db),(()=>(0,O.checkpoint_)({db:this.db})),this.onRetry),await(0,w.handleDbRetries_)("db.optimize",(()=>this.db),(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,w.handleDbRetries_)("db.vacuum",(()=>this.db),(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,O.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,_.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,P.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,y.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,v.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=R,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,C.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},25470:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(66364),d=i(50213),h=i(23560),f=i(78406),m=i(25764),p=i(38836),g=i(99331),y=i(56038),v=i(12959),w=i(55332),b=i(76187),S=i(73209),P=i(28874),_=i(42659),M=i(75240),T=i(95700),E=i(22526),k=i(45648),D=5*_.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends f.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:_.minuteMs,rank:m.EndableRanks.db,endTimeoutMs:5*_.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new p.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),m.EndableRanks.postdb,D),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*_.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,k.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,k.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,y.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,v.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,w.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,M.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:D,endableRank:m.EndableRanks.postdb,noopIfContested:!1});(0,h.isDbManager)()&&await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,b.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),await this.db.closeDb()},o=function(){return this.ended||(0,g.ending)()||(0,c.isSuspended)()}},22526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(19851),s=i(50213),n=i(92407),a=i(55332),o=i(44955),l=i(15056),u=i(87290),c=i(98314),d=i(38835),h=i(73209),f=i(95696),m=i(17217),p=i(18454),g=i(57902),y=i(28874),v=i(2858),w=i(40958),b=i(22573),S=i(42659),P=i(94448),_=i(98348),M=i(45648),T=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function k(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function D(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=D(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,M.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=k,t.libraryDbInfoJsonFile=D,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:k(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new _.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new _.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,M.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,M.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},86859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(54557),s=i(50213),n=i(99331),a=i(56038),o=i(65753),l=i(66184),u=i(70417),c=i(28874),d=i(40958),h=i(22573),f=i(45599),m=i(96249),p=i(31586),g=i(51926),y=i(57038),v=i(21074),w=(0,f.defer)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,y.knex)()(this.tableName)}prep(e,t=!1){const i=(0,v.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return w().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&w().log((0,l.defaultLogLevel)(),i+"(): "+(0,v.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;w().throw(t,{method:i,...(0,v.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,a.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,g.replaceAll)((0,g.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,v.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,m.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}async batched(e){let t,i=0;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,o.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&(await e.onResults(t),i+=t.length)}while((0,d.isNotEmpty)(t)&&!(0,n.ending)()&&(null==e.maxResults||e.maxResults>i));return{resultCount:i,done:null==t||t.length<(0,o.maxBatchPluckSize)()}}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}async pluckBatched(e){let t=0;const i=(0,u.min)([e.limit??(0,o.maxBatchPluckSize)(),e.maxResults]);if(i<=0||(0,p.lte0)(e.maxResults))return{done:!1,resultCount:t};let r;for(;null==e.maxResults||e.maxResults<=0||t(0,o.mkLogger)("db.DbSchemaValid")));function y(e){return l.PosixFile.for(s.default.join(u.ProjectPath.Data(),e+"-schema.json"))}t.schemaJsonFile=y,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,p.localTableInfo)(e.db),i=t.map((e=>e.tableName)),r=(await y(e.schema).readJson_()).tableInfo;{const e=r.map((e=>e.tableName)),t=(0,c.diff)(e,i);(0,c.isNotEmpty)(t)&&g().throw("Db is missing "+(0,f.plur)(t.length,"table")+": "+(0,h.andList)(t))}for(const e of t){const t=r.find((t=>t.tableName===e.tableName));if(null==t)g().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,c.isNotEmpty)(i)&&g().throw("Db is missing "+(0,f.plur)(i.length,"column")+" from table "+e.tableName+": "+(0,h.andList)(i.map((e=>e.name))))}}g().info("Validated schema.",{from:(0,d.shortStack)()})}catch(e){throw(0,m.dbModelHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return y(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",tableInfo:(0,p.localTableInfo)(t)},{spaces:2})}},45648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},36908:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(42231),o=i(40958),l=i(76790),u=i(23838),c=i(31586),d=i(54993),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},57038:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(31832)),n=i(19851),a=i(56519),o=i(55835),l=i(68708);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},17036:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(77598),l=i(19851),u=i(50213),c=i(7282),d=i(37805),h=i(4867),f=i(51040),m=i(77740),p=i(38835),g=i(8769),y=i(57159),v=i(34102),w=i(73209),b=i(95696),S=i(43899),P=i(18454),_=i(28874),M=i(40958),T=i(42659),E=i(41400),k=i(98553),D=i(55835),x=i(34666),C=i(32639),F=i(45648),A=i(94715),I=i(27134);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,A.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,M.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,k.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:_.Settings.dbMaintenanceTimeoutMs.valueOrDefault},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=A.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(A.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.info("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),(0,c.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{if((0,m.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,D.map)(e,(e=>e(r))),await(0,h.thenOrTimeoutError)({p:this.applyMigration_(r,i),timeoutMs:5*_.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch((e=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile(),r=(0,f.splitBatchSql)(i);if((0,M.isEmpty)(r))this.logger.info("No-op migration: "+e);else{t&&this.db.pragma("foreign_keys = OFF");for(const t of r)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,I.foreignKeyCheck_)(this.db)}}finally{t&&this.db.pragma("foreign_keys = ON")}}},94715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(97352),o=i(68852),l=i(81168),u=i(85810),c=i(42022),d=i(1971),h=i(79842),f=i(89724),m=i(17415),p=i(88600),g=i(20014),y=i(42231),v=i(87001),w=i(40958),b=i(55835),S=i(31586),P=i(97790),_=i(89937),M=i(54993),T=i(7656),E=i(36908),k=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),D=new RegExp(`^(${(0,o.escapeRegExp)(_.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())k().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)}function A(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>D.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=F,t.isoToPrecisionMs=A,t.Migrations={fix_root_tags:F,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},A),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,M.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();k().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));k().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:T.rebuildTagAssetCounts,create_tag_fts:e=>{e.exec("DROP TABLE IF EXISTS tag_fts"),e.exec("CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize=\"unicode61\");")},rebuild_null_island:e=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,y.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")}}},27134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(14121),s=i(19851),n=i(50213),a=i(84777),o=i(12959),l=i(5531),u=i(91872),c=i(99315),d=i(76187),h=i(51040),f=i(38835),m=i(57159),p=i(29882),g=i(95696),y=i(89966),v=i(38156),w=i(28874),b=i(63870),S=i(5233),P=i(42659),_=i(41400),M=i(50357),T=i(98553),E=i(56409),k=i(31586),D=i(20214),x=i(51926),C=i(12168),F=i(59455),A=i(54993),I=i(94448),O=i(9508),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){L().debug("pragmaOrThrow_()",{db:N(e),db_open:e?.open,pragma:t,okResult:i});const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,M.eql)(r,i)||L().throw(`${t} failed for ${N(e)}: ${(0,T.stringify)({result:r})}`)}function N(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}function B(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function j(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function z(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function V(e){await(0,u.handleDbRetries_)("db.quickCheck",e,B),await(0,_.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",e,j),await(0,_.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",e,z)}function W(e){return(0,O.withDbSync)(e,V,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,k.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,I.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=B,t.integrityCheck_=j,t.foreignKeyCheck_=z,t.verifyDb_=V,t.verifyDbFile_=W,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,F.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,k.gt0)(n?.busy)&&i>0?(await(0,_.delay)(250),e({db:t,retries:i-1})):n};const U=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,A.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,A.toS)(e);U.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),await W(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,D.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,D.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},21074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(48884),s=i(68852),n=i(81168),a=i(12943),o=i(96249),l=i(98553),u=i(31586),c=i(68708),d=i(32639),h=i(54993);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},35052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(22573),s=i(23838);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},9508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(80632),s=i(28874),n=i(30301),a=i(54993);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)((()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i})));try{return t((function(){const e=o();return e.open?e:o.refresh()}))}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const n=(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i});try{return await t(n)}finally{n.close()}}},74085:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelHealthCheck=void 0;const r=i(77740),s=i(98314),n=i(18454),a=i(28874),o=i(82950),l=i(42659),u=i(45599),c=i(64526),d=i(16185),h=i(45648),f=i(31687),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.dbModelHealthCheck=(0,u.defer)((()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library database…",settings:["libraryDir","forceLocalDbReplica"],timeoutMs:()=>10*a.Settings.dbMaintenanceTimeoutMs.valueOrDefault,ttlMs:l.minuteMs,onReset:()=>(0,h.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837"}],later:async()=>{const e=await(c.Library.instance()?.ready);if(null==e)return{level:"disabled",msg:["Library database tests disabled: no library is open"]};let t,i=!1;try{const s=Date.now();if(i=!1,(0,h.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,o.li)((0,h.dbSetupErrors)())],links:[m]};if(t=await e.modelDb(),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await(0,d.assertValidDbSchema_)(t),i=!0,await t.verify_(),await t.vacuum(),f.Heartbeat.assertPing_();const n=await e.dbModelSetup_();return{level:"ok",msg:["Library database is OK",(0,o.li)(["Schema validation, vacuum, optimize, and upsert round-trip took "+(Date.now()-s)+"ms","Live db is "+(0,o.tt)(t.dbFile.nativePath),"Local replica mode is "+(0,o.tt)(n.useReplica),n.useReplica?"Cold library db is "+(0,o.tt)(n.libraryDbFile):void 0])]}}catch(r){return{level:"error",msg:["Library database validation failed",(i?"":"Unrecoverable: ")+(0,s.errorToS)(r),null==t?void 0:"Live db is "+(0,o.tt)(t.dbFile.nativePath),null==e?void 0:"Local replica mode is "+(0,o.tt)(await e.useReplica())],links:i?[m]:void 0}}}});return(0,h.addDbSetupErrorListener)((()=>e.refresh())),e}))},8400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(19851),s=i(88625),n=i(2858),a=i(74085),o=i(1991),l=i(40549);t.libraryHealthCheckSetup=(0,r.lazy)((async()=>{await(0,n.readSettings)(),(0,s.healthCheckSetup)(),(0,o.syncHealthCheck)(),(0,a.dbModelHealthCheck)(),(0,l.volumeUuidHealthCheck)()}))},1991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncHealthCheck=void 0;const r=i(48884),s=i(50213),n=i(95696),a=i(62105),o=i(18454),l=i(2858),u=i(40958),c=i(82950),d=i(45599),h=i(94019),f=(0,d.defer)((()=>(0,s.mkLogger)("health.SyncHealthCheck")));t.syncHealthCheck=(0,d.defer)((()=>o.HealthCheck.for({section:"Library",id:"library-nothing-to-sync",ordinal:99,settings:["scanAllDrives","scanPaths","scanLibraryFirst","scanLibraryLast"],pendingMsg:"Checking synced directories…",later:async()=>{if(!(0,l.libraryHasSettings)())return{level:"disabled",msg:"Library sync paths test disabled: no library is open"};const e=(await(0,h.pathsToSync)()).map((e=>e.nativePath));if((0,u.isEmpty)(e))return{level:"warn",msg:"No paths are configured to scan\n"+(0,c.li)([(0,c.tt)("PS_SCAN_ALL_DRIVES")+" is false",(0,c.tt)("PS_SCAN_PATHS")+" is empty","both "+(0,c.tt)("PS_SCAN_LIBRARY_FIRST")+" and "+(0,c.tt)("PS_SCAN_LIBRARY_LAST")+" are false"]),links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]};{const t=e.map((e=>n.PosixFile.for(e)));return f().info("Checking if any paths are empty",{posixFiles:t}),null==await(0,r.findAsync)(t,(async e=>null!=await e.someDescendant((e=>e.isDirectorySync()||(0,a.acceptParentAndFileAndSimple)(e)),1)))?{level:"warn",msg:["No eligible files found in scanned paths","Checked paths:",(0,c.li)(e.map(c.tt))],links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]}:{level:"ok",msg:["At least one directory with eligible files is configured to be synced","Checked paths:",(0,c.li)(e.map(c.tt))]}}}})))},40549:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=void 0;const r=i(50213),s=i(56519),n=i(18454),a=i(28874),o=i(2858),l=i(85087),u=i(63870),c=i(86848),d=i(7014),h=i(40958),f=i(82950),m=i(45599),p=i(57924),g=i(23838),y=i(68708),v=i(94019),w=(0,m.defer)((()=>(0,r.mkLogger)("health.VolumeUUIDHealthCheck")));t.volumeUuidHealthCheck=(0,m.defer)((()=>n.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumes…",settings:["scanAllDrives"],links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],later:async()=>{if(!(0,o.libraryHasSettings)())return{level:"disabled",msg:"Volume UUID test disabled: no library is open"};const e=[],t=[];if(a.Settings.scanAllDrives.valueOrDefault)e.push(...await(0,d.volumes)());else{const i=await(0,v.scanPaths)(),r=await(0,s.mapAsyncSerial)({name:"scannedVolumes",arr:i.result.map((e=>e.nativePath)),f:e=>(0,d.bestVolumeForPath)(e),timeoutMs:(0,u.commandTimeoutMs)()});e.push(...(0,h.uniqBy)(r,(e=>e.mountpoint))),t.push(...i.noUriPaths)}const i=[...(0,g.groupBy)(e,(e=>e.uuid)).values()].filter((e=>e.length>1)),r=e.filter((e=>null==e.uuid&&!(0,c.volumeUuidNotExpected)(e))).map((e=>e.mountpoint)),n=(await(0,d.volumes)()).filter((e=>!1===e.ok)).map((e=>(0,h.compactBlanks)([e.mountpoint,e.status]).join(": ")));if(w().debug("volumeHealthCheck result",{missingUUIDs:r,noUriPaths:t,unhealthyVolumes:n,scannedVolumes:e.map((e=>(0,y.pick)(e,"uuid","mountpoint")))}),(0,h.isEmpty)(r)&&(0,h.isEmpty)(i)&&(0,h.isEmpty)(t)&&(0,h.isEmpty)(n))return(0,h.isEmpty)(e)?{msg:["No volumes need UUIDs",(0,f.tt)(a.Settings.scanAllDrives.key)+" is false, and no volumes other than the library are configured to be scanned."],level:"ok"}:{msg:["All scanned volume UUIDs are OK",(0,f.li)(e.map((e=>(0,f.tt)((0,l.volsha)(e.uuid)+" → "+e.mountpoint))))],level:"ok"};{const e=[];return(0,h.isEmpty)(n)||e.push("Some volumes are unhealthy",(0,f.li)(n.map((e=>(0,f.tt)(e))))+"PhotoStructure may crash or hang when accessing unhealthy volumes."),(0,h.isEmpty)(r)||e.push("Some volumes are missing UUIDs",(0,f.li)(r.map((e=>(0,f.tt)(e)))),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(i)||e.push("Some volumes have duplicate UUIDs",i.map((e=>(0,f.li)((0,p.andList)(e.map((e=>(0,f.tt)(e.mountpoint))))+" share UUID "+(0,f.tt)(e[0].uuid)))).join("\n---\n"),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(t)||e.push("Some paths failed to have URIs generated",(0,f.li)(t.map((e=>(0,f.tt)(e)))),"This will prevent these paths from being imported."),{level:"warn",msg:e.join("\n---\n"),links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}})))},86801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(93944).install()}catch{}const r=i(98314),s=i(98424);process.on("unhandledRejection",(e=>console.error("UNHANDLED REJECTION",(0,r.errorToS)(e)))),process.on("uncaughtException",(e=>console.error("UNCAUGHT EXCEPTION",(0,r.errorToS)(e)))),(0,s.run)()},64501:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InfoArgs=void 0,t.InfoArgs={beforeParse:e=>e.option("--volumes","Emit a table with currently mounted volume metadata. See https://photostructure.com/volumes for details.").option("--mountpoints","Emit a table with currently mountpoints. See https://photostructure.com/volumes for details.").option("--sync-paths","Emit a table listing the paths that will be synced next.").option("--plan, --licensing","Emit plan/licensing information. See the About page in the web UI for more details or to activate a subscription.").option("--child-env","Emit the environment variables provided to all spawned processes.").option("--validate","Only run file validation on the given filenames (requires current PLUS subscription).").option("-j, --json","Emit metadata as un-indented, uncolorized JSON.").option("--load-library","Load the library database so more metadata can be shown (like if a file is currently in your library). This adds a second or two (depending on the size of your library).").option("--filter ",'Case-insensitively filter keys by . may have dots. Note that .nativePath is always included. Repeat to filter for multiple terms ("--filter foo --filter bar").',((e,t)=>t.concat([e])),[]).option("--file-filters","Include an exhaustive list of file and directory filters. This is hundreds of lines long, so it's not included by default.").option("--image-hash",'Automatically filter image hash fields. Equivalent to "--filter imageHash --filter imageHashComparison"').option("--flat","Only return values for objects with only one field").option("--suggested-libraries","Emit the suggested library directories (as seen on the settings page).").option("--volumes-ttl","Emit the volume cache time-to-live (use with --debug to see details).").option("--is-library ","Run a couple quick checks to see if looks like a PhotoStructure library.").option("--read-settings ","Read the given file and output the parsed settings.").option("--reindex","Rebuild the tag full-text index and recount every asset tag count. This may take a minute or two. Don't have a sync running concurrently. Implies --cleanup.").option("--globs, --exclude-globs","Emit all file and directory exclusion globs.").option("--health","Emit details for all health checks.").option("--doctor","Emit details for all health checks that aren't OK.").option("--skip-health","Disable health checks.").option("--version-check","Check now if the current version is the latest.").option("--table","Emit with console.table() (useful with --volumes or --filter).").option("--cleanup","Run a bunch of maintenance tasks."),afterParse:function(){}}},98424:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.run=void 0;const s=r(i(57975)),n=i(19851),a=i(50213),o=i(88158),l=i(23560),u=i(19913),c=i(83556),d=i(94174),h=i(79184),f=i(79781),m=i(13991),p=i(92434),g=i(45608),y=i(56519),v=i(31562),w=i(9727),b=i(69554),S=i(38790),P=i(53978),_=i(43380),M=i(91655),T=i(15056),E=i(49776),k=i(48195),D=i(87290),x=i(46296),C=i(98314),F=i(8769),A=i(57159),I=i(83278),O=i(92423),L=i(95696),R=i(89966),N=i(63664),B=i(18454),j=i(80361),z=i(181),V=i(34592),W=i(81674),U=i(17181),H=i(43205),q=i(28874),G=i(2858),$=i(32707),J=i(63225),K=i(85087),Y=i(50036),Z=i(40044),X=i(59107),Q=i(63870),ee=i(7014),te=i(14854),ie=i(40958),re=i(22573),se=i(38639),ne=i(42659),ae=i(55835),oe=i(68708),le=i(34666),ue=i(5670),ce=i(12168),de=i(59455),he=i(98401),fe=i(64526),me=i(56992),pe=i(57064),ge=i(77948),ye=i(31503),ve=i(8400),we=i(92244),be=i(64501),Se=i(46854);t.run=async function(){try{await async function(){const e=await new b.CLI(ue.ServiceNames.info,"[FILE...]",["* Omit any filenames to run diagnostics and output system configuration, tooling, and health check information.","* File paths should be absolute or relative to cwd.","* Provide 2 file paths to see why PhotoStructure may consider them variants of the same asset.","* To emit valid JSON, set NO_COLOR=1 or use --json."].join("\n")).add(be.InfoArgs,_.WriteSettingsArg,ye.LogArgs,S.ColorArgs,P.TimingArg).parse();(0,u.setServiceName)("info"),(0,U.setupLogger)();const t=e.opts(),i=(0,ie.uniq)(e.args),r=(0,se.isTrue)(t.flat),g=(0,se.isTrue)(t.table),F=!0===t.reindex;F&&(q.Settings.recountAllTags.envValue=!0);const A=F||(0,se.isTrue)(t.cleanup);(0,se.isTrue)(t.imageHash)&&(t.filter??(t.filter=[]),t.filter.push("imageHash"),t.filter.push("imageHashComparison"));const Pe=(0,se.isTrue)(t.fileFilters),_e=(0,n.lazy)((()=>{if((0,ie.isEmpty)(t.filter))return;const e=(0,de.toA)(t.filter);return r&&i.length<=1||e.unshift("nativePath"),2===i.length&&e.push(...e.map((e=>"a."+e)),...e.map((e=>"b."+e))),e}));function Me(e){e=function(e){const t=_e();return null==t?e:Array.isArray(e)?e.map((e=>(0,oe.pickDeep)(e,...t))):(0,oe.pickDeep)(e,...t)}(e),r&&(e=(0,oe.flattenObject)(e));const i=(0,se.isTrue)(t.json);r&&(0,le.isPrimitive)(e)?console.log(e):i||(0,se.isFalse)(q.Settings.logColor.value)?console.log(JSON.stringify(e,void 0,i?void 0:2)):g?console.table(e):console.log(s.default.inspect(e,{depth:7,colors:!0,maxArrayLength:1024}))}let Te;if((0,u.setServiceName)("info"),(0,se.isTrue)(t.skipHealth)?B.HealthCheck.disableAll(!0):Te=await(0,N.getRemoteHealthSummary)(),(0,re.notBlank)(t.readSettings)){const e=await(0,G.importFileSettings_)(I.BaseFile.for(t.readSettings));return Me({settings:(0,oe.fromEntries)(e.settings.map((e=>[e.name,e.value]))),warnings:e.warnings})}if(await(0,G.readSettings)(),A&&(l.isDbJanitorService.set(!0),q.Settings.logLevel.isUnset()&&(q.Settings.logStdout.envValue=!0,q.Settings.logLevel.envValue="warn",(0,U.setupLogger)())),(0,se.isTrue)(t.versionCheck))return await((0,Y.channelVersionsCache)()?.unlink()),q.Settings.autoUpdateCheck.tmpValueIfUnset=!0,Me(await(0,Z.checkVersion_)());if((0,se.isTrue)(t.globs)||(0,se.isTrue)(t.excludeGlobs)){const e=(0,O.excludeGlobs)();return Me({excludeGlobs:{file:e.file.map((e=>(0,oe.pick)(e,"pattern","desc"))),dir:e.dir.map((e=>(0,oe.pick)(e,"pattern","desc")))}})}if((0,se.isTrue)(t.volumes)){const e=await(0,ee.volumes)();if(null!=e)return Me(e.filter((e=>!0!==e.ignorable)).map((e=>({filesystem:e.filesystem,...e,size:(0,ce.fmtBytes)(e.size),used:(0,ce.fmtBytes)(e.used),available:(0,ce.fmtBytes)(e.available),volsha:(0,K.volsha)(e.uuid)}))));console.error("--volumes failed. Please retry with --info for details.")}if((0,se.isTrue)(t.mountpoints)){const e=await(0,X.mountpoints)();if(null!=e)return Me(e);console.error("--mountpoints failed. Please retry with --info for details.")}if((0,se.isTrue)(t.plan)||(0,se.isTrue)(t.licensing)){const e=(await(0,W.m)())[0],t=(0,ae.map)(e?.l,(t=>({email:t.sub,trial:t.trial,issued_at:t.iat,expires:t.exp,meta:e.meta})));return Me({plan:await(0,W.t)(),current_license:t})}if((0,se.isTrue)(t.suggestedLibraries))return Me(await(0,pe.suggestedLibraryDirs)());if((0,se.isTrue)(t.volumesTtl))return Me({volumesTTL:await(0,me.calcVolumesTTL)()??(0,Q.volumeMetadataTtlMs)()});if((0,se.isTrue)(t.childEnv))return Me((0,w.childEnv)());const Ee=(0,a.mkLogger)("info");if((0,se.isTrue)(t.loadLibrary)||(0,se.isTrue)(t.syncPaths)||A){const e=(0,D.libraryDataDirPosixFile)();if(null==e)return console.error("Error: please set up your library.");if(!await e.isDirectory())return console.error("Error: your library data dir, "+e+", is missing.");Ee.info("Waiting for library to spin up...");const t=fe.Library.instance();try{await(t?.ready)}catch(e){Ee.warn("Failed to spin up library",e)}const i=(0,T.pathToDb)(e,"models");if(!await i.isNonEmptyFile())return console.error("Error: your library database, "+i+" is missing.")}if(A)return await(0,he.cleanup_)(),Me({cleanup:"OK"});if((0,se.isTrue)(t.syncPaths))return Me(await(0,we.syncPathsForUI)());if((0,re.notBlank)(t.isLibrary)){const e=await(0,k.whyNotLibraryDir)(t.isLibrary);return Me((0,oe.compactValues)({isLibrary:null==e,why:e}))}if((0,se.isTrue)(t.validate)){if((0,ie.isEmpty)(i))throw new Error("--validate requires filenames");return q.Settings.validateVideos.envValue=!0,q.Settings.validateJpegImages.envValue=!0,q.Settings.validateRawImages.envValue=!0,Me(await Promise.all(i.map((async e=>[e,(0,re.notBlankOr)(await(0,z.whyInvalidFile)(e),"OK")]))))}if((0,ie.isEmpty)(i)){await(0,v.until)((()=>te.CpuUsage.instance().busyPct()),{timeoutMs:2*ne.secondMs,intervalMs:250});const e={systemInfo:(0,oe.fromEntries)((await(0,ge.systemInformation)()).map((({term:e,defn:t})=>[(0,c.asObjectKey)(e),t])))};return e.versionCheck={userAgent:await(0,H.userAgent)(),...await(0,Z.checkVersion_)().catch((e=>({error:(0,C.errorToS)(e)}))),currentChannel:(0,Z.currentChannel)()},e.user_ids=(0,d.userids)(),e.group_ids=(0,d.groupids)(),e.username=await(0,d.username)(),e.paths={libraryDir:q.Settings.libraryDir.valueOrDefault,originalsDir:(0,D.libraryOriginalsDirPosixFile)()?.nativePath,systemSettingsFile:(0,$.systemSettingsFile)(),librarySettingsFile:(0,G.librarySettingsFile)()?.nativePath,libraryPreviewsDir:(0,D.libraryPreviewsDirPosixFile)()?.nativePath,librarySyncReportsDir:(0,D.librarySyncReportsDir)()?.nativePath,cacheDir:(0,E.cacheDir)(),logDir:(0,x.logDir)(),toolsDir:(0,R.toolsDir)()?.nativePath,osToolsDir:(0,R.osToolsDir)()?.nativePath,ffmpeg:await(0,V.ffmpegNativePath)(),sqlite:await(0,R.sqliteNativePath_)().catch((e=>"not found: "+(0,C.errorToS)(e)))},(0,se.isTrue)(t.health)?(e.healthSummary=await(0,N.getLocalHealthSummary)(),e.healthChecks=await Promise.all(B.HealthCheck.testResults())):(0,se.isTrue)(t.doctor)?(await(0,ve.libraryHealthCheckSetup)(),e.healthChecks=await B.HealthCheck.notOkResults()):e.healthSummary=Te??await(0,N.getLocalHealthSummary)(),e.wrongPsEnvValues=(0,J.verifyPsEnvSettings)(),(0,se.isTrue)(t.loadLibrary)&&(e.libraryMetrics=(0,oe.fromEntries)((await(0,ge.libraryMetrics)())?.map((e=>[(0,c.asObjectKey)(e.desc),e.count]))??[]),e.libraryDb=(0,oe.omit)(await(fe.Library.instance()?.dbModelSetup_()),"db","fslock")),e.volumesTTL=(0,M.fmtFullDuration)(await(0,me.calcVolumesTTL)()),e.nonDefaultSettings=(0,oe.fromEntries)((0,oe.values)(q.Settings).filter((e=>e.hasValue())).map((e=>[e.name,e.humanValue]))),Me(e)}if(2===i.length){const e=L.PosixFile.for(i[0]),t=L.PosixFile.for(i[1]),r=await(0,m.mkAssetFile_)(e),s=await(0,m.mkAssetFile_)(t),n=[];if(null==r&&n.push("Failed to read "+e),null==s&&n.push("Failed to read "+t),(0,ie.isNotEmpty)(n))return Me({errors:n});const a=(0,f.whyNotSimilarAssetFile)(r,s),l=null==a?"These two files will be aggregated into a single asset.":"These files represent different assets: "+a;let u,c;if(null==a){const e=(0,p.sortAssetFiles)([r,s]);u=e[0]?.nativePath,c=(0,o.zipPojos)(...await Promise.all(e.map(p.assetFileSortCriteriaPojo)))}const d={fileComparison:l,primary:u,a:await(0,Se.info)(e,Pe),b:await(0,Se.info)(t,Pe),cmpArr:c};return q.Settings.useImageHashes.valueOrDefault&&(d.imageHashComparison=(0,oe.omit)((0,j.compareImageHashes)(r,s),"a","b")),Me(d)}{const e=await(0,y.mapAsync)({name:"info",arr:i,f:e=>(0,Se.info)(e,Pe)}),t=(0,oe.fromEntries)(e?.map(((e,t)=>[t,e])));if(e.length>1){const e=(0,ie.compact)(await(0,y.mapAsync)({name:"mkAssetFile",arr:i,f:e=>(0,m.mkAssetFile_)(L.PosixFile.for(e)).catch((t=>{console.error("Failed to read "+e,t)}))})),r=await(0,h.aggregateAssetFiles)(e);t.clusters=r.map((e=>e.map((e=>e.uri))))}return Me(t)}}()}catch(e){(0,F.onError)((0,A.toWrappedError)("Failed",{cause:e,fatal:!0}))}finally{await(0,g.exit)({reason:"done",status:0})}}},46854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.info=void 0;const r=i(50213),s=i(88158),n=i(13991),a=i(92434),o=i(85434),l=i(98314),u=i(92423),c=i(32144),d=i(95696),h=i(62105),f=i(17217),m=i(181),p=i(66106),g=i(78984),y=i(4936),v=i(47783),w=i(16170),b=i(54979),S=i(22573),P=i(42659),_=i(45599),M=i(68708),T=i(20214),E=i(64526),k=i(19113),D=i(88224),x=i(54017),C=i(94448),F=i(3996),A=(0,_.defer)((()=>(0,r.mkLogger)("info.InfoImpl")));t.info=async function(e,t){try{const i=d.PosixFile.for(e),r=await(0,b.readMimeType)(i);if(null==r)return{nativePath:i.nativePath,error:`Could not read mimetype for ${i.nativePath}`};if((0,c.isSidecarMimetype)(r))return{nativePath:i.nativePath,mimetype:r,error:"Skipping sidecar mimetype"};if(!await(0,w.isAssetFileMimeType)(i))return{nativePath:i.nativePath,mimetype:r,error:"Skipping non-asset file mimetype"};const l=i.parent();A().throwIfAborted_();const f=await(0,n.mkAssetFile_)(i),_=t?await g.Predicates.explain(l,...(0,u.notExcludedDirPredicates)(l)):void 0,I=t?await g.Predicates.explain(i,...(0,k.libraryFileFiltersFor)(i,{validateFile:!0})):void 0,O=f.dominantColors?.filter((e=>null!=e?.color?.name)).map((e=>({rgb:e.rgbhex,name:e.color?.name,pct:e.pct}))),L=await(0,D.tagAsset)({primaryVariation:i,files:[],priorTagPaths:[],capturedAts:[],uris:[await i.uri_()]}),R=null==(0,C.modelDb)()?void 0:await new F.AssetFileFinder(i).prior(),N=await(R?.matchesFile()),B=await(0,T.thenCollect)(x.AssetFile.sameShaInLibrary(i),(e=>e.getNativePath()));A().throwIfAborted_();const j=await(0,v.readTags)(i),z=j?.capturedAt,V=(0,h.whyRejectFile)(i,!0===E.Library.instance()?.isReadySync()?(0,k.libraryFileFiltersFor)(i):void 0),W=(0,M.compactValues)({...(0,o.omitModeData)(f),capturedAtRaw:z?.rawValue,...(0,M.pick)(j,"tz","tzSource","errors","inferred","duration"),dirFilters:_,dominantColors:O,fileFilters:I,needsTranscoding:await(0,p.needsTranscoding)(i),pathsInLibrary:B,pathToLibraryAsset:(0,y.pathToLibraryAsset)((0,P.localToDate)(f.capturedAtLocal),i),priorAssetFile:R?.toJSON(),priorIsInSync:N,sidecars:(await i.existingSidecars()).map((e=>e.base)),tagResult:L,validFile:(0,S.notBlankOr)(await(0,m.whyInvalidFile)(i.nativePath),"OK"),variantSortCriteria:(0,a.assetFileSortCriteriaPojo)(f),whyExcludedDirectoryRecursive:await(0,u.whyExcludedDirectoryRecursive)(l),whyRejected:V});return(0,M.compactValues)({nativePath:i.nativePath,mimetype:r,...(0,s.sortedKeys)(W)})}catch(t){return{nativePath:(0,f.toNativePath_)(e),error:(0,l.errorToS)(t)}}}},43487:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(48884),c=i(19851),d=i(50213),h=i(88158),f=i(45393),m=i(56519),p=i(89724),g=i(38835),y=i(74128),v=i(79847),w=i(28874),b=i(47783),S=i(38010),P=i(40958),_=i(76790),M=i(75761),T=i(38639),E=i(11371),k=i(98553),D=i(55835),x=i(31586),C=i(20214),F=i(59455),A=i(64526),I=i(4407),O=i(54017),L=i(48722),R=i(37094),N=i(45295),B=i(39604),j=i(48723),z=i(41507),V=i(72761),W={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class U extends V.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,b.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,T.isTrue)(t.shown)})}const t=R.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(W):e.andWhere(W)}static findUnhiddenById(e){return(0,x.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return A.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{unlinkAssetFiles:i});const l=n.getAssetFiles({refresh:!0});if(t){(0,B.upsertToShaBlockslist)(...l.map((e=>e.sha)));for(const e of l)(0,y.syncReport)().onProgress({from:"Asset.remove",path:await e.getNativePath()??e.uri,state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}N.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),R.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&j.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,v.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(N.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,x.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,x.gte)(this.rating,w.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,L.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:j.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,P.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return j.Tag.ops().all(j.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??N.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:j.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:j.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,P.uniq)((0,F.toA)(e.tagIdsToAdd).filter((e=>(0,x.gt0)(e)&&!t.includes(e)))),r=(0,P.uniq)((0,F.toA)(e.tagIdsToRemove).filter((e=>(0,x.gt0)(e)&&t.includes(e))));if((0,P.isEmpty)(i)&&(0,P.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&j.Tag.deltaAssetCountAndAncestors(t,-1),(0,P.isEmpty)(i)||N.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,P.isEmpty)(r)||N.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,P.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&j.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,z.coalesceStreams)((0,P.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,_.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,T.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,x.gt0)(this.id)&&(0,x.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,k.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,T.isTrue)(e.shown)))??this.getAssetFiles({refresh:!0})?.find((e=>(0,T.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,M.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,E.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,M.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,F.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,x.gte)(this.rating,w.Settings.likeRating.valueOrDefault),hidden:(0,T.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=U,s=U,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("Asset.version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},U.$tableName="Asset",U.$uniqueColumnName="id",U.$booleanFields=["shown","hidden"]},54017:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(76760),o=i(19851),l=i(88158),u=i(45393),c=i(68852),d=i(81168),h=i(13991),f=i(54296),m=i(56519),p=i(76490),g=i(89724),y=i(98314),v=i(38835),w=i(8769),b=i(29882),S=i(95696),P=i(62105),_=i(74128),M=i(35721),T=i(69589),E=i(28874),k=i(28544),D=i(16170),x=i(45200),C=i(34238),F=i(87001),A=i(42233),I=i(21404),O=i(40958),L=i(17586),R=i(22573),N=i(38639),B=i(42659),j=i(33374),z=i(50357),V=i(75240),W=i(11371),U=i(55835),H=i(31586),q=i(68708),G=i(34666),$=i(89937),J=i(75020),K=i(64526),Y=i(41844),Z=i(43487),X=i(48723),Q=i(94710),ee=i(72761);class te extends ee.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>C.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=Z.Asset.shownUnhidden(e.q).join("AssetFile","AssetFile.assetId","Asset.id").where("AssetFile.version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("AssetFile.updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("AssetFile.mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("AssetFile.uri",i+"%");return t})).orderBy("AssetFile.id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,A.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,A.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("AssetFile.id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,H.gt0)(e)?te.ops().first(Z.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Z.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,R.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(te.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=te.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=te.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:te.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,q.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith($.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,q.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,U.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,F.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,H.closeTo)(i.mtime,this.mtime,2*B.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return E.Settings.forceSync.valueOrDefault?E.Settings.forceSync.key+"=true":this.version!==u.AssetFileVersion?"AssetFileVersion: "+this.version+" != "+u.AssetFileVersion:this.whyNotMatchesFile(e)}async inSyncWithFile(e){const t=await this.whyNotInSyncWithFile(e);return this.logger().tap({msg:"inSyncWithFile()",result:null==t,meta:{whyNotInSync:t}})}async fileFields_(e){const t=e??await this.posixFile_();return null==t?void 0:await(0,h.assetFileStatFields_)(t)}isInLibrary(){return this.uri.startsWith($.PS_LIBRARY_PROTOCOL)}async isNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){const t=await this.whyNotNoop(e);return this.logger().tap({msg:"isNoop()",result:null==t,meta:{whyNotNoop:t}})}async whyNotNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){if(!0===e.forceSync)return"forceSync is true";if(!(0,H.gt0)(this.id))return"missing .id";if(!(0,H.gt0)(this.assetId))return"missing .assetId";{const e=await this.whyNotInSyncWithFile();if(null!=e)return e}if(await(0,Y.mayCopyAssetsToLibrary)()){const e=K.Library.instanceRequired_().assetFileRepository(),t=e.whyNotCopyFile(await this.posixFile_());if((0,R.blank)(t)&&null==await e.existingLibraryAssetFile(this))return"need to copy into library"}this.syncState=_.AssetFileSyncStates.noop}isVersionUpToDate(){return(0,G.gte)(this.version,u.AssetFileVersion)}async siblingCount(){return te.dbl.pluckFirstf((e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=(0,T.forceContextOrSetting)()){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,H.gt0)(this.id)&&!t.forceSync)return void(null==this.syncState&&(this.upsert(),this.syncState??(this.syncState=_.AssetFileSyncStates.noop)));const i=await this.isFileDeleted();if(!0===i)return this.syncState=_.AssetFileSyncStates.deleted,this.delete(),!0!==t.skipAssetRepair&&Q.Task.addOne("repairAsset",{assetId:this.assetId}),this;if(!1===i){const i=await this.updateFromFile_(e,t);return this.syncState??(this.syncState=null==i?_.AssetFileSyncStates.noop:_.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=_.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,q.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e,t=(0,T.forceContextOrSetting)()){const i=Date.now(),r=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&!0!==t.forceSync&&await this.matchesFile(e))return void r.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=_.AssetFileSyncStates.deleted,void r.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,R.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,q.assignAllFields)(this,(0,q.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=_.SyncFileStates.synced,r.elapsed("finished",Date.now()-i,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,q.assignFields)(this,(0,q.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...te.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,H.gt0)(this.assetId)?Z.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,x.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,R.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,F.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,R.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,R.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),k.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,M.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,j.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,N.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===W.ReducerNames.fit)).map((e=>(0,M.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=C.URI.parse(this.uri),t=(0,U.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=C.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,L.at)((0,L.at)(e,-1)?.tagPath,-1)}(0,z.eql)(e[0]?.tagPath,[J.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===$.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,L.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===J.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===$.PS_LOCAL_FILE_SCHEME){const t=C.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,q.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,N.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:ie(this.createdAt),updatedAtLocale:ie(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function ie(e){return(0,U.map)(e,(e=>(0,V.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=te,r=new WeakSet,s=function(){if((0,R.blank)(this.uri))return"blank uri";if((0,R.blank)(this.sha))return"blank sha";if(!(0,H.gt0)(this.width))return"missing width";if(!(0,H.gt0)(this.height))return"missing height";if(!(0,H.gt0)(this.capturedAtLocal))return"missing capturedAtLocal";if(!(0,H.gte0)(this.capturedAtPrecisionMs))return"missing capturedAtPrecisionMs";if(E.Settings.useImageHashes.valueOrDefault){const e=[];for(const t of["dctHash","diffHash","meanHash"])(0,R.blank)(this[t])&&e.push(t);if(1===e.length)return"missing image hash: "+e[0];if(e.length>1)return"missing image hashes: "+e.join(", ")}return this.isVersionUpToDate()?void 0:"outdated version"},te.$tableName="AssetFile",te.$uniqueColumnName="uri",te.$booleanFields=["shown"],te.$transientFields=["nativePath","syncState"]},48722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(76596),s=i(31586);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},37094:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},45295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},61204:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(19851),s=i(50213),n=i(97352),a=i(75020),o=i(4407),l=i(48723),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},31687:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(38835),s=i(42659),n=i(31586),a=i(72761);class o extends a.TimestampedModel{static ping(e){return o.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){if(null==o.db())throw new Error("no library is open"+r.NoLibraryErrorFlag);try{o.ping(e);const t=o.ops().findOneBy({name:e});if(null==t||t.name!==e||(0,n.lt)(t.updatedAt,Date.now()-20*s.secondMs))throw new Error("Heartbeat row wasn't inserted")}finally{try{o.dbl.runf((t=>t.delete().where({name:e})))}catch{}}}}t.Heartbeat=o,o.$tableName="Heartbeat",o.$uniqueColumnName="name",o.$useCache=!1},95700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(19851),s=i(56038),n=i(28874),a=i(42659),o=i(41400),l=i(69032),u=i(61204),c=i(49796);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h());try{await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())}catch{}};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},55046:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(57975),n=i(50213),a=i(7282),o=i(65211),l=i(40958),u=i(38639),c=i(45599),d=i(31586),h=i(68708),f=i(34666),m=i(54993),p=i(57038),g=i(94448),y=i(33572),v=i(63872);class w{constructor(){this.$instanceId=(0,a.isTest)()?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if((0,a.isProd)())throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}update(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("update()",{self:this.toJSON()}),this.class().ops().updateOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},94448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},33572:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(50213),s=i(40958),n=i(22573),a=i(38639),o=i(97790),l=i(51926),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},63872:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(48884),m=i(19851),p=i(50213),g=i(81168),y=i(48299),v=i(12943),w=i(38835),b=i(34102),S=i(28874),P=i(40958),_=i(76790),M=i(22573),T=i(50357),E=i(96249),k=i(98553),D=i(55835),x=i(31586),C=i(68708),F=i(59455),A=i(86859),I=i(33572);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,I.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new A.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,k.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,k.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,D.mapOr)(this.db(),(e=>e.isOpen),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,_.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,k.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,D.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,k.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,M.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,M.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);if(null==s)return;return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,k.stringify)(e))}reload(e){const t=[],i=this.allf((i=>{for(const r of e){const e=this.model.hasId(r)?this.model.pickId(r):this.$pickModelUcn(r);null!=e?(t.push([r,e]),i=i.orWhere(e)):h(this,s,"f").warn("reload(): given insufficient partial model",{fragment:r})}return i})),n=[];for(const[e,a]of t){const t=i.find((e=>(0,T.eqlSubset)(a,e)));if(null==t)h(this,s,"f").warn("reload(): failed to find result in db",{prior:e,dbArr:i});else{const i=h(this,r,"m",u).call(this,e);h(this,r,"m",l).call(this,i,t),i!==e&&h(this,r,"m",l).call(this,i,t),n.push(t)}}return n}upsert(e){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const t=this.columnNames(),i=[];for(const s of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=new Map,n=new Set,a=(0,P.compact)(s.map((e=>this.fromJSON(e))));for(const t of a){const i=(0,k.stringify)(this.$pickModelUcn(t));e.set(i,t),this.model.hasId(t)||n.add(i),t.$beforeUpsert()}h(this,r,"m",c).call(this,a.map((e=>e.$toDbJSON(t))));const o=this.reload(a),l=new Map(o.map((e=>[(0,k.stringify)(this.$pickModelUcn(e)),e])));for(const e of a){const t=(0,k.stringify)(this.$pickModelUcn(e)),r=l.get(t)??e;n.has(t)&&r.$afterInsert(),r.$afterUpsert(),i.push(r)}}return i}delete(e){const t=(0,F.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,k.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},20958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(19851),s=i(50213),n=i(88158),a=i(99331),o=i(70025),l=i(8769),u=i(22573),c=i(98553),d=i(50989),h=i(72761);t.OperationNames=(0,d.strEnum)("rebuildLibrary","forceRestartSync");const f=(0,r.lazy)((()=>(0,s.mkLogger)("model.Operation")));class m extends h.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(m.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return m.getFirstPendingOp(e)??m.ops().insertOne(e)}static getFirstPendingOp(e){return f().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,u.blank)(e?.name)?f().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return f().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce_(e,t,i=n.identity){const r=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=r)return void f().debug("applyOnce(): already done",{priorCompleted:r});const s=this.ops().insertOne(e);try{const e=await t(s);return(0,a.ending)()||s.markCompleted(),e}catch(t){if((0,o.isRedoableError)(t))return void f().info("applyOnce(): redoable error",{crit:e,error:t});throw(0,l.onError)("Operation.applyOnce(): "+(0,c.stringify)(e),t),t}}markCompleted(){null==this.completedAt&&(this.completedAt=Date.now(),this.upsert())}}t.Operation=m,m.$tableName="Operation",m.$uniqueColumnName="id",m.$useCache=!1},49796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.toPct=void 0;const r=i(48161),s=i(1708),n=i(48884),a=i(50213),o=i(28874),l=i(40958),u=i(42659),c=i(45599),d=i(98553),h=i(55835),f=i(31586),m=i(68708),p=i(67478),g=i(51926),y=i(59455),v=i(54993),w=i(76386),b=i(33572),S=i(55009),P=i(72761),_=(0,c.defer)((()=>(0,a.mkLogger)("model.Progress")));function M(e){return null==e||!(0,f.isNumber)(e)||e<0||e>100?void 0:(0,f.sigFigs)(e,3)}t.toPct=M;const T=(0,g.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function E(){const e=o.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*u.dayMs}t.defaultMinCreatedAt=E;class k extends P.TimestampedModel{static vacuum(e=o.Settings.progressRetentionDays.valueOrDefault*u.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t)));for(const e of(0,n.batches)(i,o.Settings.dbBatchSelectSize.valueOrDefault))S.ProgressMeta.dbl.runf((t=>t.whereIn("progressId",e).delete())),k.dbl.runf((t=>t.whereIn("id",e).delete()))}static countCompletedDirectorySyncs(){return this.dbl.pluckFirstf((e=>e.where({state:"done"}).whereNotNull("completedAt").where("uri","like","ps%")))}static times(){return _().tap({msg:"times()",result:this.dbl.all({sql:T})})}static insertNew(e){const t=(0,h.map)(e.dek,d.stringify);return this.ops().insertOne({...(0,m.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&this.assignFromPojo(e),super.upsert()}$beforeUpsert(){super.$beforeUpsert(),null==this.id&&(this.pid??(this.pid=s.pid),this.hostname??(this.hostname=(0,r.hostname)())),"done"===this.state&&(this.completedAt??(this.completedAt=Date.now())),this.completePct=M(this.completePct),this.incompletePct=M(this.incompletePct),this.scanningPct=M(this.scanningPct)}$afterUpsert(){super.$afterUpsert(),(0,w.tellWebProgressUpdated)()}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,l.compactBlanks)((0,p.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,d.stringify)((0,l.compactBlanks)((0,y.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,m.omit)(e,"volume","uri"))}getMeta(){return S.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncomplete(e=E()){return this.logger().tap({msg:"priorIncompleteProgress()",result:k.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc")))})}getLastCompletedAt(e=E()){return k.dbl.pluckFirstf((t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e)))}getLastIncompleteStartAt(){return k.dbl.pluckFirstf((e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0)))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),S.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,l.diff)(t.map((e=>e.name)),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),S.ProgressMeta.ops().upsert((0,m.entries)(e).map((([e,t])=>({progressId:this.id,name:e,value:(0,v.toS)(t)})))),(0,l.isNotEmpty)(i)&&S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).whereIn("name",i).delete()))}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),S.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,m.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=k,k.$tableName="Progress",k.$uniqueColumnName="id"},55009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},39604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(19851),s=i(50213),n=i(95696),a=i(40958),o=i(22573),l=i(86859),u=i(94448),c=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),d=(0,r.lazy)((()=>new l.DbRequest(u.modelDb,"ShaBlocklist")));function h(e){return null!=(0,u.modelDb)()&&!(0,o.blank)(e)&&c().tap({msg:"isShaBlockslisted",result:null!=d().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}function f(...e){if(null==u.modelDb.prior())return;const t=(0,a.uniq)(e).map((e=>({sha:e})));return(0,a.isEmpty)(t)?void 0:d().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,u.modelDb)())return null;const t=h(await n.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=h,t.upsertFileToShaBlockslist=async function(e){if(null==(0,u.modelDb)())return;const t=await n.PosixFile.for(e).sha();return null==t?void 0:f(t)},t.upsertToShaBlockslist=f},48723:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(56038),o=i(34102),l=i(19851),u=i(50213),c=i(36372),d=i(97352),h=i(28874),f=i(81168),m=i(42231),p=i(75020),g=i(40958),y=i(22573),v=i(42659),w=i(41400),b=i(50357),S=i(55835),P=i(31586),_=i(34666),M=i(20214),T=i(51926),E=i(59455),k=i(12168),D=i(6186),x=i(57038),C=i(21074),F=i(7656),A=i(43487),I=i(48722),O=i(45295),L=i(98784),R=i(41507),N=i(72761),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:A.Asset.dbl.pluckFirst(A.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset(),this.ops().clearDbCache()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{r.clear();for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.update({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.RecursiveAssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),this.ops().upsertOne(i)}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return A.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,M.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();return(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)})),r.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(A.Asset.dbl.all(t).map(I.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return A.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,k.fmt)(e.length)+" of ")+(0,k.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.RecursiveAssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?A.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(A.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(I.toAssetId))));for(const t of r)t.assetIdA.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(this.id??0),"Asset.id",i)).limit(t))).map(I.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!0,z.cmp=(e,t)=>(0,_.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=A.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(D.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e}),B);const V=(0,l.lazy)((()=>A.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},98784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(38156),s=i(3127),n=i(40958),a=i(41400),o=i(94715),l=i(55046),u=i(48723);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=new r.PushProgressObserver({op:"Rebuilding tag search index"},u.Tag.dbl.pluckFirstf((e=>e.count("*")))),t=this.dbl.db();o.Migrations.create_tag_fts(t.db),await u.Tag.ops().batched({qb:e=>e,onResults:t=>(this.$logger().throwIfAborted_(),this.insertFts(t),e.incrProgress(t.length),(0,a.delay)(1))}),e.completed()}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},41507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},94710:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Task=t.StaleTaskError=t.InvalidTaskError=t.TaskNames=t.Tasks=t.testTask=void 0;const c=i(78474),d=i(22454),h=i(23560),f=i(12089),m=i(76740),p=i(22911),g=i(99331),y=i(31562),v=i(38835),w=i(70025),b=i(8769),S=i(74128),P=i(28874),_=i(37692),M=i(40958),T=i(22573),E=i(42659),k=i(45599),D=i(98553),x=i(49769),C=i(68708),F=i(50989),A=i(59455),I=i(58723),O=i(34274),L=i(90901),R=i(61989),N=i(93755),B=i(69032),j=i(55046);t.testTask=(0,f.shim1)({name:"testTask",impl:async e=>{}}),t.Tasks={applyDeleted:I.applyDeleted,applyExcluded:I.applyExcluded,runTagMaintenance:B.runTagMaintenance,updateAssetFile:N.updateAssetFile_,repairAsset:async function(e){e.forceSync=!0,e.skipPreviews=!0,e.skipAssetTagging=!0;const t=await(0,R.updateAsset_)(e);return(0,M.isNotEmpty)(t?.assetIdsToUpdate)&&H.add(t?.assetIdsToUpdate.map((t=>({fn:"repairAsset",args:{...e,assetId:t},priority:W.repairAsset+1})))),null!=t&&!0!==t.deleted&&(0,T.blank)((0,A.toA)(t.rejected).join(""))&&(0,T.blank)(t.error)&&H.addOne("assetPostUpsertTasks",(0,C.omit)(e,"skipPreviews","skipAssetTagging")),t},assetPostUpsertTasks:L.assetPostUpsertTasks,syncFile:O.importFileToResult_,testTask:t.testTask},t.TaskNames=(0,F.strEnum)(...(0,C.keys)(t.Tasks));class z extends Error{}t.InvalidTaskError=z;class V extends Error{}t.StaleTaskError=V;const W={applyDeleted:16,applyExcluded:16,runTagMaintenance:14,updateAssetFile:13,repairAsset:12,assetPostUpsertTasks:10,syncFile:0,testTask:-1},U=["repairAsset"];class H extends j.Model{constructor(){super(...arguments),r.add(this),o.set(this,(0,k.defer)((()=>new m.Abortable)))}static countTaskNames(){const e={};for(const t of s.dbl.allf((e=>e.select("fn").count().groupBy("fn"))))e[t.fn]=t["count(*)"];return e}static orderBy(e){return e.orderBy([{column:"priority",order:"desc"},{column:"retries",order:"desc"},{column:"id",order:"asc"}])}static count(){return s.dbl.pluckFirstf((e=>e.count("id")))}static freeSlots(){return P.Settings.taskListCap.valueOrDefault-s.count()}static countByFn(e){return s.dbl.pluckFirstf((t=>t.where({fn:e}).count("id")))}static nextByFn(e,t=(e=>e)){return s.ops().allf((i=>s.orderBy(t(i.where({fn:e})))))}set args(e){this.argsJSON=(0,D.stringify)(e)}get args(){const e=(0,D.parseJSON)(this.argsJSON);return(0,C.notEmptyObj)(e)&&(e.halt=u(this,o,"f").call(this)),e}get isSerial(){return U.includes(this.fn)}toString(){return`Task#${this.fn}(${this.argsJSON})`}static addOne(e,t){return s.add([{fn:e,args:t}])[0]}static add(e,t=!1){if((0,M.isEmpty)(e))return[];const i=s.ops().upsert(e.map((e=>({fn:e.fn,argsJSON:(0,D.stringify)(e.args)})),t));return s.ee.emit("added",i),(0,h.isTaskListManager)()||(0,_.addStateEvent)("checkTasks"),i}$beforeUpsert(){this.priority??(this.priority=W[this.fn]),this.retries??(this.retries=P.Settings.maxRetries.valueOrDefault)}donePromise(){return(0,h.isTaskListManager)()?(0,x.getOrSet)(u(s,s,"f",n),this.id,(()=>new p.Deferred(this.toString(),{payload:this}))):(0,y.untilTrue)((()=>null==s.ops().findById(this.id)),{intervalMs:E.secondMs})}abort(e){this.logger().warn("aborting task",{reason:e,task:this}),u(this,o,"f").call(this).abort(e),this.delete(),(0,T.blank)(this.args.path)||(0,S.syncReport)().onProgress({path:this.args.path,from:this.fn,state:S.SyncFileStates.failed,details:e})}async _run(){if(this.retries<0)throw this.logger().warn(".run(): too many retries"+v.InternalErrorFlag,{job:this}),this.delete(),new z;if(!u(this,r,"m",l).call(this))throw this.logger().warn(".run(): someone already started this task",{job:this}),new V;try{const e=Date.now(),i=await t.Tasks[this.fn](this.args);return this.logger().throwIfAborted_(u(this,o,"f").prior()),s.taskResolvedCounts.incr(this.fn),s.ee.emit("resolved",this,i,Date.now()-e),this.delete(),u(s,s,"f",n).get(this.id)?.resolve(i),i}catch(e){if((0,g.ending)())throw this.logger().info("task failed, but we're ending. We'll leave it for next time.",{task:this}),e;throw s.taskRejectedCounts.incr(this.fn),(0,w.isRedoableError)(e)?(this.retries++,this.priority--,this.upsert()):!0===(0,w.isRetriableError)(e)&&this.retries>=0?this.logger().warn("run failed, but we can retry it later",{task:this,error:e}):(s.ee.emit("rejected",this,e),this.delete(),u(s,s,"f",n).get(this.id)?.reject(e),(0,b.onError)(this.toString()+" failed",e)),e}finally{u(s,s,"m",a).call(s)}}}t.Task=H,s=H,o=new WeakMap,r=new WeakSet,a=function(){for(const[e,t]of u(this,s,"f",n).entries())t.isSettled&&u(this,s,"f",n).delete(e)},l=function(){const e=this.retries;if(1===s.dbl.runf((t=>t.where({id:this.id,retries:e}).update({retries:e-1}))).changes)return--this.retries,!0;{const e=this.toJSON(),t=this.reload();return this.logger().warn(".#decrRetries(): someone already started this task",{before:e,reloaded:t}),!1}},H.$tableName="Task",H.$uniqueColumnName="fn,argsJSON",H.$useCache=!1,H.taskResolvedCounts=new d.CountingSet,H.taskRejectedCounts=new d.CountingSet,H.ee=new c.EventEmitter,n={value:new Map}},72761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),this.createdAt??(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},58723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyExcluded=t.applyDeleted=void 0;const r=i(50213),s=i(43487),n=(0,r.mkLogger)("ops.ApplyRemovable");async function a(e,t,i){const r=e?"Deleting":"Excluding",a=e?"deletedAt":"excludedAt";await s.Asset.dbl.batched({qb:e=>e.select("id").where("shown",0).andWhere(a,"<=",t),onResults:async t=>{for(const a of t){n.throwIfAborted_(i);try{await s.Asset.remove({assetId:a,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){n.error(r+" failed",{assetId:a,error:e})}}}})}t.applyDeleted=function(e){return a(!0,e.createdAt,e.halt)},t.applyExcluded=function(e){return a(!1,e.createdAt,e.halt)}},76386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)((()=>(0,s.mkLogger)("progress.Progress")));t.ProgressRateMs=(0,r.lazy)((()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:1.5))),t.tellWebProgressUpdated=(0,r.lazy)((async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch((e=>h().warn(".tellWebProgressUpdated: failed",{error:e})))}),(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},3996:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const a=i(19851),o=i(50213),l=i(79781),u=i(56519),c=i(56038),d=i(59189),h=i(38835),f=i(95696),m=i(48368),p=i(181),g=i(69589),y=i(28874),v=i(28544),w=i(47783),b=i(87001),S=i(40958),P=i(76790),_=i(22573),M=i(42659),T=i(55835),E=i(31586),k=i(43487),D=i(54017);t.isFileInSync=async function(e){return new C(f.PosixFile.for(e)).alreadySynced()};const x=new d.SerialLaterQueue;class C{constructor(e,t=(0,g.forceContextOrSetting)()){this.file=e,this.ctx=t,r.set(this,void 0),this.rejectedAssetIds=new Set,this.rejectedSiblingIds=new Set,this.alreadySynced=(0,c.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>n(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,c.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new D.AssetFile).updateFromFile_(this.file);return null==e?n(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,a.lazy)((async()=>{const e=await(0,w.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,a.lazy)((()=>y.Settings.useImageHashes.valueOrDefault?(0,m.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,a.lazy)((()=>(0,u.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,a.lazy)((async()=>{const e=await this.capturedAt_();return n(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,c.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,_.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return n(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await x.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return n(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new k.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,c.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,p.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtAndImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,c.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return n(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;n(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw n(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),s(this,r,(0,o.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f")}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),n(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}n(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(e=this.file){const t=await e.uri_();if(null!=t)return D.AssetFile.ops().firstf((e=>e.whereIn("uri",[...(0,b.uriEncodingVariants)(t),this.file.fileuri()])));n(this,r,"f").warn("byUri() uri is null",{file:e})}async assetByNormalizedPathUri(){const e=await this.file.normalize();return e.nativePath===this.file.nativePath?void 0:(await this.byUri(e))?.getAsset()}async assetBySha(){const e=await this.file.sha_();return k.Asset.findFirstByFile((t=>(t=t.where("AssetFile.sha",e),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds))),this.rejectedSiblingIds.size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),t)))}async assetByCapturedAtAndImageHash(){const e=await this.capturedAt_();if(null==e)return n(this,r,"f").throw("Cannot import, capturedAt is null"+h.InternalErrorFlag);if(y.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(D.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=y.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=D.AssetFile.query();return(0,E.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(M.secondMs,y.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,c.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)n(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(y.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void n(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const a=await this.dominantLabhashes();if((0,S.isNotEmpty)(a)){const t=e.localBoundaries({delta:4*s});if(null==t)n(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",a).orWhereIn("mode1",a).orWhereIn("mode2",a))));if(null!=e)return e}}const o=this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash));if(null!=o)return o;if(y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const r={};for(let e=0;e0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds)));const i=await this.firstSimilarAsset(D.AssetFile.ops().all(t));return null!=i&&n(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const s=(0,P.sortBy)(e.filter((e=>!this.rejectedSiblingIds.has(e.id)&&!this.rejectedAssetIds.has(e.assetId))),(e=>[(0,T.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of s)if(null!=e){await e.getNativePath();const i=D.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const s=(0,l.whyNotSameAsset)(t,e,i);if(null==s)return n(this,r,"f").info("Found sibling AssetFile",e),k.Asset.ops().findById(e.assetId);this.rejectedSiblingIds.add(e.id),n(this,r,"f").debug("Contemporary assetFile not similar: "+s,e?.uri)}}}t.AssetFileFinder=C,r=new WeakMap},34274:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult_=void 0;const u=i(19851),c=i(50213),d=i(73568),h=i(38835),f=i(95696),m=i(62105),p=i(74128),g=i(181),y=i(69589),v=i(28874),w=i(40958),b=i(22573),S=i(38639),P=i(59455),_=i(64526),M=i(19113),T=i(94710),E=i(3996),k=i(90901);t.importFileToResult_=async function(e){const t=_.Library.instanceRequired_();return(0,p.syncReport)().wrap_({path:e.path,from:"AssetFileImporter",fn_:()=>new D(f.PosixFile.for(e.path),t.assetFileRepository(),e).apply_()})};class D{constructor(e,t,i){r.add(this),this.file=e,this.repo=t,this.start=Date.now(),s.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else if(this.ctx.forceFilters||null==await this.prior()){const t=await(0,m.whyRejectFile)(this.file,(0,M.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,s,"f").throwIfAborted_();const i=await this.prior();if((0,w.isNotEmpty)(e)&&null!=i&&(l(this,s,"f").info("Deleting prior AssetFile",{rejected:e,prior:i}),i.delete(),this.ctx.skipAssetRepair?l(this,s,"f").info("Skipping asset repair",{assetId:i.assetId}):(l(this,s,"f").info("Scheduling asset repair",{assetId:i.assetId}),T.Task.addOne("repairAsset",{assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)}))),null!=i){const t=i.getAsset();null!=t?.deletedAt&&e.push("Asset is marked as deleted"),null!=t?.excludedAt&&e.push("Asset is marked as excluded")}if(l(this,s,"f").throwIfAborted_(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,b.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,s,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,s,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,s,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,r,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,s,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new E.AssetFileFinder(e,this.ctx),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=D,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(){l(this,s,"f").throwIfAborted_();const e=await l(this,s,"f").tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if((0,w.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,s,"f").throwIfAborted_();const t=await l(this,s,"f").tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,s,"f").throwIfAborted_();const i=await l(this,s,"f").tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return l(this,s,"f").throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return l(this,s,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,s,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,s,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;await l(this,s,"f").tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault}),l(this,s,"f").throwIfAborted_();try{o=await(0,k.assetPostUpsertTasks_)({asset:a,...this.ctx})}catch(e){e instanceof d.AbortError?l(this,s,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,s,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:r,assetFile:i,asset:a,uri:n,uris:[n,...(0,P.toA)(o?.newAssetFileUris)]}}},41844:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(50213),c=i(74128),d=i(81674),h=i(57902),f=i(4936),m=i(28874),p=i(47783),g=i(14245),y=i(67083),v=i(16170),w=i(54979),b=i(98604),S=i(40958),P=i(22573),_=i(98553),M=i(68708),T=i(89937),E=i(59455),k=i(54017),D=i(94710);t.mayCopyAssetsToLibrary=async function(){return m.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,u.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!0!==m.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,d.l)())return"no active subscription";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(m.Settings.libraryDir.valueOrDefault))return e+" already contained by "+m.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,m.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,E.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(k.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),D.Task.addOne("repairAsset",{assetId:t,forceSync:!0})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,_.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return a.addAssetFile(d),(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,p.readCapturedAt)(e),i=(0,f.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,p.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,p.readTags)(e);if(null!=i){if(m.Settings.writeGeolocationTagsToLibraryCopies.valueOrDefault){const e=(0,g.geolocationToXmp)(i);(0,M.isEmptyObj)(e)||await(0,p.writeTags_)(t,e)}return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred)}this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},90901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const r=i(50213),s=i(92434),n=i(73568),a=i(99331),o=i(39250),l=i(38835),u=i(57159),c=i(48604),d=i(66106),h=i(69589),f=i(40958),m=i(45599),p=i(23838),g=i(31586),y=i(64526),v=i(88224),w=i(43487),b=i(41844),S=i(68640),P=(0,m.defer)((()=>(0,r.mkLogger)("sync-file.AssetPostUpsertTasks"))),_=(0,m.defer)((()=>new o.LastOneInWins("Asset tasks")));async function M(e){const t=e,i=e,r=(0,g.toGt0)(t.asset?.id)??(0,g.toGt0)(i.assetId);if(null==r)throw new Error("assetPostUpsertTasks_(): unexpected null assetId"+l.InternalErrorFlag);const o=(0,h.forceContextOrSetting)(e),m=P().addContext(`.postUpsertAssetTasks_(Asset:${r})`);if(m.abortable=o.halt,o.skipPreviews&&o.skipAssetTagging)return void m.info("skipped (skipPreviews && skipAssetTagging)");const M=t.asset??w.Asset.ops().findById(r);if(null==M)return m.throw("unexpected null asset",{asset:M});try{return await _().enqueue({key:r,abortable:m.abortable,fn:()=>async function(e,t,i){const r=(0,h.forceContextOrSetting)(i),n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted_(),(0,f.isEmpty)(a)&&(await w.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,b.mayCopyAssetsToLibrary)())for(const[t,i]of(0,p.groupBy)(a,(e=>e.sha)).entries()){e.throwIfAborted_();try{for(const r of i)r.isInLibrary()&&await r.exists()&&e.debug("no-op for file SHA: already in library.",{sha:t,uri:r.uri});for(const e of i)if(await e.exists()){const t=await y.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,r);if(null!=t){o.newAssetFileUris.push(t.uri);continue}}}catch(r){e.warn("Failed to copy variation to library, but we'll try to continue",{sha:t,uris:i.map((e=>e.uri)),error:r})}}e.throwIfAborted_();const l=r.skipPreviews?void 0:await(0,S.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...r}),u=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?P().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,s.bestExistingAssetFile)(e.getAssetFiles())}(t,l);if(null==u)return e.throw("null primaryOrShownAssetFile_()",{asset:t});const m=await u.posixFile_();if(!0!==r.skipPreviews&&t.isVideo()){if(null==m)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});o.transcoded=null!=await(0,d.transcode_)(m,c.Previews.instance().ap(n).mp4(),{force:r.forceRebuildPreviews,halt:r.halt})}return e.throwIfAborted_(),t.markShownAndUpsert_(u),r.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,v.tagAndUpsertAsset_)(t),o}(m,M,{...e,...o})})}catch(e){if(e instanceof n.AbortError)return void m.warn("aborted, next caller will clean up my mess",{error:e});const t=[e];if(!(0,a.ending)()){m.error("failed, marking asset unshown",{error:e});try{M.markUnshownAndUpsert()}catch(e){m.error("failed to mark asset unshown",{upsertError:e}),t.push(e)}}throw new u.WrappedError("Failed to post-process assset "+M.id,{causes:t})}}t.assetPostUpsertTasks=function(e){try{return M(e)}catch(e){if(e instanceof n.AbortError)return void P().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=M},61989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset_=t.updateAsset=void 0;const r=i(48884),s=i(50213),n=i(45393),a=i(79184),o=i(79781),l=i(92434),u=i(56519),c=i(70417),d=i(69589),h=i(28874),f=i(40958),m=i(22573),p=i(38639),g=i(50357),y=i(43487),v=i(54017),w=i(3996),b=i(90901);async function S(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,r=(0,s.mkLogger)(`sync-file.UpdateAsset(${i})`);r.abortable=t.halt;const S=y.Asset.ops().findById(i);if(null==S)return r.throw("no such asset");const _=S.getAssetFiles({refresh:!0});if((0,f.isEmpty)(_))return r.warn("No asset files: deleting."),S.delete(),{asset:S,rejected:"Empty asset (no AssetFiles)"};const M=S.$clone(),T=S.getShown()?.$clone();for(const e of _)r.throwIfAborted_(),await e.upsertIfNeeded_(void 0,t);_.some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&S.clear(),await P(r,_);const E=(0,l.sortAssetFiles)(_),k=E?.[0];if((0,f.isEmpty)(E)||null==k)return r.warn("No existing files. Skipping for now."),S.markUnshownAndUpsert(),{asset:S,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!k.isVersionUpToDate())return r.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:k}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${k.id}, could not be updated. Un-showing Asset:${i}`};const D=await k.capturedAt();if(null==D)return r.warn("Best file failed to extract a captured-at",{bestAcceptedAF:k}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${k.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const x=new Set,[C,F]=await(0,u.partitionAsync)(E,(e=>(0,o.isSimilarAssetFile)(e,k)));if(r.throwIfAborted_(),(0,f.isNotEmpty)(F)){const e=await(0,a.aggregateAssetFiles)(F);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});x.add(e.id);for(const i of t)e.addAssetFile(i);v.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),r.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function A(e){return(0,f.uniq)(C.map((t=>t[e])))}const I=await Promise.all(C.map((e=>e.capturedAt()))),O=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,L=I.map((e=>e?.localBoundaries({delta:O}))),R=(0,c.min)(L.map((e=>e?.start)))??D.localBoundaries({delta:O})?.start,N=(0,c.max)(L.map((e=>e?.end)))??D.localBoundaries({delta:O})?.end,B=v.AssetFile.ops().all(v.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${k.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",A("sha")),null==R||null==N?r.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:R,endBoundary:N}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[R,N]),e.orWhereIn("AssetFile.meanHash",A("meanHash")).orWhereIn("AssetFile.diffHash",A("diffHash")).orWhereIn("AssetFile.dctHash",A("dctHash"))))));if(r.throwIfAborted_(),h.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const e=await k.posixFile();if(null==e)r.info("bestAcceptedAF has no posixFile, cannot expand query for fuzzy dates",{bestAcceptedAF:k});else{const i=new w.AssetFileFinder(e,t);for(const e of[...C,...B])i.rejectedAssetIds.add(e.assetId),i.rejectedAssetIds.add(e.id);let s=h.Settings.maxContemporaryAdoptionAssets.valueOrDefault;for(;--s>0;){r.throwIfAborted_();const e=await i.assetByCapturedAtAndImageHash();if(null==e){r.info("allowFuzzyDateImageHashMatches(): no additional assets found to adopt");break}if(r.info("allowFuzzyDateImageHashMatches(): found asset with similar image",{a:e}),null!=e){i.rejectedAssetIds.add(e.id);for(const t of e.getAssetFiles())r.info("found asset file by fuzzy date and image hash",{uri:t.uri,assetId:e.id}),B.push(t),i.rejectedAssetIds.add(t.id)}}}}r.info("asset file candidates for adoption: ",B.map((e=>e.posixPathFromGrandparent)));const j=[];for(const e of B){r.throwIfAborted_();try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,k)&&(r.info("adopting similar asset file",{af:e}),x.add(e.assetId),e.shown=!1,S.addAssetFile(e),e.upsert(),j.push(e))}catch(t){r.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}}r.info("fetched expansion",{retainAFs:C.map((e=>e.id)),rejectAFs:F.map((e=>e.id)),externalAssetFiles:B.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:j.map((e=>e.posixPathFromGrandparent))}),await P(r,[...C,...j]),t.skipPreviews&&t.skipAssetTagging?(r.info("skipping previews and tagging",t),S.upsert()):await(0,b.assetPostUpsertTasks_)({...t,asset:S});const z=!(0,g.eql)(M,S),V=!(0,g.eql)(T,S.getShown()),W=!(z||V||t.forceRebuildPreviews||t.forceSync);return r.tap({msg:"updateAsset() result",level:"info",result:{asset:S,assetIdsToUpdate:Array.from(x),assetFiles:S.assetFiles,skipped:W},meta:{ctx:t,assetChanged:z,primaryAssetFileChanged:V}})}async function P(e,t){const[i,s]=(0,r.partition)(t,(e=>e.isVersionUpToDate()));for(const t of s){e.throwIfAborted_();const r=i.find((e=>e.sha===t.sha));if(null!=r){e.info("backfilling",{sibling:r,dest:t});const i=await t.updateFromShaSibling_(r);null!=i&&i.upsert()}}}t.updateAsset=async function(e){try{const t=await S(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}},t.updateAsset_=S},93755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t.updateAssetFile_=t.updateAssetFile=void 0;const r=i(50213),s=i(92434),n=i(98314),a=i(74128),o=i(69589),l=i(87001),u=i(40958),c=i(22573),d=i(68708),h=i(43487),f=i(54017),m=i(94710);async function p(e){const t=Date.now(),i=e,s=e,n=s.af?.id??i.assetFileId,u=(0,r.mkLogger)(`updateAssetFile(${n})`),d=s.af??f.AssetFile.ops().findById(n);if(null==d)return u.throw("db record not found",{assetFileId:n});const h=await d.posixFile_(),p=(0,o.forceContextOrSetting)(e),v={id:n,assetFileId:n,path:h?.nativePath,uri:d?.uri};if(null==h){const e=["cannot resolve URI"];return(0,c.blank)(d.mountpoint)||e.push("is "+d.mountpoint+" mounted?"),(0,a.syncReport)().onProgress({path:d.uri,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:e.join(": "),state:a.SyncFileStates.skipped}),{...v,error:"file for URI not found"}}const w=await(h?.isDeletedUri(d.uri));if(null==w)return u.info("no-op: file URI points to an unmounted volume",v),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:((0,c.toNotBlank)(d.mountpoint)??"volume")+" is not currently mounted",state:a.SyncFileStates.skipped}),{...v,skipped:!0};const b=e.whyReject??await d.whyRejected();if(w||!(0,c.blank)(b)){const e={...v,rejected:b,deleted:w};return u.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:w?"file no longer exists":"rejected: "+b,state:a.SyncFileStates.deleted}),d.delete(),!0!==p.skipAssetRepair&&m.Task.addOne("repairAsset",{assetId:d.assetId}),e}const S=await h.uri_();if(!await(0,l.uriIsEquivalent)(S,d.uri)){const e=await g(d,S,p);if(null!=e)return{...v,...e}}return!p.forceSync&&await d.matchesFile()?(u.info("no-op: file already matches db record",v),d.touch(),{...v,skipped:!0}):{...v,...await y(d,p)}}async function g(e,t,i){const n=(0,r.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,u.uniq)([...(0,l.uriEncodingVariants)(e.uri),...(0,l.uriEncodingVariants)(t)]);n.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const o=f.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,u.isNotEmpty)(o)){n.warn("Found other AssetFiles with equivalent URIs.",{afIds:o.map((e=>e.id))});const t=[e,...o],r=(0,s.sortAssetFiles)(t);if((0,u.isEmpty)(r))return n.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,d.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const l=t.map((e=>e.id));for(const e of r)if(await e.exists()){f.AssetFile.dbl.runf((t=>t.whereIn("id",l.filter((t=>t!==e.id))).delete()));const r=y(e,i);return h.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,u.uniq)(t.map((e=>e.assetId)))))),r}}n.info("no-op, no duplicate URIs.")}async function y(e,t){const i=Date.now();return null!=await e.upsertIfNeeded_(void 0,t)&&h.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:await e.getNativePath(),elapsedMs:Date.now()-i,from:"updateAssetFileIfNeeded()",state:e.syncState??a.SyncFileStates.unknown}),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await p(e)}catch(t){return{id:e.assetFileId,...e,error:(0,n.errorToS)(t)}}},t.updateAssetFile_=p,t.handleAssetFileUriChange=g,t.updateAssetFileIfNeeded=y},68640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const r=i(99331),s=i(38835),n=i(48604),a=i(50213),o=i(69589),l=i(87001),u=i(40958),c=i(45599),d=i(50357),h=i(31586),f=i(68708),m=i(59455),p=i(43487),g=(0,c.defer)((()=>(0,a.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,m.toA)(e.assetFiles).find((e=>(0,h.gt0)(e.assetId)))?.assetId,i=(0,o.forceContextOrSetting)(e),a=g().addContext(".Asset:"+t);if(i.skipPreviews)return void a.warn("skipPreviews is true: no-op");if(!(0,h.gt0)(t))return a.throw("invalid assetId",{assetId:t});const c=e.asset??p.Asset.ops().findById(t);if(null==c)return a.throw("Asset:"+t+" not found");a.throwIfAborted_(i.halt);try{const e=await c.getExistingAssetFiles();if((0,u.isEmpty)(e))return void a.warn("no existing assetFiles",{asset:c});const r=n.Previews.instance().ap(t),o=await r.readInfo();a.throwIfAborted_(i.halt);const h=await(0,n.buildAssetPreviews_)({...i,assetId:t,assetFiles:e}),m=e.find((e=>e.id===h?.assetFileId))??e.find((e=>(0,l.uriIsEquivalent)(h?.uri,e.uri)));a.info("buildAssetPreviews_()",{result:h,primaryAssetFile:m});const p=await(m?.posixFile_());if(null==m||null==p||!0!==await(p?.exists()))return a.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:h,assetFiles:e.map((e=>(0,f.pick)(e,"id","uri"))),primaryAssetFile:m,primaryPosixFile:p});const g=(0,d.eql)(o,h),y=null==h||g;return{...h,noop:y}}catch(e){throw(0,r.ending)()||(a.warn("Failed to update previews. Un-showing asset "+t,{error:e}),c.markUnshownAndUpsert()),e}}},94019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(87290),o=i(34102),l=i(16287),u=i(45969),c=i(43334),d=i(28874),h=i(45200),f=i(69375),m=i(7014),p=i(41400),g=i(31586),y=i(92244),v=i(46832);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const w=(0,r.lazy)((async()=>{const e=[];for(const t of await(0,m.volumes)()){if(!0===t.ignorable||!1===t.ok||(c.isMac||(0,u.isDocker)())&&"/"===t.mountpoint||(0,f.isExcludedMountpoint)(t.mountpoint)||!(0,g.gt0)(t.size))continue;const i=await(0,v.toUriPath)(t.mountpoint,(0,h.nativePath2uri)(t.mountpoint,t));null!=i&&e.push(i)}return e}));async function b(){const e=[],i=[],r=d.Settings.argvScanPaths.toNotEmpty()??d.Settings.scanPaths.values;for(const s of r)if(await(0,l.isReadableDirectory)(s)){const r=await(0,v.toUriPath)(s);null==r?(e.push(s),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",s)):i.push(r)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",s);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,p.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];if(d.Settings.argvScanPaths.isNotEmpty()){for(const i of d.Settings.argvScanPaths.values){const r=await(0,v.toUriPath)(i);null!=r?e.push(r):(0,t.logger)().warn("pathsToSync(): Ignoring scanPath element: failed to create URI path",i)}return e}e.push(...(await b()).result),!0===d.Settings.scanAllDrives.value&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:d.Settings.libraryDir.valueOrDefault,originalsDir:d.Settings.originalsDir.value})));d.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),d.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},98622:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runTimeIsStale=t.SyncCron=void 0;const r=i(1708),s=i(17415),n=i(28874),a=i(41400),o=i(30301),l=i(31586);t.SyncCron=(0,o.lazy)((()=>{const e=n.Settings.syncCronTZ.valueOrDefault??(0,s.toValidIanaZone)(r.env.TZ);return n.Settings.syncCron.cron(null==e?void 0:{timezone:e})})),(0,a.later)((()=>{n.Settings.syncCron.watchLater((()=>t.SyncCron.unset())),n.Settings.syncCronTZ.watchLater((()=>t.SyncCron.unset()))})),t.runTimeIsStale=function(e){return null==e||(0,l.lte)((0,t.SyncCron)().nextRun(new Date(e))?.getTime(),Date.now())}},92244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.isStale=t.bestPathToSync=t.stalePathsToSync=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(23560),o=i(22277),l=i(87290),u=i(57902),c=i(28874),d=i(40958),h=i(76790),f=i(42659),m=i(75240),p=i(31586),g=i(20958),y=i(49796),v=i(94019),w=i(98622),b=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));t.nativePathBlocklist=new o.TTLSet(10*f.minuteMs);const S=10*f.minuteMs;async function P(){const e=await(0,v.pathsToSync)(),t=c.Settings.forceSync.valueOrDefault?[]:await y.Progress.times();return b().tap({msg:"pathsAndTimesToSync()",level:u.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}function _(e,t){return null==e.lastStartedAt||null==e.lastCompletedAt||(0,p.lte)(e.lastStartedAt,t)||(0,w.runTimeIsStale)(e.lastCompletedAt)}function M(){return g.Operation.getFirstPendingOp({name:g.OperationNames.forceRestartSync})}async function T(e){const t=M(),i=t?.createdAt,s=e.filter((e=>_(e,i)));if((0,d.isEmpty)(s))return(0,a.isSyncService)()&&t?.markCompleted(),b().tap({msg:"bestStable(): No stale paths to sync!",level:"info",result:void 0,meta:{arr:e,forceRestartOp:t}});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,p.gt)(e.lastUpdatedAt,Date.now()-10*f.minuteMs))return b().tap({msg:"bestStable(): returning most recently updated",level:"info",result:{...e,why:"recently updated"}})}const n=(0,r.leastBy)(s,(e=>[e.lastStartedAt??0,e.lastCompletedAt??0]));return b().tap({msg:"bestStable(): returning least-recently-started or least-recently-completed:",level:"info",result:null==n?void 0:{...n,why:"least recently started or completed"},meta:{stale:s}})}function E(e,t){return null==e.lastStartedAt?"new":null==e.lastCompletedAt?"todo":(0,p.gt)(e.lastUpdatedAt,Date.now()-f.minuteMs)?"syncing":_(e,t)?"stale":"synced"}function k(e){return null==e?void 0:new Date(e).toISOString()}function D(e){if(null==e)return;const t=Date.now()-e;return t<2*f.secondMs?"just now":(0,m.fmtDuration)(t)+" ago"}t.pathsAndTimesToSync=P,t.stalePathsToSync=async function(){const e=await P(),t=M(),i=t?.createdAt,r=e.filter((e=>_(e,i)));return(0,h.sortBy)(r,(e=>[null!=e.lastUpdatedAt&&Date.now()-Se.nativePath)),t=await T(e),i=(0,l.libraryOriginalsDirPosixFile)()?.nativePath,r=M()?.createdAt;return e.map((e=>({path:e.nativePath,library:i===e.nativePath,status:E(e,r),isNext:e.nativePath===t?.nativePath,lastStartedISO:k(e.lastStartedAt),lastStarted:D(e.lastStartedAt),lastCompletedISO:k(e.lastCompletedAt),lastCompleted:D(e.lastCompletedAt)})))}},46832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.posixFileToUriPath=t.toUriPath=void 0;const r=i(53265),s=i(45200),n=i(22573),a=i(68708),o=i(54993);async function l(e,t){if((0,a.isObject)(e)&&!(0,n.blank)(e.nativePath)&&!(0,n.blank)(e.uri))return e;const i=(0,r.resolve)((0,o.toS)(e)),l=await t??await(0,s.nativePath2uri)(i);return null==l?void 0:{nativePath:i,uri:l.toString()}}t.toUriPath=l,t.posixFileToUriPath=function(e){return l(e.nativePath,e.uriObject_())}},7656:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.DirectAssetCountForTagQuery=t.RecursiveAssetCountForTagQuery=t.nonLeafTagIds=void 0;const r=i(50213),s=i(56038),n=i(95704),a=i(38156),o=i(42659),l=i(45599),u=i(41400),c=i(31586),d=i(51926),h=(0,l.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function f(e){return e.prepare((0,d.compressWhitespace)("SELECT"," t1.id,"," count(t2.id) AS cnt","FROM"," Tag t1"," JOIN Tag t2 ON t1.id = t2.parentId","GROUP BY"," 1","HAVING"," cnt > 0")).pluck().all()}async function m(e,i=[]){const r=e.prepare(t.RecursiveAssetCountForTagQuery).pluck(),o=e.prepare(t.DirectAssetCountForTagQuery).pluck(),l=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId"),c=new Set(f(e)),d=new a.PushProgressObserver({op:"Rebuilding tag asset counts"},e.prepare("SELECT count(*) FROM Tag").pluck().get());await(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e){const e=!c.has(t);(0,s.timeSync)("db.rebuildTagAssetCounts("+(e?"leaf":"cte")+")",(()=>{const s=(e?o:r).get({tagId:t});l.run({tagId:t,assetCount:s,updatedAt:Date.now()}),d.incrProgress(),h().debug("_rebuildTagAssetCounts()",{isLeaf:e,whereClauses:i,tagId:t,assetCount:s})})),t%10==0&&(h().throwIfAborted_(),await(0,u.delay)(1))}}}),d.completed()}t.nonLeafTagIds=f,t.RecursiveAssetCountForTagQuery=(0,d.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.DirectAssetCountForTagQuery=(0,d.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," AssetTag"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," AssetTag.tagId = :tagId"," AND Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL;"),t.rebuildTagAssetCounts=async function(e,t=o.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>m(e,["assetCount IS NULL"]))),(0,c.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rm(e)))}},69032:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(1728),c=i(56038),d=i(34102),h=i(49076),f=i(69589),m=i(28874),p=i(42231),g=i(85087),y=i(98770),v=i(59107),w=i(63870),b=i(7014),S=i(22573),P=i(42659),_=i(41400),M=i(75240),T=i(31586),E=i(34666),k=i(51926),D=i(75020),x=i(54017),C=i(48723),F=i(98784),A=i(7656),I=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return I().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=((0,o.isTest)()?5:30)*P.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=I().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.throwIfAborted_(i?.halt),await L(),i.recountAllTags&&(s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)(),s.info("rebuilding tag asset counts..."),await(0,A.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0))}catch(e){I().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,T.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),I().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const L=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{I().info("updating tag mountpoints...");const e=C.Tag.findByPath([D.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await N(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function R(){t.tagFtsRebuild.unset(),L.unset()}async function N(e){if(null==e||2!==e.depth||!e._path.startsWith(D.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===D.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,M.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,_.later)((()=>{(0,d.ee)().on("clearCache",R),m.Settings.libraryDir.watchLater(R)})),t.fixFileRootTag=N,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,k.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,_.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},87550:e=>{"use strict";e.exports=require("better-sqlite3")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},66150:e=>{"use strict";e.exports=require("fast-xml-parser")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},31832:e=>{"use strict";e.exports=require("knex")},51168:e=>{"use strict";e.exports=require("luxon")},93973:e=>{"use strict";e.exports=require("ml-kmeans")},4927:e=>{"use strict";e.exports=require("papaparse")},83058:e=>{"use strict";e.exports=require("picomatch")},22915:e=>{"use strict";e.exports=require("platform-folders")},57272:e=>{"use strict";e.exports=require("plist")},57160:e=>{"use strict";e.exports=require("punycode.js")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},93944:e=>{"use strict";e.exports=require("source-map-support")},49378:e=>{"use strict";e.exports=require("trash")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},76982:e=>{"use strict";e.exports=require("crypto")},34589:e=>{"use strict";e.exports=require("node:assert")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=86801);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/list.js b/bin/list.js index d833938..3af03ff 100755 --- a/bin/list.js +++ b/bin/list.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463:(e,t,i)=>{const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),w=m(y,f);return a(s,t,o,p,w)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),w=m(g,p);if(!l(s,w))throw new o("decryption failed");const v=await y(a,f,r.subarray(16));if(!v)throw new o("decryption failed");return v},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),w=u.subarray(32),v=await g(e,y,w),b=n(o,l,v,t,s),S=m(b,p);return a(o,t,l,v,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),w=p.subarray(0,32),v=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,w,v);if(!P)throw new o("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const s=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*s);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*s);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(s*t);case"day":case"days":case"d":return Math.round(864e5*s);case"week":case"weeks":case"w":return Math.round(6048e5*s);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*s)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227:(e,t,i)=>{const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120:(e,t,i)=>{const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827:(e,t,i)=>{const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015:(e,t,i)=>{const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function w(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...w(e.slice(i+1))]}function v(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return T(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function T(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function x(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return w(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=v,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=T,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[T(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await x(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),w=i(25764),v=i(38836),b=i(99331),S=i(95937),P=i(98314),T=i(38835),_=i(70025),M=i(8769),E=i(43334),D=i(95402),x=i(28874),k=i(63870);class C extends v.EndableWrapper{constructor(e,t,i=w.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>n(this,r,"m",s).call(this)),i,"worker"===e?(0,k.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,D.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,S.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+T.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&D.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,b.ending)()||!0===(0,_.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,r=new WeakSet,s=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(E.isWin?3:1)*c.minuteMs,maxTasksPerProcess:x.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:x.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:x.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,k.commandTimeoutMs)(),taskTimeoutMillis:x.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,s.set(this,void 0),n.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,s,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]=t))}get length(){return u(this,n,"f")}set length(e){l(this,n,(0,d.clamp)(0,u(this,n,"f"),e),"f")}clear(){this.length=0}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,n,"f")),e<0||e>=u(this,n,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,s,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,n,"f"){u(this,s,"f")[e]=c}));return u(this,n,"f")}pop(){return u(this,r,"m",o).call(this,u(this,n,"f")-1,(e=>{var t;return l(this,n,(t=u(this,n,"f"),--t),"f"),u(this,s,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,n,"f"){u(this,s,"f")[e]=c,l(this,a,e,"f")}));return u(this,n,"f")}shift(){return u(this,r,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,n,(i=u(this,n,"f"),--i),"f"),u(this,s,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",o).call(this,u(this,n,"f")-1-e,(e=>{const i=u(this,s,"f")[e];u(this,s,"f")[e]=u(this,s,"f")[t],u(this,s,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=n(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),s=i(31586),n=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),s=i(65843),n=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),s=i(20014),n=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)((()=>!1))},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),s=i(98553);var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},57206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(77988),s=i(51168),n=i(45599),a=i(98553),o=i(68708),l=i(24689),u=i(21330),c=i(57159),d=i(28544),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},19851:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function w(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(w()??await(m.isWin?P():m.isMac?_():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(w);const v=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=v.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const T={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],T))}async function M(){return S(w((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],T)})))}t.localeMac=_,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),s=i(32105),n=i(14593);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),s=i(55835),n=i(59455),a=i(48884);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),s=i(54557);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),s=i(42659),n=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,s]of(0,l.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,l.keys)(e))if(r[n]=t(n,e[n]),s++,(0,o.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,n.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),s=i(73024),n=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),w=i(30933),v=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function T(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function M(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){v().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=T,t.hasApt=function(){return P()||T()},t.isFedora=_,t.isAlpine=M;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function x(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const k=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return x(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return v().warn("osNameMac(): unknown release",e),b()}}function F(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":x(e,D);return null!=t?`Windows ${t} (${e})`:(v().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,w.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(T())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(M())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},45393:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=4},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(72993),s=i(50213),n=i(23560),a=i(43334);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(85949).title=t}catch(e){(0,s.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},92782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),s=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),s=i(56409),n=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}async function w(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return s.promise}const v=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return w(...e)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),w(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),s=i(54993);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),w=i(34102),v=i(43334),b=i(24399),S=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,w.ee)().on("clearCache",(()=>M.prior()?.clear()))));const T=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>v.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>T().includes(e.toLowerCase())))};let _=!0;const M=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(v.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(1708)),n=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),s=i(57150),n=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,n.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,s.logStartup)())}},28850:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),s.set(this,void 0),n(this,r,e,"f")}_call(){return(0,l.time)(a(this,r,"f")+(null==a(this,s,"f")?"(local)":"(remote)"),null==a(this,s,"f")?this.impl():a(this,s,"f").call(this))}setShim(e){n(this,s,e,"f")}hasShim(){return null!=a(this,s,"f")}clearShim(){n(this,s,void 0,"f")}}r=new WeakMap,s=new WeakMap},12089:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=a,s.set(this,void 0),n.set(this,void 0),l(this,s,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",a).call(this,e),(()=>u(this,r,"m",o).call(this,e)))}setShim(e){l(this,n,e,"f")}hasShim(){return null!=u(this,n,"f")}clearShim(){l(this,n,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",a).call(this,e))}}s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,s,"f")+(null==u(this,n,"f")?"(local)":"(remote)"),null==u(this,n,"f")?this.impl(e):u(this,n,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return s(this,r,"f")[Symbol.iterator]()}get length(){return s(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=s(this,r,"f").length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),a=this.valueOf(s(this,r,"f")[n]);if(e===a)return{found:!0,index:n};e>a?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&s(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...s(this,r,"f")];const a=t=>t<0||t>s(this,r,"f").length-1?null:(i??this.diff)(s(this,r,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return s(this,r,"f").shift()}at(e){return(0,a.at)(s(this,r,"f"),e)}toA(){return[...s(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===s(this,r,"f").length-1){const e=[...s(this,r,"f")];return s(this,r,"f").length=0,e}return s(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return s(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),s=i(82328),n=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),s=i(95705);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const w=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" …(+"+s+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const v=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return v.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const T=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return T.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['‘’].*['‘’]$/,D=/^["“”„«»〃].*["“”„«»〃]$/;function x(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>w.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function w(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=v(i),t=v(r);return 2*b(e,t).length/(e.length+t.length)}))}function v(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function T(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=w,t.bigrams=v,t.nonUniqIntersection=b,t.lnsDiff=T;const _=/[^\da-z]+/gi;function M(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=M,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:w(e,t),lns:T(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),s=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},75387:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},65211:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(19851),s=i(76790),n=i(22573),a=i(54993),o=i(7282),l=i(55222);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!(0,o.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),u=0}},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),s=i(55835),n=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},79184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(59455),s=i(48884),n=i(22859),a=i(28874),o=i(79781),l=i(92434);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(50357),o=i(55835),l=i(31586),u=i(68708),c=i(12168),d=i(23467),h=i(73168),f=i(50213),m=i(86580),p=i(48368),g=i(80361),y=i(28874),w=i(28544),v=i(75767),b=i(16170),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} ≠ ${o}`}function T(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function _(e,t){return[T(e),T(t)]}function M(e,t,i){const r=(0,v.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.aKey}:${r.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=w.CapturedAt.fromAssetFile(e),f=w.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const T=a.isFuzzy||f.isFuzzy;if(T&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",_)??P(e,i,"model",_);if(null!=E)return E;const D=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),x={cameraId:M(e,i,"cameraId")??null,imageId:M(e,i,"imageId")??null,lensId:M(e,i,"lensId")??null,exposureSettings:(0,v.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(D,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(D)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:x});const k=(0,s.compact)((0,u.values)(x));if((0,s.isNotEmpty)(k))return k.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:T});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(x).filter((e=>null==x[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos ≠ images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=E(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},13991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(19851),s=i(55835),n=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function w(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function v(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([w(e),v(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=w,t.assetFileStatFields_=v,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),w=i(14036),v=i(45200),b=i(34238),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function T(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function M(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=T,t.sortScale=_,t.mtime2sort=M;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function x(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=T(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,w.isSupportedByCurrentBrowserExt)(n.ext),mtime:M(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function k(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=x(e);if(null==t)return;const i=[];for(const e of k())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=x,t.assetFileSortFields=k,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,v.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),s.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,n(this,s,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return n(this,s,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,n(this,s,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=n(this,r,"f")&&clearTimeout(n(this,r,"f")),a(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,s=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(87997)),n=i(31586);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const w=y(i(87997)),v=y(i(57975)),b=i(45599),S=i(26905),P=i(55835),T=i(31586),_=i(68708),M=i(20214),E=i(57153),D=i(85556),x=i(50213),k=i(70025),C=i(95937),F="TIMEOUT",A=(0,b.defer)((()=>(0,x.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,T.gt0)(t)?new s(F).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const s=i[r];if(s.isSettled){if(s.name===F)return void A().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield s.value}}if(i.every((e=>e.name===F)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[v.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(w.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,T.gt0)(e)&&(g(this,h,w.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,s=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),w.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>v()),10*n.minuteMs);const y=5*n.secondMs;async function w(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function v(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>w(e))))},t.end=w,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),v();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>w(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,s.compact)(g.valuesFlat()).map((e=>w(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class w extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=w,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,s=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function w(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=w,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{w({reason:`${e}:${t}`,status:0,error:i})}))}))},39250:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(23838),a=i(54993),o=i(15674),l=i(73568),u=i(76740),c=i(99331),d=i(42638);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new d.Promises(e,t)}vacuum(){return s(this,r,"f").filterInPlace(((e,t)=>t.isPending&&!0!==t.payload?.aborted)),s(this,r,"f").valueCount()}enqueue({key:e,abortable:t,fn:i}){for(const t of s(this,r,"f").get(e)??[])t.payload?.abort("aborted by new work");if(this.vacuum(),(0,c.ending)())throw new l.AbortError("ending");const n=t??new u.Abortable,o=this.p.serial((0,a.toS)(e),(()=>i(n)),n);return s(this,r,"f").add(e,o),o}},r=new WeakMap},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),w=i(22911),v=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new b(e,t,i,r)};class b extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,n,0,"f"),d(this,s,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,r,"m",u).call(this,w.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,n,"f")}isStale(){return null==c(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,s,"f")?void 0:Date.now()-c(this,s,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(v().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,n,(i=c(this,n,"f"),++i),"f")}},u=function(e){d(this,s,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof w.Deferred?e:new w.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),s=i(80049);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},22781:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),s.set(this,!1),n.set(this,!1)}_call(){return a(this,s,"f")?(o(this,n,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,r,"f")):(o(this,s,!0,"f"),o(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,s,!1,"f"),!0===this.runLaterIfBusy&&a(this,n,"f")&&(o(this,n,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,s,"f")}prior(){return a(this,r,"f")}async force(){return await a(this,r,"f"),this._call()}}r=new WeakMap,s=new WeakMap,n=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),w=i(15674),v=i(42638);var b=i(20214);async function S(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function T({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,l.gt0)(s)?(0,c.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function _({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,w.maxCpus)()))<=1)return T({arr:e,f:t,name:i,timeoutMs:n});const u=a??(o.length<=s?v.PermissivePromises:new v.Promises(i,(()=>s))),d=(0,l.gt0)(n)?e=>(0,c.thenOrTimeoutError)(t(e),n):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=S,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await S(s);r.push(...await S(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=T,t.mapAsyncSerial=async function(e){return(await T(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await _({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){s=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await _({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),w=i(25764),v=i(38836),b=i(73614);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function T(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new v.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),w.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=T,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>T(e,t)),i)}},42638:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),w=i(54993),v=i(89788),b=i(82647),S=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,w.toS)(e)};class T{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new v.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=T,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new T(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new T(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},59189:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(1708)),n=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),w=i(50213),v=i(7282),b=i(88158),S=i(45969),P=i(43334),T=i(28874),_=i(3790);function M(e){return E().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const E=(0,n.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(T.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,b.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,T.allSettings)())t.watchLater(e)}));const D=["HOME","LANG","USER"],x=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],k=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?D:x),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,T.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,v.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,S.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,T.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,o.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(s.default.env,(e=>M(e)||!(0,_.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:A({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let F=!1;function A({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...k(),...i?(0,g.childProcLocale)():{},...C(r),...e??{}});for(const e of(0,T.transientSettings)())e.deleteFromEnv(s);if((0,y.isLogged)("debug")&&!F){F=!0;const e=(0,w.mkLogger)("child.ChildEnv"),t=(0,l.entries)(s).map((([e,t])=>[e,(0,_.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return s}t.childEnv=A},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),w=i(79089),v=i(45255),b=i(22911),S=i(4867),P=i(73614),T=i(70025),_=i(57159),M=i(36868),E=i(66184),D=i(45643),x=i(95402),k=i(9727),C=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function A(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,x.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,D.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{x.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,x.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,D.waitForPidExit)(i,5e3)}function I(e,i,r,s=0){const a=new Date,o=[];return(0,w.niceable)(i,r)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,w.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&A(e)}),s-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,x.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,k.spawnOptions)(r);return(0,E.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new b.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(a.stdin);const w=new d.Latch;null==a.stdout?w.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>w.resolve())));const P=new d.Latch;null==a.stderr||s?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,S.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:w.state(),stderr:P.state()}),await(0,S.thenOrTimeoutError)({p:w.promise,timeoutMs:v.ShortCommandTimeoutMs,halt:i.halt}),await(0,S.thenOrTimeoutError)({p:P.promise,timeoutMs:v.ShortCommandTimeoutMs,halt:i.halt});const E=p.join("");(0,l.notBlank)(E)&&g.push(new Error(E)),!r&&(0,o.isNotEmpty)(g)&&C().warn(f+" resulted in errors:",g);const D=i.isIgnorableError??T.isIgnorableError,x=g.filter((e=>!0!==D(e)));if(x.length>0)throw 1===x.length?x[0]:new _.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!n&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:E}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,x.killPid)(a.pid,!0),e}}t.endProcess=A,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,k.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),s=i(41400),n=i(19851),a=i(28874);(0,s.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,n.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},85100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(23560),s=i(28874),n=i(45255);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?s.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},34330:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),w=i(54993),v=i(27395),b=i(25764),S=i(99331),P=i(42638),T=i(38835),_=i(8769),M=i(57159),E=i(66003),D=i(50213),x=i(45643),k=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new M.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,v.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=F,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,x.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+T.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,w.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+T.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),s=i.sibling(r);if(s.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",s.posixPathFrom((0,l.examples)()));const n=(0,d.originalsDir)();if(s.isSelfOrDescendantOf(n))return a.join("$library",s.posixPathFrom(n));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",s.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(6858),a=i(1708),o=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return s(this,r,"f").push(...e),this}async parse(e=a.argv,t){let i=(0,m.addHelpFooter)(new n.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of s(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":o.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,a.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of s(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),s=i(38639),n=i(17181),a=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,s.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),a.Settings.logColor.envValue=e,(0,n.setupLogFormatter)()}))}}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(1708)),n=i(22573),a=i(38639);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},53978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},54772:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),w=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function v(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void w().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void w().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(v)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=v,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return T(v(e))}function y(e){return(0,f.clampRGB)(M(_(e)))}function w(e){return(0,t.LabBitZip)().clampValue(e)}function v(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return w([116*i-16,500*(t-i),200*(i-r)])}function _(e){const[t,i,r]=w(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function M(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=T,t.lab2xyz=_,t.xyz2rgb=M,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function x(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function k(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return F(k(e))}function F(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function A(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function I(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(D,e,(()=>x(e,t))):x(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=k,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(A(e))},t.hsv2hsl=F,t.hsl2hsv=A,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},42079:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(31586),s=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),w=(0,s.sqrt)(g*g+h*h);let v=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);v+=2*(v<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=w-y;let T=y*w==0?0:b-v;T-=2*(T>Math.PI?1:0)*Math.PI,T+=2*(T<-Math.PI?1:0)*Math.PI;const _=2*(0,s.sqrt)(y*w)*Math.sin(T/2),M=(i+c)/2,E=(y+w)/2;let D;y*w==0?D=v+b:(D=(v+b)/2,D-=(Math.abs(v-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const x=(M-50)**2,k=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),C=1+.015*x/(0,s.sqrt)(20+x),F=1+.045*E,A=1+.015*E*k,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*I)*O;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*A),2)+L*P/(a*F)*_/(o*A))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(40958),s=i(31586),n=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},32848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(48884),o=i(31843),l=i(70417),u=i(3048);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},40401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),w=i(85810),v=i(3048),b=i(76490),S=i(1971),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,w.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??v.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,w.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function x(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(T.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...M,seed:e}),s=k(r.centroids,f.length);if(s.lengtht&&x(g-1);const n=s.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,w.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n),2);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),D(a,t);const A=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),I=(0,n.sortBy)(F?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:A,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:A,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,v.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,v.ciede2000_delta_e)(e.centroid,r))}return i};const T=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:v.cie76_delta_e,cie94:v.cie94_delta_e,ciede2000:v.ciede2000_delta_e},M=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function D(e,t){const i=e.countSum,r=e.size;x(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function x(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,w.unlabhash)(r),a=i.find((e=>(0,v.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function k(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,v.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{M.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=x,t.mergeNearCentroids=k},85409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(31586),s=i(68708),n=i(50989);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),w=i(21330),v=i(928),b=i(54261),S=i(73389),P=i(51275),T=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof w.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function M(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof w.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),x(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof w.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void T().warn("datedToDateTime() failed",{d:e,error:t})}}function x(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,v.getMillisecond)(e)))return 0;if((0,c.gt0)((0,v.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,v.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,v.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,v.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,v.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=M(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([k(e,i),k(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??w.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=M,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=x,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),x)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=x(e)),r??(r=x(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,w.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,w.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),s=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),s=i(31586),n=i(54557),a=i(91655),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),s=i(40958),n=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function w(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),w=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(w)??i,rawValue:e,tzoffsetMinutes:w})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??w(e,b(),t)},t.parseExifDateTimeRe=w;const v=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,v,p.monthRE,v,p.dayRE,/[T\s]/,p.hourRE,v,p.minuteRE,v,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),w=i(79842),v=i(66649),b=i(98247),S=i(98725),P=i(928),T=i(54261),_=i(73389),M=i(89724),E=i(17415),D=i(88600),x=i(51275);function k(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,D.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(S.ISO_YMD_RE.exec(e)?.groups??S.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tk(e))).join("-")}toLocal(){return(0,M.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function F(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,T.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,E.zoneToTzOffsetMinutes)((0,v.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(s=>(0,d.map)((0,P.getDay)(e),(n=>(0,d.map)((0,P.getHour)(e),(a=>(0,b.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,h.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${k(n)}:${k(a)}`},t.toExifDateTime=F,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,T.hasTime)(e)||(i??(0,w.datedToPrecisionMs)(e))>=c.dayMs?O(e):F(e,(0,x.getZoneName)(e))?.toISOString({includeOffset:t})};const A="yyyy:MM:dd HH:mm:ss.SSS",I=A+"ZZ";function O(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>k(e))).join(t)}function L(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(v.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,w.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,x.hasZone)(t)?I:A):void 0},t.datedToYMD=O,t.toFuzzyDate=L,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,v.datedToMillis)(e)||null==(0,v.datedToMillis)(t))return;const[s,n]=[e,t].map((e=>(0,v.datedToMillis)(e))).sort(),o=(n-s)/(r+1),l=(0,x.getZoneName)(e),u=l===(0,x.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,T.hasTime)(e)))?L(c):c},t.setZone=function(e,t,i){const r={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,x.hasZone)(e)},s=(0,E.normalizeZone)(t);return null!=e&&null!=s&&(0,T.hasTime)(e)?e instanceof y.DateInterval?e.setZone(s,r):F(e)?.setZone(s,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,w.datedToDateTime)(e);if(null==i)return;const r=(0,x.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),w=i(68852),v=i(4001),b=i(28874),S=i(24689),P=i(79842),T=i(66649),_=i(98247),M=i(21330),E=i(54261),D=i(73389),x=i(16400),k=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,T.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,w.concatRegexp)([/^/,t.yearRE,w.RegExpOptional.from(/-/,t.monthRE,w.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,w.concatRegexp)([/^/,t.yearishRE,w.RegExpOptional.from(/-/,t.monthishRE,w.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function A(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(v.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>A(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const e of n){const t=a(e);if(null!=t&&(0,k.isValidDate)(t))return t}}t.parseDated=I;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;M.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new w.RegExpEscaped("(?"+(0,x.monthNames)().map(w.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,w.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return M.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,x.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),s=i(31586),n=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),s=i(31586),n=i(68708);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),s=i(19851),n=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,s.lazy)((()=>w(l.Settings.datesBeforeAreEstimated.valueOrDefault)??w(l.Settings.datesBeforeAreEstimated.defaultValue)));function w(e){return(0,a.map)((0,c.isoToDated)(e),v)}function v(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function T(e,t){return _(Date.now()-e,t)}function _(e,t){return v(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},42499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(51168),s=i(19851),n=i(19043),a=i(28874);t.setupLuxon=(0,s.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,n.locale)()}))},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=T,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:T(i)};const _=/\b(?Z|UTC|GMT)\b/,M=/(?[-±+−])/,E=/[-−]/,D=/(?[01]\d)/,x=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return b(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return w(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),M,D,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const A=/\b(?(?:Etc\/)?GMT)\b/,I=(0,n.lazy)((()=>(0,m.concatRegexp)([A,M,x,m.RegExpOptional.from(k)])));function O(e){return F(I().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return T(i);if(null!=t){const i=S(e);if(null!=i)return T(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),w=(0,s.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),v=(0,s.lazy)((()=>(0,n.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),b=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,p.datedToISO)(e)))))),S=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,y.datedToLocal)(e)))))),P=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,m.datedToMillis)(e))))));function T(e){if(null==e)return!1;const t=M(e);return w().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return T(e)?e:void 0},t.isValidDate=T;const _=String(new Date("bad"));function M(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===_)return _;const t=(0,n.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,E())&&s.push("year is in the future"),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):S().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):b().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(t)).join("; "))}catch(t){return w().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=M;const E=(0,s.lazy)((()=>r.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return T(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==M({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),s=i(31586),n=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},82261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},92407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(19851),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},55332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(19851),s=i(50213),n=i(76187),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},91872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i,r){const a=Date.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}))}},12943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(79842),s=i(66649),n=i(40958),a=i(68708);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},65753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(19851),s=i(7282),n=i(28874);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*((0,s.isTest)()?.25:5))))},80632:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(54993),u=i(50213),c=i(23560),d=i(65211),h=i(29882),f=i(53265),m=i(66430),p=i(66184),g=i(28874),y=i(15674),w=i(87550);function v(){const e=g.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,a.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=g.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=g.Settings.logSql.valueOrDefault}){e=(0,f.resolve)(e),(0,h.mkdirpSync_)((0,r.dirname)(e));const b=(0,h.posixPathFromGrandparent)(e),S=(0,m.nativePathSizeSync)(e),P=(0,u.mkLogger)("db.mkdb("+b+")");if(null!=S){const E=Math.round(S/o.MiB),D=Math.ceil(1.5*E);D>g.Settings.dbCacheSizeMb.valueOrDefault&&(P.info("Dynamically setting dbCacheSize to "+g.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:E}),g.Settings.dbCacheSizeMb.envValue=D);const x=Math.round(1.5*E);x>g.Settings.maxMemoryMb.valueOrDefault&&(P.warn("Large database: setting maxMemoryDb to "+x+"MB",{dbFileSizeMb:E,"Settings.maxMemoryMb":g.Settings.maxMemoryMb.valueOrDefault}),g.Settings.maxMemoryMb.envValue=x)}P.info("Opening "+e+"...");const T={fileMustExist:!1,readonly:!1};if((0,a.gt0)(t)&&(T.timeout=Math.ceil(t)),i){const k=(0,u.mkLogger)("SQLite("+b+")"),C=(0,p.defaultLogLevel)();function F(e,...t){var i;(0,n.blank)(e)||k.log(C,(i=e,(0,l.toS)(i).replace(/\s{2,}/g," ")),{args:t})}T.verbose=F}const _=new w(e,T);P.info("Open. Setting PRAGMAs...");for(const A of(0,s.compact)(['encoding = "UTF-8"',"threads = "+(0,y.maxCpus)(),"foreign_keys = ON","page_size = "+v(),"trusted_schema = 0","cache_size = -"+Math.round(g.Settings.dbCacheSizeMb.valueOrDefault*o.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL",(0,a.gt0)(g.Settings.dbBusyTimeoutMs.valueOrDefault)?"busy_timeout = "+g.Settings.dbBusyTimeoutMs.valueOrDefault:null,"temp_store = MEMORY","synchronous = "+g.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,c.isDbJanitorService)()?(0,l.toS)(g.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+g.Settings.dbAutoVacuumMode.valueOrDefault]))P.tapThunk({msg:"PRAGMA "+A,result:()=>_.pragma(A)});const M=_;return M.__uid=(0,d.uid)(),M},t.pageSizeBytes=v},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},95704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(40958),s=i(31586),n=i(59455),a=i(65753),o=i(51040);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},76187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(17217),s=i(87391),n=i(7311);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},51040:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+$/gm,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(19851),s=i(50357),n=i(30976),a=i(50213),o=i(95696),l=i(80632),u=i(76187),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},87391:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),w=i(70698),v=i(64680),b=i(29882),S=i(45969),P=i(43334),T=i(28874),_=i(41692),M=i(32774),E=i(80612),D=i(32551),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+x()),preexistingDir:i});return e}}function C(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:M.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,D.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,D.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,D.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:C(),desc:"cache"})));const F=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),T.Settings.cacheDir.watchLater(A)}));function A(){T.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{F();const e=T.Settings.cacheDir.valueOrDefault;try{return(0,b.mkdirpSync_)(e),(0,w.writeCachedirTag_)(e).then((()=>(0,v.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=A},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),s=i(45969),n=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),s=i(45969),n=i(32774);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),s=i(96706),n=i(29882);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),s=i(49776),n=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),s=i(54993),n=i(29882),a=i(28874);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),s=i(55835),n=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function w(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function v(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(v(e),!1)}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function T(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(T(e))}async function M(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await w(t);return(0,r.uniq)([t,i,await b(t),await P(t),await _(t),await M(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=w,t.libraryOriginalsDirPosixFile=v,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=T,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=M},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),w=i(80612),v=i(32551);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,v.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,v.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,w.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,v.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),s=i(7282),n=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),s=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),w=i(59958),v=i(6012),b=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(w.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,n.join)((0,m.homeDir)(),".psenv"));const t=(0,b.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,d.debom)(s.default.readFileSync((0,g.resolve)(r))),n=(0,v.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(n))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),s=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(1708)),n=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),s=i(19851),n=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),w=i(70025),v=i(57159);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,w.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,w.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function T(e,t){return e instanceof v.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(T(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=T,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),T(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),s=i(26905),n=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},68301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(19851),s=i(42659),n=i(75240),a=i(55835),o=i(31586),l=i(68708),u=i(59455),c=i(54993),d=i(50213),h=i(45255),f=i(37628),m=i(99331),p=i(46292),g=i(38835),y=i(32144),w=i(29882),v=i(95696),b=i(55222),S=i(28874),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function T(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*s.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=s.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,w.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),s=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=s,meta:{event:T(e),recentEventCount:r,maxErrorsPerDay:s,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:T(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:T(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new _(v.PosixFile.for(e).join("events"))))))},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),s=i(38639),n=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function w(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function v(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function b(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function S(e){return!!((0,s.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||b(e))||void 0}t.isSqliteBusyError=w,t.isSqliteDisconnectedError=v,t.isSqliteConstraintError=b,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===S(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||w(e)||v(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=S;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),s=i(31586),n=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),s.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(n(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),s=i(19851),n=i(15197);t.ee=(0,s.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new n.CapturingEventEmitter(e)}))},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(73024)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(76760)),n=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),s=i(76760);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),w=f(i(1708)),v=i(46466),b=f(i(57975)),S=f(i(38522)),P=i(19851),T=i(40958),_=i(5233),M=i(22573),E=i(42659),D=i(50357),x=i(96249),k=i(98553),C=i(55835),F=i(31586),A=i(68708),I=i(97790),O=i(39926),L=i(51926),R=i(59455),N=i(54993),B=i(48884),j=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),q=i(76850),H=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Z=i(43334),Y=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),se=i(89968),ne=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),we=i(27794),ve=i(73428),be=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const Se=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,T.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,M.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const s=(0,fe.resolve)(i),n=new Pe(s,t);return Se().set(i,n),Se().set(s,n),n}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,T.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,T.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,T.isNotEmpty)(e)?(0,T.includesAll)(t,e):(0,T.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,T.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,T.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,T.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,T.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,q.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,be.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,ve.writeFileSync_)(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,A.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,we.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,we.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,T.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,F.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),Te)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,n=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,v.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*E.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let Te=!0;t.useFsWatch=function(e){Te=e},t.execDir=function(){return Pe.for(w.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),s=i(88840),n=i(14036),a=i(29882);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,n.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),w=i(14427),v=i(17217),b=i(16287),S=i(68284);class P{constructor(e,t){this.base=e,(0,w.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const T=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,v.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void T().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void T().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void T().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),w=i(54557),v=i(50213),b=i(88158),S=i(56519),P=i(46292),T=i(32551),_=i(35280),M=i(87290),E=i(96706),D=i(57902),x=i(43334),k=i(78984),C=i(33995),F=i(28874),A=i(21144),I=i(83278),O=i(48313),L=i(85772),R=i(78133),N=i(46356),B=i(17217),j=(0,u.lazy)((()=>(0,v.mkLogger)("fs.ExcludeGlobs"))),z=new w.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((x.isWin?"*":"")+"/"+t.s+"/",t.desc));if(x.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}x.isLinux&&e.push(new U(`${(0,T.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Z=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ne,whyNoMedia:L.whyNoMedia,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ne}])),t.excludeGlobs=(0,u.lazy)((()=>{Z();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Y=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return F.Settings.disableAllFilters.valueOrDefault?void 0:k.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ne(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,M.libraryDirPosixFile)(),(0,M.libraryOriginalsDirPosixFile)(),...F.Settings.argvScanPaths.values,...F.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,A.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ne},88561:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class w extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=w,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,n.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),s=i(17217),n=i(16287),a=i(68284);async function o(e){return(0,r.pick)(await(0,n.stat_)((0,s.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,s.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),s=i(19851),n=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,s.set(this,[]),n.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,n,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,s,"f").push(e)}close(){u(this,n,"f").close()}}t.FileWatcher=m,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,s,"f"))t(e,this.nativePath)}}},73209:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const T=i(58587),_=P(i(44652)),M=i(87997),E=i(40958),D=i(17586),x=i(42659),k=i(50357),C=i(75240),F=i(55835),A=i(31586),I=i(30976),O=i(13538),L=i(54993),R=i(7282),N=i(68852),B=i(23560),j=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),q=i(55222),H=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,s,Math.max(Date.now(),b(this,s,"f",n)+1),"f",n),(0,E.compactBlanks)([q.TokenRadix.encode(b(this,s,"f",n)),B.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,A.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return b(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>b(this,r,"m",v).call(this)),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=s,s,(i=b(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(b(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await b(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+b(this,l,"f")),this.staleMs=(0,A.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),b(s,s,"f",o).push(this)}get acquired(){return b(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await b(this,r,"m",f).call(this,e)??b(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,D.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==b(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:x.secondMs);S(this,c,setInterval((()=>b(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=b(this,c,"f")&&(clearInterval(b(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(b(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),S(this,u,!1,"f"),(0,F.map)(b(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?b(this,r,"m",w).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>b(this,r,"m",w).call(this)),(0,A.toGt0)(this.staleMs)??x.secondMs),"f"),b(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(b(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,A.gt0)(this.staleMs)&&Date.now()>b(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await b(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await b(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,A.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+x.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,A.gt0)(t)&&!(0,T.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),b(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await b(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},w=async function(){await b(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},v=function(){(0,E.filterInPlace)(b(s,s,"f",o),(e=>b(e,l,"f")!==b(this,l,"f")))},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),s=i(51926),n=i(54993),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(73024)),n=i(57075),a=i(46466),o=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44652)),n=r(i(73024)),a=i(46466),o=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),w=i(16287),v=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return v().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;v().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await T(n.default.createReadStream(i)),stats:(0,u.pick)(await(0,w.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function T(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=T,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),s=i(42659),n=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),s=i(54993),n=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,n.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,n.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,n.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,n.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(51926),n=i(54993);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(76760)),n=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},61704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(21144),s=i(17217);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=n(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),w=i(83278),v=i(70698),b=i(88561),S=i(65238),P=i(16287),T=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),_="NoMedia",M=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+_+"$","im"),E=Object.freeze(["."+_,_]),D=Object.freeze((0,u.flatten)(E.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function x(e){return null!=M.exec(e)}t.isNoMediaName=x;const k=(0,o.lazy)((()=>new b.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=w.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return x(i.base)||await(0,v.isCachedirTagFile)(i)?k().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await k().getOrSetAsync(i.nativePath,(()=>F(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function F(e){if(x(e.base))return k().set(e.parent().nativePath,e.nativePath),T().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,S.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([A(e.nativePath,i),(0,S.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,v.isCachedirTagDirectory)(e)?T().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(v.CACHEDIR_TAG).nativePath)}):null}async function A(e,t){for(const i of g.isCaseSensitiveFs?D:E){if(!0===t?.aborted)return null;const r=a.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return T().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(x(r.basename))return T().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,r.basename))});if(r.basename===v.CACHEDIR_TAG){const t=(0,a.join)(e,r.basename);if(await(0,v.isCachedirTagFile)(t))return T().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=F,t._dirHasNoMediaChild=A},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),w=i(78133),v=i(53265),b=i(17217),S=i(16287),P=i(66430),T=i(5545);function _(e){return((0,b.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return C(e).some(_)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,b.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,w.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return n.default.dirname((0,b.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=M.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function D(e){const t=n.default.parse((0,b.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,n.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,b.toNativePath_)(e.ancestor),i=(0,b.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(y.isLinux?r===s:(0,p.equalsIgnoreCase)(r,s))}function C(e){return(0,b.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function F(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function A({p:e,maxLength:t}){const i=(0,b.toNativePath_)(e);if(i.length<=t)return i;const r=C(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),O([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),O([...s,...n])}function I(e){return e.startsWith("\\\\")}function O(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),y.isWin?"":n.default.sep)}t.parseNativePath=E,t.parentBasename=D,t.grandParentBasename=function(e){return D(n.default.parse((0,b.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return k(b.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(b.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(b.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=F,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,b.toNativePath_)(e),r=(0,b.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,w.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,w.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=A,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(A({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(T.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;if(F(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await s.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,b.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,b.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),w=i(64660),v=i(21144),b=i(16287),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function T(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,w.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=T,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...M(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await T(i))return y.isLinux?i:(0,v.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,w.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),w=i(76790),v=i(5233),b=i(22573),S=i(42659),P=i(26905),T=i(75240),_=i(55835),M=i(31586),E=i(68708),D=i(13538),x=i(89937),k=i(12168),C=i(54993),F=i(48884),A=i(50213),I=i(45255),O=i(81168),L=i(56519),R=i(56038),N=i(31562),B=i(84777),j=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),q=i(43334),H=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Z=i(34238),Y=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),se=i(73209),ne=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,w.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,A.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),r=new fe(i,t);return(0,O.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===x.PS_LIBRARY_SCHEME?1:t.scheme===x.PS_LOCAL_FILE_SCHEME?2:t.scheme===x.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,v.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,M.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,D.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,T.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,M.clamp)(I.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*k.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,M.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*k.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),w=i(83278),v=i(19748),b=i(92423),S=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function T(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):null}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function M(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function x(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function k(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function C(e){return(0,w.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function A(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function I(e){return[{isSupportedFileExtension:v.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:A}]}function O(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:k},{notDimensionsTooSmall:T},{notVideoTooShort:_},{notVideoTooLong:M},{notRejectedRating:D},{notExcludedKeyword:x}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=T,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=A,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(76760)),n=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(s.default.join((0,p.execDir)(),"resources"),s.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=s.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),s=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),s=i(84542);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(51455)),n=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),w=i(28874),v=i(63870),b=i(88561),S=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(w.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function T(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=T;const _=(0,a.lazy)((()=>new b.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function E(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=D(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(w.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(s===f.Timeout&&(0,g.onTimeout)({soft:!1}),s!==f.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{w.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),T()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?T():M(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(w.Settings.readdirCacheMs.valueOrDefault)?E(e):D(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=D},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const s=i(73024),n=r(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=n.default.resolve(t,...e);if((0,s.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??n.default.resolve(...e))},t.execDir=(0,l.defer)((()=>n.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(22454),s=i(28874),n=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),s=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const s=r(i(73024)),n=r(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,g.statTimeoutMs)(),!0)}function v(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function S(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(S(r),S(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}t.stat_=w,t.statMaybe=v,t.statToType=b,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await v(e,t)},t.isEmptyFile=async function(e,t){const i=await v(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await v(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await v(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await v(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await v(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await v(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await v(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),s=i(56409);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(57075)),n=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),w=i(19851),v=i(40958),b=i(22573),S=i(42659),P=i(98553),T=i(31586),_=i(68708),M=i(50989),E=i(51926),D=i(85556),x=i(54993),k=i(89788),C=i(23467),F=i(7282),A=i(23560),I=i(77377),O=i(71567),L=i(73568),R=i(25764),N=i(38836),B=i(99331),j=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),q=i(5012),H=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Z=i(84542),Y=i(73428);t.AssetFileSyncStates=(0,M.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,M.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,M.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,M.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const X={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,_.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,M.strEnum)(...(0,_.keys)(new class{constructor(e,t,i,r,s,n,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,w.lazy)((()=>(0,Y.writeTextfile_)(re().nativePath,(0,E.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(X)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=S.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,H.isCsvExt)(e)&&(0,T.gte)(e.mtimeMs(),t)))},t.syncReport=(0,w.lazy)((()=>new se));class se extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new k.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,s,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,b.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,q.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,x.toS)(e.path),state:e.state,details:(0,x.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:t,at:new Date(t).toISOString(),...i,...(0,_.pick)(e,"from","elapsedMs","url")};(0,_.isEmptyObj)(e.meta)||(s.meta=(0,P.stringify)(e.meta)),(0,F.isTest)()&&process.stdout.write((0,P.stringify)(e)+Z.Newline),f(this,r,"m",u).call(this,s)}}maybeSystemData(e){(0,A.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:n}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,B.ending)()||r instanceof L.AbortError?t.SyncFileStates.canceled:r instanceof D.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return f(this,n,"f")??f(this,r,"m",h).call(this)}async flushClose(){return f(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,n,"f");return m(this,n,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,s,"f")}}t.SyncReport=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,r,"m",c).call(this,i):(f(this,r,"m",c).call(this,{...i,details:(0,v.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Z.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,s,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,j.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,s,"f").nativePath),this.logger.info("Opening new report: "+f(this,s,"f")),(0,F.isTest)()&&(0,O.stdoutWrite)({syncReport:f(this,s,"f").nativePath},!1),m(this,n,(0,g.createWriteStream)(f(this,s,"f").nativePath),"f"),f(this,n,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Z.Newline),f(this,n,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(48161)),n=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44652)),n=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},79847:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkFileUri=t.trashOrUnlinkFileUris_=void 0;const o=n(i(51455)),l=a(i(49378)),u=i(40958),c=i(22573),d=i(13538),h=i(83104),f=i(45255),m=i(31562),p=i(98314),g=i(34102),y=i(28874),w=i(45200),v=i(63870),b=i(16287),S=i(74128),P=i(84258),T="fs.Trash";async function _(e){const t=Date.now(),i=(0,v.commandTimeoutMs)(),r=(0,c.toNotBlank)(e.nativePath)??await(0,d.thenOrTimeout)((0,w.uri2nativePath)(e.uri,e.mountpoint),i);if((0,c.blank)(r)||r===h.Timeout)return(0,S.syncReport)().onProgress({from:T,state:"failed",details:"Could not convert URI to native path",path:e.uri,elapsedMs:Date.now()-t}),{uri:e.uri,unlinked:!1};const s=await(0,b.statMaybe)(r);if(null==s)return(0,S.syncReport)().onProgress({from:T,state:"noop",details:"Failed to delete: no such file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(!s.isFile())return(0,S.syncReport)().onProgress({from:T,state:"noop",details:"Failed to delete: not a file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(y.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,d.thenOrTimeoutError)((0,l.default)(r,{glob:!1}),i),await function(e){return(0,m.untilTrue)((async()=>null==await(0,b.statMaybe)(e)),{timeoutMs:f.ShortCommandTimeoutMs})}(r))return(0,S.syncReport)().onProgress({from:T,state:"deleted",details:"Moved file to trash",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0};(0,P.logger)().warn("soft-delete("+r+") didn't seem to work: the file is still there?")}catch(e){(0,S.syncReport)().onProgress({from:T,state:"note",details:"Failed to soft-delete file to trash: "+(0,p.errorToS)(e),path:r,elapsedMs:Date.now()-t}),(0,P.logger)().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}try{return await(0,d.thenOrTimeoutError)(o.unlink(r),i),(0,g.ee)().emit("fileChanged",r),(0,P.logger)().info("unlink("+r+") successful"),(0,S.syncReport)().onProgress({from:T,state:"deleted",details:"Permanently deleted file",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0}}catch(i){return(0,S.syncReport)().onProgress({from:T,state:"failed",details:"Could not move file to trash or delete: "+(0,p.errorToS)(i),path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!1}}}t.trashOrUnlinkFileUris_=async function(e){const t=[];for(const{uri:i,mountpoint:r}of(0,u.uniqBy)(e,(e=>e.uri)))try{t.push(await _({uri:i,mountpoint:r}))}catch(e){t.push({uri:i,unlinked:!1,error:e})}return t},t.trashOrUnlinkFileUri=_},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),s=i(41400),n=i(55835),a=i(92782),o=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),h=i(87128),f=i(95696);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=n(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await a.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(76760)),n=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),w=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function v(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function T(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=v,t.zcat=async function(e,t){try{return v(e,t)}catch(t){return void w().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void w().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=T,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await T(e,t)}catch(t){w().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},87408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(63870),s=i(18454),n=i(89035),a=i(82638);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...s.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:s.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},18454:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b,S,P,T=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},_=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const M=i(19851),E=i(40958),D=i(76790),x=i(22573),k=i(41400),C=i(50357),F=i(26905),A=i(50268),I=i(55835),O=i(68708),L=i(30976),R=i(51926),N=i(13538),B=i(42279),j=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),q=i(50213),H=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Z=i(77740),Y=i(98314),X=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),se=i(21525),ne=i(82638),ae=(0,M.lazy)((()=>(0,q.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{T(this,s,"f",l).push(e+": failed: "+(0,Y.errorToS)(t)),this.onResultChange()})),T(this,s,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return T(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){T(this,s,"f",l).push((0,R.isString)(e)?e:(0,Y.errorToS)(e)),this.onResultChange()}static lastErrors(){return T(this,s,"f",l).toA()}static addLoadingMsg(e){T(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,E.compact)((0,j.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:T(this,s,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[T(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=T(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>T(this,s,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return T(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,A.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=T(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=s.summary();if(e.pendingCount>0){const t=await Promise.all(s.testResultsCritical());e=s.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){s.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,F.shortStack)());else{this.onResultChange(),T(this,s,"f",l).clear(),T(this,s,"f",d).clear(),T(this,s,"f",h).clear(),T(this,s,"f",c).clear(),this.summary.clear(),_(this,s,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new s(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return T(this,s,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,n,o,l,u,c,d,h,f,m,S,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=n,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=S,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),v.set(this,(0,M.lazy)((async()=>{await T(this,p,"f").prior(),(0,C.eql)(T(this,g,"f"),T(this,r,"m",w).call(this))||(this.onReset?.(),await this.refresh(),T(this,v,"f").unset())}))),this.refresh=(0,M.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await T(this,p,"f").prior();const e=T(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,q.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[A.HealthCheckSections.ordinal(this.section),l??999,this.id],_(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>T(s,s,"f",a).enqueue({name:this.id,l:()=>T(this,r,"m",b).call(this,o)}),ttlMs:S}),"f"),this.isCritical&&T(this,p,"f").watchLater({onChange:s.onCriticalResult,onError:s.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>T(this,v,"f").call(this)))}isStale(){return T(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return T(this,p,"f").settledCount()}reset(){return T(this,p,"f").unset(),this.onReset?.(),_(this,g,{starting:!0},"f"),this}setTTL(e){T(this,p,"f").setTTL(e)}result(){return T(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return T(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return T(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??T(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,E.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,E.isNotEmpty)(i)&&(r.links=(0,E.uniqBy)(i)),(0,E.isNotEmpty)(t)&&(r.buttons=(0,E.uniqBy)(t)),r}t.HealthCheck=oe,s=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,v=new WeakMap,r=new WeakSet,o=function(){return(0,E.filterInPlace)(T(this,s,"f",n),(e=>!e.isPending)),T(this,s,"f",n)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,ne.summarizeHealthChecksSync)({errors:T(this,s,"f",l),skipPending:T(this,s,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&_(this,s,!0,"f",u),i.state!==T(this,s,"f",c).last?.state&&T(this,s,"f",c).push({state:i.state,ts:Date.now()}),i},w=function(){return(0,O.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},b=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,F.shortStack)()}),_(this,g,T(this,r,"m",w).call(this),"f");try{if((0,Z.getDevEnvFlag)("PS_SLOMO")&&await(0,k.delay)((0,L.randomInt)(.3*i,.7*i)),this.isSkipped())return T(this,r,"m",S).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const s=await(0,N.thenOrTimeoutError)(e(),i);return T(this,r,"m",S).call(this,{test:s,elapsedMs:Date.now()-t})}catch(e){return T(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},S=function({test:e,src:t="#toResult",elapsedMs:i}){var r,n;const a=s.normalizeMsg(e.msg),o=e.level??((0,z.toS)(a).toLowerCase().includes("error")?"error":(0,z.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,E.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(_(this,y,(n=T(this,y,"f"),r=n++,n),"f"),r),(0,$.ending)()?u:this.logger.tap({level:se.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const s=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,x.toNotBlank)((0,Y.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,X.isFatalError)(e)&&s.toLowerCase().includes("warn")?"warn":"error"),T(this,r,"m",S).call(this,{test:{msg:s,level:t},src:"#toErrorResult",elapsedMs:i})},n={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new U.CountingSet},f={value:[]},oe.all=(0,M.lazy)((()=>Object.freeze((0,D.sortBy)(T(s,s,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,H.debounce)((()=>{ae().info("onCriticalResult()",s.summary.refresh())}),250),oe.summary=(0,M.lazy)((()=>T(s,s,"m",m).call(s))),oe.resetDebounced=(0,H.debounce)((()=>s.reset()),50)},85021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function w({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await w(e)})};const v=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...v(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...v(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...v(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>v.unset()))})),t.summarizeHealthChecksSync=b},95242:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),w=i(57159),v=i(83278),b=i(95696),S=i(62105),P=i(84258),T=i(38156),_=i(69589),M=i(28874),E=i(47783),D=i(29990),x=i(16047),k=i(42725),C=i(4192),F=i(32876),A=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class O{constructor(e,t,i){r.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,_.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(r=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,S.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await n(this,r,"m",s).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:n,height:a,sha:l,mimetype:u}=t;if(null==s||null==n||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,D.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:n,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(k.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,D.equivalentFitSizes)(r,s)){const n=(0,D.fitSizes)(e,e.mimetype),a=(0,o.diff)(r,s);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=n.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:n});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=O,s=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new T.PushProgressObserver({path:e.nativePath,op:"Building previews"},k.ImageSize.sq().length+k.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:k.ImageSize.largestFit().max});if(null==a)throw new w.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,x.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,v.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,D.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=k.ImageSize.largestSq(),b=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,h.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of l){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&r.reducer===F.Fit&&M.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of k.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=M.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(r)+" -> "+(0,u.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,C.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new w.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),w=i(70417),v=i(35721);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,v.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,v.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,w.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,v.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},33106:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(9288)),n=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(40958),s=i(33374),n=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),w=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function v(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){w().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void w().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=v(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void w().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=v,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void w().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),s=i(54993),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),s=i(19851),n=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),w=i(55222),v=i(63870),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+w.TokenRadix.randomChars(2),w.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,v.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(9288)),n=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),w=i(88561),v=i(95696),b=i(17217),S=i(50213),P=i(23624),T=i(28874),_=i(12089),M=i(16170),E=i(1078),D=i(33106),x=i(86580),k=i(78011),C=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const A=(0,n.lazy)((()=>new w.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=v.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,x.fitToResolution)(i.dimensions,Math.round(T.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,x.fitToResolution)(i.dimensions,T.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,M.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),w=await(p?k.meanDiffHash:k.meanDiffHashCIELAB)(y()),v=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(w.meanHash),diffHash:(0,P.b64encodeBits)(w.diffHash),dctHash:(0,P.b64encodeBits)(v),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,M.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:A,impl:I}),t._imageHash_=I,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},80361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(33374),l=i(57924),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(21605),m=i(48884),p=i(50213),g=i(97352),y=i(85810),w=i(3048),v=i(32848),b=i(82647),S=i(38812),P=i(70417),T=i(23624),_=i(28874),M=i(86580),E=i(48368),D=i(2090),x=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,w.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,w.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const k=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(k))}function F(e,t,i=E.HashDim){const r=(0,T.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function A({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=F(e,i,r),l=F(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));x().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function I(e,t,i="debug",r={}){return x().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=A({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,M.validRotations)(r,s)}),m=A({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=A({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,v.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void x().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,w=(0,M.aspectRatio)(r),S=(0,M.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=w&&null!=S&&!(0,o.isCloseAspectRatio)(w,S);let T=0,k=0;n&&(k+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,T+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(k+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,T+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(T+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,k+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const F=R((T+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),I=R((k+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,D.fmtAspectRatio)(w)} vs ${(0,D.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,F)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,F)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=I,z=j&&N.avg>=F;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:F,imageCoeffDelta:T,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:I,colorCoeffDelta:k,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:w,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return x().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(k))?(0,h.padding)("0",2*i*i):"",s=F(e,t,i);return f.Rotations.map((e=>(0,T.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=A,t.isSimilarImage=I,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return I(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},42725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},4192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},78011:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(9288)),n=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},48604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),s=i(31586),n=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(9288)),n=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,n.lazy)((()=>{s.default.simd(l.Settings.enableSIMD.valueOrDefault),s.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),s.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(77988),n=r(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),w=i(56519),v=i(56038),b=i(57159),S=i(95696),P=i(17217),T=i(28874),_=i(47783),M=i(16170),E=i(95141),D=i(54979),x=i(1078),k=i(63870),C=i(86580),F=i(277),A=i(16047),I=i(13940),O=i(5733),L=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await z(e,t))?.nativePath}async function j(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,k.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=j,t.toSharp=function(e){const t=e;if((0,O.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:T.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,v.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=N().addParameterContext(e.nativePath);(0,O.setupSharp)();const n=await(0,D.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,x.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,M.isVideoMimeType)(n),S=(0,M.isLibrawMimeType)(n),P=a.dimensions,k=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==k?.width||null==k?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:k,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const I=(0,C.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),z=(0,M.isSharpMimeType)(n)&&null==t,V=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||z||V)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:z,isMirrorOrientation:V});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...T.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...T.Settings.embeddedThumbnails.values);const a=k.width*k.height*.2,u=k.width*k.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>j(e,n,t,k,I)))}}}(0,M.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,F.isHeifSupported)()&&f("heif",(()=>(0,w.thenMap)((0,F.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,w.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,L.isVideoSupported)())try{return await(0,w.thenMap)((0,L.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,v.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=z},181:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(9288)),n=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),w=i(54979),v=i(63870),b=i(5733),S=i(50961),P=i(66106),T=i(51210),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&_().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const M=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,v.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return M().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:M,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,w.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,T.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),w=i(56038),v=i(31562),b=i(98314),S=i(34102),P=i(88561),T=i(95696),_=i(17217),M=i(74128),E=i(31843),D=i(70417),x=i(33847),k=i(28874),C=i(94678),F=i(43207),A=i(47783),I=i(16170),O=i(95141),L=i(1078),R=i(63870),N=i(89782),B=i(13940),j=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,j.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,E.lerp2d)(e,{x:76800,y:k.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:k.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function q(e){return await(0,t.isVideoSupported)()?T.PosixFile.for(await(0,t._extractVideoFrame_)((0,_.toNativePath_)(e))):void 0}async function H(e,t){const i=V("extractVideoFrame",e),r=T.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,j.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,B.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,A.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,N.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,F.extractDurationSec)(l),m=Math.min(f??0,k.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,j.ffmpegFrame_)(t),!1===await(0,v.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,A.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function G(){return k.Settings.transcodeVideos.valueOrDefault&&await(0,j.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,A.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,F.extractDurationSec)(i);if(!(0,c.gt)(n,k.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=q,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await G())return;const n=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,A.readTags)(e),h=(0,L.extractSizeInfoFromTags)(d),m=(0,F.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,A.readRawTags)(t),r=await(0,A.readRawTags)(e),s=(0,F.extractDurationSec)(r),n=(0,F.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),s=k.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,C.extractBitrateKbps)(i)??k.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,w.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new x.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:r.halt,...g},m=k.Settings.transcodeMaxDim.valueOrDefault,p=(0,D.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,j.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,M.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-n})}catch(t){throw(0,M.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:Date.now()-n}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await q(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,j.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),w=i(84258),v=i(28874),b=i(76280),S=i(63870),P=i(19769),T=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function _(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:v.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=_;const M=/ffmpeg version n?(?\S+)/i,E=(0,u.lazy)((async()=>{const e=await _();if(null==e)return void T().info("failed to find ffmpeg in $PATH",{ffmpegPath:v.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=M.exec(t.result)?.[1];return T().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function D(){E.unset(),t.ffmpegVersionDescription.unset()}function x(e){const t=e?.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function k(e){const t=[...v.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(v.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=v.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(E(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",D),(0,g.ee)().on("clearToolCache",D)})),t.ffmpegVersion_=async function(){return await E.prior()??E.refresh()},t.isFFmpegSupported=async function(){return null!=await E()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=k,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...k(t),...F(t),...x(t),"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){T().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return T().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return T().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await _(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(19851),s=i(42659),n=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),w=i(89782),v=i(13940),b=i(42725),S=i(19769),P=(0,r.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,v.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>D(e,t)})};const T=["-T"],_=["-Z","-"],M=["-o","1"],E=["-t","0","-j"];async function D(e,t){const i=await(0,w.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=b.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[...T,..._,...M,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],v={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:v});const D=(0,c.execFile)(g,y,void 0,v),x=[];function k(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});x.push(r)}}if(D.on("error",k),D.stderr.on("data",k),await t.writeStream_(D.stdout),(0,s.isNotEmpty)(x))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:x,path:e.nativePath});(0,c.endProcess)(D)}t.dcraw_emu_=D},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},42042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(22573),s=i(28874),n=i(81674);t.getEmail=async function(){const e=s.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),w=i(50213),v=i(56519),b=i(76596),S=i(46292),P=i(87290),T=i(77740),_=i(34102),M=i(83278),E=i(28874),D=i(37692),x=i(71706),k=i(83950),C=i(72042),F=i(33603),A=i(48132);t.k=(0,y.rolazy)((()=>(0,x.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,w.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,C.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,T.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function L(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:k.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,F.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,v.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await L((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,A.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function B(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=L,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await L(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof k.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,T.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,F.sids)({timeoutMs:A.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),(e=>M.BaseFile.for(e))),s=(n=(0,l.flatten)((await(0,v.someOrTimeout)([()=>function(e){return L(E.Settings[(0,t.k)().L].value,"Settings",A.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:A.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,f.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l))),(e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,o.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset())),D.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=B,t.l=async function(){try{return await B()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await B()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},84194:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(40958),a=i(76790),o=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),h=i(19851),f=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function w(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=w,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(w(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const v=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||v.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=w(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==w(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(45599),o=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),h=i(50213),f=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),w=i(45879),v=i(70854),b=i(57902),S=i(72308),P=i(43334),T=i(24399),_=i(7014),M=i(30933),E=i(71706),D=i(84194);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const x=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function k(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=k;const C=(0,a.defer)((()=>(0,m.thenMap)(k(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),F=/o\.e\.m\./i;async function A(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,w.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(F)))}async function I(){return P.isLinux?(await A("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function O(){return P.isLinux?(await A("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await A("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void x().warn((0,t.k)().i+" failed",e)}}async function N(){return(await T.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,M.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,r.compactBlanks)(await A("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,v.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,v.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,I,O,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return x().tap({msg:"sids()",result:(0,D.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,f.isTest)())for(const t of e)H.add(t)},t.clearSids=function(){(0,f.isTest)()&&H.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},34474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(40958),s=i(42659),n=i(41400),a=i(96249),o=i(68708),l=i(34666),u=i(20214),c=i(71371),d=i(50213),h=i(42638),f=i(31562),m=i(98314),p=i(89968),g=i(28874),y=i(4904),w=i(57902),v=i(89241),b=i(83954);function S(e=10*s.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(w.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-s.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new v.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*s.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-s.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),s=i(23560),n=i(66184),a=i(72210);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),s=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function w(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...w(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),w=i(31256),v=i(28538),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new w.GelfLogFormatter,this.logFilter=new v.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),s=i(42659),n=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),s=i(31586),n=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),s=i(57902);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,s.set(this,[]),n.set(this,(0,l.lazy)((()=>{o(this,s,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,s,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,n,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,r,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,r,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){if(null==e||0===o(this,s,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,s,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),s=i(50989),n=i(28874);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=n.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},89241:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),h=i(38522),f=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),w=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),s.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,s,!0,"f")})),this.stream.on("end",(()=>{u(this,s,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,s,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,s,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,s,!0,"f");else{const t=(0,w.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),s=i(76760),n=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),w=i(22277),v=i(25764),b=i(38836),S=i(99331),P=i(42638),T=i(76596),_=i(98314),M=i(89968),E=i(29882),D=i(28874),x=i(28981),k=i(20839),C=i(21727),F=i(66184),A=i(57902),I=i(72210),O=i(98192);function L(e){const t=(0,x.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),v.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new w.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await M.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(A.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,_.errorToS)(t))))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,T.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,_.errorToS)(e))))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await M.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),s=i(82328),n=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),w=i(31586),v=i(409),b=i(23560),S=i(81168),P=i(78406),T=i(25764),_=i(20197),M=i(14977),E=i(36868),D=i(28874),x=i(32105),k=i(20839),C=i(21727),F=i(66184),A=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:T.EndableRanks.logger,unref:!0,onEnd:()=>c(this,s,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:x.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:b.processName,logFilter:F.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,v.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,A.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,w.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,M.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),s=i(84542),n=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),s=i(76790),n=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),s=i(41400),n=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),w=i(66184),v=i(28538),b=i(24068),S=i(43705),P=i(51879);function T(){(0,w.logFilter)()instanceof v.LogFilterImpl||w.logFilter.set(new v.LogFilterImpl),_();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new S.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,n.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&b.LogTail.instance()}function _(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=T,t.setupLogFormatter=_,(0,s.later)((()=>{h.Settings.logStdout.watchLater(T),h.Settings.logDir.watchLater(T),h.Settings.tailLogs.watchLater(T),h.Settings.logColor.watchLater(_),h.Settings.logLevel.watchLater((()=>w.defaultLogLevel.unset()))}))},83954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(89179);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},82647:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p69(){return n(this,r,"m",s).call(this,.5)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,s=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},44983:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(76790),s=i(93973);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},36372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(76790),s=i(42659),n=i(31586),a=i(97238),o=i(50597),l=i(9103),u=i(55222);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},38812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(21605);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}×${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),s=i(65713);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function w(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=w;class v{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new v;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function T(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=w(t,((t,r)=>(t-i)*(r-e))),s=w(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=T,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(T(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(38522),s=i(22573),n=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(48161)),n=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),w=i(34102),v=i(26293),b=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==b.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=S.exec(e)}function T(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=T,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=T(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const _=(0,s.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,w.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=T(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),s=i(19851),n=i(54993);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(22573),s=i(51926),n=i(83556);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),s=i(59455),n=i(31562);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),w=i(97790),v=i(59455),b=i(54993),S=i(54557),P=i(19851),T=i(50213),_=i(88158),M=i(409),E=i(78406),D=i(25764),x=i(99331),k=i(56519),C=i(46292),F=i(8769),A=i(83278),I=i(32144),O=i(29882),L=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,T.mkLogger)("proc.Pids"))),j=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,O.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,v.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??L.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,f.isEmpty)(s))return B().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,N.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){B().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!z(r,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:r}),a.push(W(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,F.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,s,"f").delete(l),o(this,s,"f").getOrSet(l,(async()=>{const i=o(this,r,"m",n).call(this,e.pid),s=(0,w.opt)((0,_.Try)((()=>(0,O.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:s,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,s,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,v.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,r,"m",n).call(this,e);return(0,k.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new E.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:D.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=U,s=new WeakMap,a=new WeakMap,r=new WeakSet,n=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new U(A.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const s=i(31421),n=i(48161),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),w=i(84968),v=i(48963),b=i(56519),S=i(84777),P=i(8103),T=i(45879),_=i(43334),M=i(24399),E=i(45643),D=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function k(e){if(_.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,T.readFileMaybe)("/proc/"+i+"/stat")));return D().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,E.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:N)).filter((e=>x(e)&&t.includes(e.pid)));return D().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=x,t.pidInfo=async function(e){return(0,b.thenMap)(k([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,b.thenMap)((0,E.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=k;const C="Get-Process",F="| Select-Object -Property Id,ProcessName,StartTime";function A(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return R(e);const t=[C,"-Id",A(e),"-ErrorAction SilentlyContinue",F].join(" ");return(0,b.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,v.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,v.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===a.default.pid))||r.push({pid:a.default.pid,start:new Date(w.StartTs),cmd:"node "+a.default.title}),r}async function N(e){return t=(await(0,S.stdoutResult_)("ps",["-p",A(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(_.isLinux)return(0,c.toGt0)((0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){D().warn("clk_tck failed",{error:e})}return 100})),j=(0,g.lazy)((()=>Date.now()-(0,n.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,s=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(s)?{pid:i,cmd:r,start:new Date(j()+s/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),s=i(42659),n=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),w=i(99331),v=i(56519),b=i(31562),S=i(84777),P=i(34102),T=i(43334),_=i(28874),M=i(63870),E="{ready}",D=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,v.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,w.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,v.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,s.lazy)((()=>{if(!T.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,w.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),s=i(91655),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874),l=(0,n.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,s.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,s.pick)(e??{},"retries","halt","path"),...(0,s.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},86941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(19851),s=i(59455),n=i(72993),a=i(46292),o=i(95696),l=i(50213),u=i(83179),c=i(28874),d=i(2858),h=i(84438),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),n=await t.resolve_();if(null==r||null==n||n.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=n.join("licenses");for(const r of(0,s.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=n.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),s=i(22573),n=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function w(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function v(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){T(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&w(),y("strictDeduping",e)&&v(),(y("optOut",e)||y("noNetwork",e))&&_()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(m.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=w,t.setStrictDeduping=v;const b=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],S={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function T(e){for(const t of b)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:S;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function _(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=T,t.disableExternalNetworkRequests=_},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),s=i(53265),n=i(87652);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},4936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(55835),l=i(51926),u=i(50213),c=i(81168),d=i(79842),h=i(21330),f=i(51275),m=i(29882),p=i(28874),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+e.replace(/'/g,"′")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),s=i(83556);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),w=i(40583),v=i(81168),b=i(44198),S=i(96706),P=i(34102),T=i(28283),_=i(81075),M=i(98778),E=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?n(this,r,"m",s).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?n(this,r,"m",s).call(this,e??t)+": "+i:null==this.fromEnv(e)?n(this,r,"m",s).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,v.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,S.caseInsensitiveEnv)():new w.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,b.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,T.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(T.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return _.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,b.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&S.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,b.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&S.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new w.CaseInsensitiveValued(e)))??(0,S.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,v.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],E.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,v.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],E.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,v.wrap)(["",e+": "+r],E.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,s=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),s=i(51168),n=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),w=i(40583),v=i(79840),b=i(7282),S=i(12801),P=i(4328),T=i(70488),_=i(84248),M=i(5531),E=i(99315),D=i(34365),x=i(34580),k=i(96706),C=i(50274),F=i(33866),A=i(52086),I=i(48584),O=i(45969),L=i(43334),R=i(24540),N=i(70379),B=i(71300),j=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),q=i(30577),H=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Z=i(71988),Y=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),se=i(57039),ne=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(b.isProd);const we=()=>!(0,t.isProd)();function ve(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function be(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>we()?"1":"25"}),imageCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>we()?32:1024}),quiet:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:be}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Y.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:be}),useFsWatch:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new se.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>H.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:H.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>H.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Y.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new Y.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),minDelayBetweenSpawnMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,T.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>we()?"5s":"5m"}),streamFlushMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>v.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ne.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>we()?50:500,min:1,max:5e3}),enableArchive:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ve()}),enableRemove:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ve()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:D.SynchronousModes,defaultValue:D.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>we()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:we()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>we()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Y.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Y.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!we()||!(0,O.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:F.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Y.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Y.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:q.UpdateChannels}),autoUpdateCheck:new Y.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Y.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Y.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Y.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Y.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Y.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Y.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Y.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":s.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Y.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Y.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!we()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new ne.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Y.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Y.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!we()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:A.CropStrategies.attention,strEnum:A.CropStrategies}),videoFrameAtSec:new ne.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Y.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Y.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Z.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Y.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>j.DefaultIncludedPreviewTags}),disableAllFilters:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Y.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new se.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ne.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!we()}),tagKeywordsFromPath:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Y.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new ne.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!we()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Y.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Y.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function Se(e){const i=((0,u.blank)(e)?"":e).split(n.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(n.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=Se,t.pathWithDefaults=(0,a.lazy)((()=>Se((0,k.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const Te=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Te().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new w.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(31586),n=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),w=i(15674),v=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=c.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,v.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>(0,n.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,n.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,w.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel,v.Settings.minBusyPct.opts.defaultValue=()=>(0,s.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),w=i(54993),v=i(50213),b=i(81168),S=i(83556),P=i(87290),T=i(98314),_=i(34102),M=i(83278),E=i(95696),D=i(60865),x=i(4175),k=i(83179),C=i(81075),F=i(28874),A=i(41692),I=i(84438),O=i(32707),L=i(6707),R=i(98778),N=i(55018),B=i(10357),j=(0,r.lazy)((()=>(0,v.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,O.systemSettingsFile)()){if(null!=e)return X(M.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,L.readTomlFile_)((0,O.systemSettingsFile)()))?.[F.Settings.libraryDir.name])}catch{return}}function U(e){return(0,L.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function q(){return U((0,O.systemSettingsFile)())}function H(e){return U(z(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:F.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,k.settingsToObj)(i),wip:r}),r){const t=await(0,L.readTomlFile_)(s),i=await(0,L.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function K(e=(0,O.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,F.persistedSystemSettings)()),t}function Z(e){return X(z(e))}async function Y(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,F.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,F.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,T.errorToS)(e)),[]}}async function Q(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,L.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,F.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,F.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}})));return t.info("loaded",{settings:(0,k.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,x.handleDeprecatedSettings)(),(0,x.handleMetaSettings)(a),{settings:a,warnings:n}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return F.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=q,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await q()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await H()&&await Y()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",G),(0,_.ee)().on("settingsChanged",G),F.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,D.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(E.PosixFile.for(e),(0,F.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=Y,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([F.Settings.noNetwork,F.Settings.httpPort,F.Settings.license,F.Settings.logStdout,F.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(F.Settings))ee().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),F.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(E.PosixFile.forMaybe((0,O.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,_.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${(0,D.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,w.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>function(e,t){return(0,r.compact)((0,a.splitStringArray)(e)?.map((e=>t.getCI(e))))}(t,e.strEnum),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),s=i(55835),n=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),s=i(44652),n=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),s=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),s=i(81168);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),w=i(81168),v=i(76596),b=i(79842),S=i(66649),P=i(21330),T=i(98725),_=i(928),M=i(54261),E=i(89724),D=i(17415),x=i(88600),k=i(51275),C=i(29882),F=i(17217),A=i(68284),I=i(57902),O=i(28874),L=i(65162),R=i(71300),N=i(14036),B=i(61424),j=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,b.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,F.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,b.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,A.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,T.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,D.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,D.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,M.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,_.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,x.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,D.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,b.datedToStartDateTime)(this.date)??(0,b.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,b.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function q(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],s=r;if((0,x.isValidDate)(t)){if((0,D.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||R.OverrideUTCZoneTags.includes(s))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,w.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,b.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,b.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,b.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function H(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,T.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,b.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,T.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,x.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,w.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",q(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??s("tags",q(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("stat+bname",await(0,B.extractStatBname)(e)))??(n?void 0:s("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",H(e,t)))??(n?void 0:s("path",G(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await $(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return q(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),s=i(97352),n=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(77988),n=r(i(76760)),a=r(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),w=i(12168),v=i(56038),b=i(4867),S=i(36557),P=i(98247),T=i(21330),_=i(98725),M=i(23467),E=i(88561),D=i(95696),x=i(17217),k=i(16287),C=i(50213),F=i(17921),A=i(7282),I=i(88158),O=i(23560),L=i(28874),R=i(12089),N=i(45255),B=i(81168),j=i(63870),z=i(15674),V=i(28544),W=i(43207),U=i(72180),q=i(75767),H=i(12788),G=i(80495),$=i(14036),J=i(67083),K=i(3432),Z=i(28630),Y=i(15912),X=i(30748),Q=i(16170),ee=i(95141),te=i(7330),ie=i(54979),re=i(1078),se=i(61424),ne=i(8791),ae=(0,o.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ce()};const le=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,S.batchClusterOptions)((0,A.isTest)()?8:(0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function ue(){const e=le();return e.ended?le.refresh():e}function ce(e=!1){return(0,d.map)(le.clear(),(t=>t.end(e)))}t.exiftool=ue,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeoutError)({p:ue().version(),timeoutMs:N.ShortCommandTimeoutMs})},t.exiftoolVersionMaybe=function(){return(0,d.map)(le.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,j.commandTimeoutMs)()})))},t.shutdownExiftool=ce,t.extractBinaryTag=function(e,t,i){return ue().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),ie.mimetypeCache.prior()?.clear()};async function de(e){return(0,f.omit)(await ge(e,!1),...t.IgnoredSidecarFields)}function he(e){return null==e?void 0:(0,t._readTags)((0,x.toNativePath_)(e))}async function fe(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function me(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*w.GB)&&t.push("-api LargeFileSupport=1"),t}async function pe(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ae().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,ie.readMimeType)(e),s=await e.sidecar(),n=(0,Q.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Q.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ae().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function ge(e,i=!0){const r=D.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void ae().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ae().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,Z.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,Q.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ae().debug("readRawTags() sidecar had values",{sidecar:e.base})):ae().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,J.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,ee.orientationToRotation)(a.Rotation),ae().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ye(e,t){return null==t?void 0:(0,v.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Q.normalizeMimetype);if((0,u.blank)(r))return void ae().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ae().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,se.canInferForDir)(e.parent()),l=await(0,K.maybeInferTimezone)(e,n,o);if(ae().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values])if(!(0,U.isUtcTagName)(t)){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,T.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l)}const c=o?(0,X.extractMakeAndModel)(n):await(0,se.inferMakeAndModel)(e,n);c.Make!==(0,X.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ae().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,G.extractExposureSettings)(n),g=await(0,re.extractSizeInfoFromFile)(e,n);if(null==g)return void ae().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,ne.extractTitleDescription)(n),...d,cameraId:(0,q.cameraIdFromTags)(n),imageId:(0,q.imageIdFromTags)(n),lensId:(0,q.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,te.extractRating)(n)};(0,A.isTest)()&&(y.__parsedBy__=a.default.pid);const w={...n,...y};return ae().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(w,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(w)}catch(e){return void ae().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,M.eqlAsync)(e.sha(),t.sha())||await(0,M.eqlAsync)(de(e),de(t))},t.readTags=he,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ye(t,await ge(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,x.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await he(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await ue().readRaw((0,x.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ae().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,ee.extractRotation)(await ge(e,!0))},t.moveOriginal=fe,t.overwriteTags_=async function(e,t){try{await(0,v.time)("exiftool.overwriteTags:"+e,(async()=>{await ue().write(e.nativePath,t,await me(e)),e.clearThisAndParent()}))}catch(i){ae().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,v.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await ue().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=me,t.writeTagDest=pe,t.writeTags_=function(e,t,i){return(0,v.time)("exiftool.writeTags:"+e,(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await pe(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=D.PosixFile.for(t),s=(0,f.fromEntries)(i);ae().info("writeTags()",{src:e,dest:t,t:s}),await ue().write(r.nativePath,s,await me(r)),L.Settings.overwriteOriginal.valueOrDefault||await fe(r),r.clearThisAndParent()}}))},t.readRawTags=ge,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return ae().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ae().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...L.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,$.isVideoExt)(n.default.extname(e))?[]:["-fast"]],r=await(0,v.time)("exiftool.read()",(()=>ue().read(e,i).catch((t=>{ae().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ae().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,Q.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),oe&&(r.__instance=(0,F.safeUUID)()),r}}),t.parseTags=ye},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),w=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const v=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function T(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([T(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(T)):(0,u.compactBlankValues)(t)}function M({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of v){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of v)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of v){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>M({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>M({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>M({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>M({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,w.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),s=i(40958),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function w(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=w,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return w(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return w(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return w(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return w(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return w(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return w(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return w(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return w(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),s=i(45599),n=i(68708),a=i(50213),o=(0,s.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,n.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:s}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[s])&&(t[i]=t[s]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,n.pick)(e,"Directory","FileName"));for(const t of(0,n.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),w=i(50213),v=i(81168),b=i(66649),S=i(17415),P=i(29882),T=i(95696),_=i(17217),M=i(28874),E=i(47783);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>x({action:e,key:t,value:i})))}function x({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=x,t.InferAction="infer";const k=(0,s.lazy)((()=>(0,w.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function A(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,v.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,r){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=T.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,v.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=F(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=A,t.ensureInferredHistoryRecords=async function(e,i,r){const s=D(t.Actions.infer,r),n=(M.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?A(r):void 0)??{};return M.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),I(i,s,n)},t.ensureHistoryRecords=I},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(53705)),n=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),w=i(72180),v=i(14245),b=i(61424),S=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,v.omitInvalidGeolocationTags)(t);{const e=T(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,w.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=_(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function T(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return S().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function _(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,u.toDated)(t[r]);if(null==s||(0,f.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return S().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return S().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=T,t.inferTzOffsetMinutesFromFilename=_},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),w=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function v(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):v(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>w.unset()))})),t.keywordToPath=function(e){const t=w();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=v,t.splitKeywords=b;const P=/^\(?none\)?$/i;function T(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function M(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,M);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,M).map((t=>[e.Keyword,...t]))}t.parseCategories=T,t.isKeywordStruct=_,t.parseKeywordStruct=M,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=T(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(_(i)?t.push(...M(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const w=/([\d. -]+)\s?mm\b/i,v=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=w.exec(e)?.[1].replace(/\s/g,""),i=v.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function w(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=w(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=w;const v={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(v))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},38010:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(50213),g=i(84885),y=i(66649),w=i(98725),v=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function T(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return v().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return v().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return v().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,w.parseDated)({input:e.When}));return null==r?v().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?v().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):v().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-T(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),s=i(54993),n=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},66039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(75020),u=i(59455),c=i(50213),d=i(68852),h=i(81168),f=i(70417),m=i(28874),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,w=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,v=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,w),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function T(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,v),null!=e&&(T(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(T(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(T(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(T(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const _=(0,s.compactBlanks)(t.split(/\s+/)),M=l.length,E=b.length;if(_.length>0)if(0===M&&E>0)l.push(..._);else if(0===E&&M>0&&1===_.length)b.push(..._);else if(1===_.length)l.push(..._);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?_.pop():_.shift()),l.push(..._)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function T(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function _(e,t,i){return T("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=T([t.modifier,t.lifespan]),r=T(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?T([r,e]):_(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),s=i(54993),n=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),s=i(40958),n=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,s.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),w=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),v=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return w().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return w().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return v().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},3127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(54993),s=i(42231);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),w=i(79842),v=i(21330),b=i(98725),S=i(51275),P=i(35280),T=i(19748),_=i(88561),M=i(95696),E=i(65238),D=i(17217),x=i(57902),k=i(28874),C=i(80496),F=i(65162),A=i(28544),I=i(47783),O=i(88840),L=i(30748),R=i(16170),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:x.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,v.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,v.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,v.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,T.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7,i=!0){if(!await j(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(r,(e=>(0,F.bname)(e))),n=(0,D.findFileIndex)(e,s);if(n<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),H(e,t,!1)):void 0;const l=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[s.slice(n-2*t,n),s.slice(n+1,n+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,w.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,w.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function w(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function v(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=w,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(w(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=v,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>v(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),s=i(22573),n=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),w=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function v(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await v(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void w().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?w().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=v,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),s=i(57975),n=i(90595),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",w=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class v{static isUri(e){return e instanceof v||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return M(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=w.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=k(i[4]||g),n=(i[5]||g).split("/").map(k).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?v.file(r.win32.join(M(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=v;const b=h.isWinPortable?1:void 0;class S extends v{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=M(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function T(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:T;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:T(o,!1)),r}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=T,t.uriToFsPath=M;const x=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(x)?e.replace(x,(e=>D(e))):e}t.percentDecode=k,t.toURI=function(e){return v.isUri(e)?e:v.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),s=i(40958),n=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),s=i(22573),n=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(9103),a=i(37628);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),s=i(30577);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),s=i(22573),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),s=i(9595),n=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},42233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(45200),s=i(98770),n=i(7014);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),s=i(22573),n=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),w=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function v(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=v,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await w());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(v)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),w=i(24399),v=i(28874),b=i(24541),S=i(60224),P=i(63870),T=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function M(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(M(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(M(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function x(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(M(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return w.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function A(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void T().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void T().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return T().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,T().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function I(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>w.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:v.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(x)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>w.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(T().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:v.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(A)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));T().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=A,t.volumeInfoWin=I},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),w=i(83278),v=i(8103),b=i(16287),S=i(45969),P=i(43334),T=i(69108),_=i(98770),M=i(44224),E=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,v.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,M.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>w.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,T.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await x(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,E.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const x=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),s=i(5233),n=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),w=i(98770),v=i(63870),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),T=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,w.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await T()],{timeoutMs:(0,v.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,w.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,v.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),s=i(19851),n=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),w=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(v)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?w().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){w().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const v=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),w=i(84777),v=i(34330),b=i(8769),S=i(34102),P=i(17217),T=i(16287),_=i(43334),M=i(28874),E=i(8540),D=i(68884),x=i(44224),k=i(24541),C=i(69375),F=i(63870),A=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function O(e=(0,F.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function L(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{M.Settings.libraryDir.watchLater(I),M.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&M.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),O((0,F.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux){const i=(0,x.maybeWatchProcMounts)();await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),O((0,F.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),O((0,F.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=M.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?k.mountpointsWin:x.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,F.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||M.Settings.validateMountpoints.valueOrDefault&&!await(0,T.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,S.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),I()})),M.Settings.mountpointsTtlMs.watch(O)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>L(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),L()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,w.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,F.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>L(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),w=i(28874),v=i(69108),b=i(68884),S=i(59107),P=i(69375),T=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await D()??await(0,c.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,b.isGioSupported)())try{await(0,c.thenMap)((0,b.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){T().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function M(e){return!w.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,P.isExcludedMountpoint)(e)&&(!w.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function D(e=_,t=M,i=E){if(y.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return T().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return T().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void T().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=D,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(_)?new h.FileWatcher(_,{recursive:!1,persistent:!1},(()=>{T().info("detected change in "+_),(0,d.setUnrefTimeout)((()=>S.mountpoints.refresh()),n.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),s=i(42659),n=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),w=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await M()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const v=["LocalName","RemoteName","Status"],b=["NETUSE","get",v.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function T(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,u.parseFixed)(v,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=T,t._netInfoWinWmic=_;const M=(0,w.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(T(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),s=i(12168),n=i(28874);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),w=i(95696),v=i(45969),b=i(28874),S=i(59107),P=i(63870),T=i(68995),_=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function E(e){return(0,a.isTrue)(e.ignorable)||(0,v.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function D(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function x(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=D(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function k(e){if(b.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of b.Settings.volumeUuidFilePaths.values){const i=w.PosixFile.for(e.mountpoint).join(t),r=await x(i).catch((e=>_().info("Failed to read "+i,{error:e})));if(null!=r)return _().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,T.volumeUuidSubpath)());if("/"===e.mountpoint)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(b.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(b.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,T.writeVolumeUuid)(e);if(!(0,n.blank)(t))return _().tap({msg:"readVolumeUUID(): wrote new "+(0,T.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return _().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),S.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(E(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>k(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>_().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=E,t.toVolumeUUID=D,t.readUuidFile_=x,t.readVolumeUUID=k},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),w=i(59455),v=i(48884),b=i(50213),S=i(7282),P=i(23560),T=i(28850),_=i(45255),M=i(81168),E=i(56519),D=i(4867),x=i(49776),k=i(9595),C=i(77740),F=i(44198),A=i(96706),I=i(8769),O=i(57159),L=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),j=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),q=i(43334),H=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Z=i(27461),Y=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=s.default.platform(),ne=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,ne),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,x.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ne.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,M.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:se}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))n.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function me(e,i){const r=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(r))return;const s=await(0,L.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function pe(e,t,i){const r=i.filter((e=>(0,M.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,M.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,W.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,M.equalsIgnoreCase)(n,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,S.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,w.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,D.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,O.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,T.shim0)({name:"fs.volumes",impl:async function(){if((0,S.isTest)()){const e=(0,p.toInt)((0,F.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeoutError)({p:q.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeoutError)({p:q.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,M.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,v.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),h=i(34238),f=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const a=n(i(37067)),o=n(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),h=i(50213),f=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),w=(0,u.defer)((()=>(0,h.mkLogger)("net.get")));async function v(e,t){return b({...t,url:e})}async function b(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?a.request:"https"===t.scheme?o.request:w().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??f.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",h=e?.agent??!1,b=r(t.toString(),{method:c,headers:u,timeout:n,agent:h},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const a={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&y.HttpStatusIs.redirect(a.statusCode)&&!(0,l.blank)(e.headers.location)?(w().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(v(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(w().debug("complete",{...a,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(a))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||b.write(e.body),b.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=v,t.httpRequest_=b},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),s=i(37692);let n=!1;function a(){return n}function o(e=!0){l(e),(0,s.writeStateFile)({paused:e})}function l(e){e!==n&&(n=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=a,t.pause=o,t.resume=function(){return o(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return a()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),s.minuteMs);function v(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=v,t.targetCpuLoadPct=b,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(b()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(b()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=v();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,w());return t=(0,a.clamp)(1,s,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const s=r(i(78474)),n=i(40958),a=i(76790),o=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),h=i(87290),f=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),w=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let v;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new s.default;let b=0;function S(){const e=(0,h.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-b>o.minuteMs;i&&(b=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(v?.nativePath)||(v?.close(),v=void 0),r&&null!=e&&(v??(v=new f.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=S()?.readJsonSync();for(const i of e?.events??[])T.get(i.e)!==i.ts&&(w().info("emitting event "+i.e),t.stateEvents.emit(i.e),T.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const T=new Map;function _(e){const i=S();if(null==i)w().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),s=function(e){const t=Date.now()-10*o.minuteMs;return(0,n.uniqByLast)((0,a.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:s};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=_,t.addStateEvent=function(e){const t=Date.now();T.set(e,t),_({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),s=i(87997),n=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function w(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:w((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=w,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return w(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return w(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},75761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function w({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function v({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const v=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=v):p.src=v,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(w({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=w,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...v({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=v},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),s=i(31586),n=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),s=i(22573),n=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function w(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function v(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=w,t.fmtLocalToShort=function(e){return(0,a.map)(w(e),m)},t.nextMidnightTs=v,t.msUntilMidnight=function(){return v()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),s=i(73872);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const w=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,w),w}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s.hasPrior=()=>r,s}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),s=i(21605),n=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),s=i(68708),n=i(34666),a=i(32639);function o(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,n.isPrimitive)(e)||(0,n.isPrimitive)(t))return e===t;if(!(0,s.isObject)(e)||!(0,s.isObject)(t))return!1;for(const i of(0,s.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),s=i(42659),n=i(55835),a=i(31586),o=i(12168),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),s=i(50357),n=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class s extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=s},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,(t=>!e(i,t,s)));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),s=i(22573),n=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=w(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,s){return!(null==s||!o(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,s.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function w(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function v(e){return o(e)&&e>0}function b(e){return o(e)&&e>=0}function S(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function T(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function _(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=v,t.firstGt0=function(...e){for(const t of e){if(v(t))return t;const e=y(t);if(v(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return v(t)?String(t):void 0},t.mapNumeric=S,t.map2Numeric=function(e,t,i){return S(e,(e=>S(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,n.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return S(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=T,t.toPrecisionMaybe=function(e,t){return d(e,(e=>T(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=_,t.times=function(e,t){if(!v(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return _(0,100,v(t)?P(100*(v(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function w(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function v(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=w(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=w,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=v,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=v(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),s=i(30976),n=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),s=i(54993),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),s=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=w,t.ensureSuffix=v,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return v(w(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=w((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),s=i(68708),n=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let s=!0;const n=setTimeout((()=>{s&&(s=!1,i(a.Timeout))}),t);try{n.unref?.();const t=await e;s&&(s=!1,i(t))}catch(e){s&&(s=!1,r(e))}finally{clearTimeout(n)}}))}async function c(e,t,i=!0){const s=await u(e,t,i);if(s===a.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return s}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?a.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return c(e,s,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,n.tot)(i);const s=await u(e,t,r);return s===a.Timeout?(0,n.tot)(i):s}},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),s=i(30301),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(30301),s=i(54993);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},58939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(55835),s=i(31586);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),s=i(30301),n=i(31586),a=i(97238),o=i(29652);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return n(e)??[]},t.optToA=n},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),s=i(23541),n=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},64526:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(27395),u=i(25764),c=i(38836),d=i(99331),h=i(45608),f=i(15056),m=i(87290),p=i(38835),g=i(57159),y=i(61704),w=i(95696),v=i(18454),b=i(13940),S=i(48604),P=i(19851),T=i(23560),_=i(28874),M=i(2858),E=i(7014),D=i(63870),x=i(15674),k=i(22573),C=i(38639),F=i(42659),A=i(56409),I=i(68708),O=i(25470),L=i(22526),R=i(41844);class N extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,T.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,k.blank)(e)||!(0,M._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired_(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new A.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted_(),await(0,M.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted_();const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,x.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted_(),(0,T.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted_(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),v.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.previews=(0,P.lazy)((()=>(0,I.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new R.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,T.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.onEnd=(0,P.lazy)((async()=>{if(!(0,d.ending)())for(const{ea:e,t}of[{ea:this.dbModelJanitor.clear(),t:5*F.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=w.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise.then((()=>this))}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup_(){return(await this.dbModelJanitor())?.backup_()}}t.Library=N,r=N,n=new WeakMap,s={value:void 0}},19113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(62105),s=i(181),n=i(94448),a=i(39604);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},18449:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(7282),s=i(96706),n=i(29325),a=i(28874);t.sentryEnabled=function(){return(0,s.isEnvTrue)("ENABLE_SENTRY")||(0,r.isProd)()&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},95629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(16436)),l=a(i(48161)),u=a(i(1708)),c=i(19851),d=i(19043),h=i(50213),f=i(31578),m=i(7282),p=i(96175),g=i(23560),y=i(84968),w=i(81168),v=i(37805),b=i(25764),S=i(38836),P=i(99331),T=i(85100),_=i(98314),M=i(68301),E=i(70025),D=i(8769),x=i(34102),k=i(34592),C=i(42042),F=i(34474),A=i(20839),I=i(57902),O=i(45969),L=i(43334),R=i(40958),N=i(22573),B=i(42659),j=i(41400),z=i(98553),V=i(55835),W=i(12168),U=i(59455),q=i(54993),H=i(18449),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,T.serviceExitTimeoutMs)(e.name),release:v.release,environment:(0,m.nodeEnv)(),maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(M.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,w.ellipsize)(i,256));const r=await X(e);return await(M.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,x.ee)().on("fatal",$),(0,x.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Z(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Z(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=v.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,k.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*A.DefaultLogFlushMs);const e=await(0,F.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,w.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,w.isString)(e.meta)?(0,w.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Z,t.sentryExceptionToS=Y,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[I.LogLevels.fatal,"fatal"],[I.LogLevels.error,"error"],[I.LogLevels.warn,"warning"],[I.LogLevels.info,"info"],[I.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},37158:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const p=m(i(29907)),g=m(i(1708)),y=i(57206),w=i(19851),v=i(50213),b=i(59880),S=i(23560),P=i(19913),T=i(71567),_=i(37805),M=i(38836),E=i(99331),D=i(45608),x=i(56038),k=i(55534),C=i(42499),F=i(49776),A=i(96706),I=i(98314),O=i(38835),L=i(70025),R=i(8769),N=i(57159),B=i(34102),j=i(33456),z=i(87408),V=i(85021),W=i(17181),U=i(86941),q=i(28874),H=i(41692),G=i(2858),$=i(69385),J=i(22573),K=i(42659),Z=i(41400),Y=i(56409),X=i(55835),Q=i(41583),ee=i(54993),te=i(95629);t.setupEventHandlers=(0,w.lazy)((()=>{(0,B.ee)().on("resume",(()=>(0,$.resume)())),(0,B.ee)().on("pause",(()=>(0,$.pause)()))}));class ie extends M.EndableWrapper{constructor(e){super(e),r.add(this),s.set(this,void 0),n.set(this,new Y.Latch),a.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,x.time)("Service.setup",(()=>f(this,r,"m",o).call(this))))),u.set(this,(0,w.lazy)((()=>{const e=g.default.stdin.pipe(new j.LineReader);return e.on("data",(e=>f(this,r,"m",d).call(this,(0,ee.toS)(e)))),e}))),(0,S.isBillingService)()||(0,H.setSettingsDefaults)(),h(this,s,(0,v.mkLogger)("Service("+this.name+")"),"f"),f(this,r,"m",c).call(this),this.setup_()}get name(){return super.name}get ready(){return f(this,n,"f").promise}get isReady(){return f(this,n,"f").isResolved()}setInputHandler(e,t){f(this,a,"f").set(e.trim().toLowerCase(),t)}}t.Service=ie,s=new WeakMap,n=new WeakMap,a=new WeakMap,u=new WeakMap,r=new WeakSet,o=async function(){try{(0,J.mapNotBlank)((0,A.getEnv)("PS_FATAL_"+this.name),(e=>{throw new N.WrappedError(e,{fatal:!0})})),(0,J.mapNotBlank)((0,A.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new N.WrappedError(e)}),5*K.secondMs)})),(0,P.setServiceName)(this.name),(0,b.setProcessTitle)(),(0,S.isMainService)()&&await(0,U.mergeUserDataDirs_)(),await(0,G.readSettings)(),await f(this,r,"m",l).call(this),(0,W.setupLogger)(),(0,y.addDefaultJsonRevivers)(),(0,F.cacheDir)(),(0,t.setupEventHandlers)(),f(this,u,"f").call(this),await(0,C.setupLuxon)(),q.Settings.startPaused.valueOrDefault&&(0,$.pause)(),(0,E.ending)()?f(this,n,"f").reject():f(this,n,"f").resolve()}catch(e){console.error((0,I.errorToS)(e)),f(this,n,"f").reject((0,Q.toErr)(e)),(0,D.exit)({reason:(0,L.addErrorFlags)(this.name+" setup failed: "+(0,I.errorToS)(e),O.FatalErrorFlag),status:14})}},l=async function(){(0,S.isPermaService)()||(0,B.ee)().on("fatal",(e=>(0,D.exit)({error:e,status:12}))),g.default.on("unhandledRejection",(e=>(0,X.map)(e,(e=>(0,R.onError)("unhandledRejection",e))))),g.default.on("uncaughtException",(e=>(0,X.map)(e,(e=>(0,R.onError)("uncaughtException",e))))),g.default.on("SIGINT",(()=>(0,D.exit)({reason:"SIGINT",status:0}))),g.default.on("SIGHUP",(()=>(0,D.exit)({reason:"SIGHUP",status:0}))),g.default.on("SIGTERM",(()=>(0,D.exit)({reason:"SIGTERM",status:0}))),p.default.isWorker&&g.default.on("disconnect",(()=>(0,D.exit)({reason:"disconnect",status:0}))),await(0,te.installSentry)(this)},c=function(){this.setInputHandler("--version",(()=>(0,T.stdoutWrite)({version:_.version}))),this.setInputHandler(k.ServiceExitCommand,(()=>(0,Z.later)((()=>(0,D.exit)({reason:k.ServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,T.stdoutWrite)(x.PromiseTimer.instance().report()))),this.setInputHandler(V.HealthCheckCommand,(async()=>(0,T.stdoutWrite)(await(0,z.getStatusSummary)({refresh:!0}))))},d=async function(e){if(f(this,s,"f").debug("onLine()",{line:e,ending:this.ended||(0,E.ending)()}),await this.setup_(),e.startsWith("--")){const t=e.split(/\s+/,1)[0],i=f(this,a,"f").get(t);null==i?(f(this,s,"f").error("onLine(): unknown command",{line:e,knownCommands:[...f(this,a,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else f(this,s,"f").error("onLine(): failed to process",{line:e})}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},46628:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(47783),c=i(97573),d=i(42231),h=i(40958),f=i(22573),m=i(68708),p=i(75020),g=i(54993),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function w(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function v(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(w));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...v(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...v(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=v},88224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(28874),o=i(42231),l=i(40958),u=i(20214),c=i(43487),d=i(46628),h=i(63175),f=i(4407),m=i(58886),p=i(32646),g=i(48144),y=i(60047),w=i(6186),v=i(42003),b=i(43723),S=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function P({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];if(t=(0,l.uniqBy)([e,...t],(e=>e.nativePath)),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,y.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),a.Settings.tagGeo.valueOrDefault)for(const e of t){const t=await(0,p.geoTagFile)(e);if(null!=t){u.push(t);break}}await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,b.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,g.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,v.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{S().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const P=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(w.normalizeTagRoot),o.joinTagPath)),T=await(0,w.tagDeltas)(i,P);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:P,result:T}),T}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await P({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=P},63175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(47783),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},4407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(47783),h=i(40958),f=i(55835),m=i(31586),p=i(75020),g=i(54993),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),w=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function v(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:v(e)})))}function T(e){if((0,m.within)(1,12,e))return(0,f.map)(w()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function M(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),T);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),w.unset()})),t.yearToOrdinal=v,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=T,t.dayTagRef=_,t.dateTag=M,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:M(r.date)}},58886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(19851),s=i(50213),n=i(42231),a=i(21404),o=i(40958),l=i(89937),u=i(75020),c=i(54017),d=i(94448),h=i(69032),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},32646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTagFile=t.geoTag=void 0;const r=i(48884),s=i(56519),n=i(50213),a=i(28874),o=i(47783),l=i(14245),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)((()=>(0,n.mkLogger)("curators.GeoTagger")));function p(e){const t=a.Settings.tagGeoMaxDistanceKm.valueOrDefault;if(t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t))return void m().warn("geoTag(): GeolocationDistance too large, skipping geo tag",(0,f.pickDeep)(e,...l.GeolocationFields));const i=a.Settings.tagGeoSynonyms.synonymMap(),s=a.Settings.tagGeoTemplate.valueOrDefault.map((t=>(0,r.first)(i.get(t)??[t],(t=>(0,f.pluckDeep)(e,t)?.value)))),n=(0,c.compactBlanks)(s);return m().tap({msg:"geoTag",result:0===n.length?void 0:(0,c.compact)([u.TagRoots.Where,...n]),meta:{picked:s}})}t.geoTag=p,t.geoTagFile=function(e){return(0,s.thenMap)((0,o.readTags)(e),p)}},48144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(47783),h=i(97573),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),w=i(96249),v=i(55835),b=i(75020),S=i(54993),P=i(6186),T=i(43723),_=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),M=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return _().tap({msg:"extractDashDashTags()",result:(0,v.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,v.mapOr)(M(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function D(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>M.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=D;const x=/\w{2,7}:\/\/\S+/g;function k(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(x,(e=>(i.push(e),"")));s.push(...(0,v.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,w.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function F(e,t){const[i,s]=(0,r.partition)(k(e),T.isWhoTag),n=(0,w.flatten)(i.map(T.nameTag)),a=(0,m.uniq)((0,w.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=k,t.dedupeKeywordPaths=C,t.processKeywords=F,t.keywordTagFiles=async function(e,t){return F([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,w.flatten)(e.map(D)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,w.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},60047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(56519),s=i(28874),n=i(47783),a=i(75020),o=i(40958),l=i(22573),u=i(55835);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},6186:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhereRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(50213),s=i(28874),n=i(42231),a=i(75020),o=i(40958),l=i(22573),u=i(45599);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.WhereRoot={name:a.TagRoots.Where,ordinal:5},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,t.WhereRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Where,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase()))),g=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhereRoot,...e.slice(1)]:g.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},42003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[w(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function w(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}t.friendlySubtype=y,t.fixCase=w},43723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(19851),s=i(50213),n=i(28874),a=i(47783),o=i(28630),l=i(66039),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(v)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function w(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function v(e){if(!(0,d.blank)(e))return Array.isArray(e)?(w(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=w,t.nameTag=v},98348:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(48884),d=i(19851),h=i(23560),f=i(25764),m=i(38836),p=i(99331),g=i(5916),y=i(12959),w=i(55332),v=i(91872),b=i(80632),S=i(51040),P=i(44955),T=i(15056),_=i(70025),M=i(57159),E=i(18454),D=i(28874),x=i(5233),k=i(42659),C=i(31586),F=i(68708),A=i(30976),I=i(17036),O=i(27134),L=i(35052);class R extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=k.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),D.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*k.secondMs),this.migrate_=(0,g.lazyAsync)({desc:"db.migrate",later:async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{await(0,O.verifyDb_)((()=>this.db))}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||D.Settings.dbForceRecover.valueOrDefault)&&(E.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new I.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e}}}),this.tableInfo_=(0,d.lazy)((()=>(0,L.localTableInfo)(this.db)))}toJSON(){return(0,F.pick)(this,"schema","dbFile")}get isOpen(){return!0===l(this,n,"f")?.open}get inTransaction(){return this.isOpen&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(t||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,b.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===D.Settings.dbAutoVacuumMode.valueOrDefault&&(0,C.gt0)(D.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%D.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&(this.logger.info("running incremental_vacuum..."),l(this,n,"f")?.pragma("incremental_vacuum")),l(this,n,"f")}async verify_(){await(0,O.verifyDb_)((()=>this.db))}assertHeartbeat_(){const e=(0,A.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{this.logger.info("closing db",l(this,n,"f")),await(0,x.retryOnReject_)((()=>{!0===l(this,n,"f")?.open&&l(this,n,"f")?.close()}),{timeoutMs:D.Settings.dbBusyTimeoutMs.valueOrDefault,maxRetries:5,errorIsRetriable:_.isSqliteBusyError,retryDelay:k.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>this.db),(()=>(0,O.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db),(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db),(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,O.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,T.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,P.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,y.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,w.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=R,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,C.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},25470:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(66364),d=i(50213),h=i(23560),f=i(78406),m=i(25764),p=i(38836),g=i(99331),y=i(56038),w=i(12959),v=i(55332),b=i(76187),S=i(73209),P=i(28874),T=i(42659),_=i(75240),M=i(95700),E=i(22526),D=i(45648),x=5*T.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class k extends f.EndableInterval{static for(e){return new k(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:T.minuteMs,rank:m.EndableRanks.db,endTimeoutMs:5*T.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new p.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),m.EndableRanks.postdb,x),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*T.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,M.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,y.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,w.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=k,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:x,endableRank:m.EndableRanks.postdb,noopIfContested:!1});(0,h.isDbManager)()&&await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,b.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),await this.db.closeDb()},o=function(){return this.ended||(0,g.ending)()||(0,c.isSuspended)()}},22526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(19851),s=i(50213),n=i(92407),a=i(55332),o=i(44955),l=i(15056),u=i(87290),c=i(98314),d=i(38835),h=i(73209),f=i(95696),m=i(17217),p=i(18454),g=i(57902),y=i(28874),w=i(2858),v=i(40958),b=i(22573),S=i(42659),P=i(94448),T=i(98348),_=i(45648),M=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,w._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function x(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return k((0,l.pathToDb)(t,"models"))}function k(e){return e.sibling("db-info.json")}async function C(e=x(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw M().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=x,t.libraryDbInfoFromDbFile=k,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=k(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new T.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>M().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new T.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return M().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,v.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw M().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return M().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},86859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(54557),s=i(50213),n=i(99331),a=i(56038),o=i(65753),l=i(66184),u=i(70417),c=i(28874),d=i(40958),h=i(22573),f=i(45599),m=i(96249),p=i(31586),g=i(51926),y=i(57038),w=i(21074),v=(0,f.defer)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,y.knex)()(this.tableName)}prep(e,t=!1){const i=(0,w.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return v().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&v().log((0,l.defaultLogLevel)(),i+"(): "+(0,w.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;v().throw(t,{method:i,...(0,w.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,a.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,g.replaceAll)((0,g.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,w.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,m.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}async batched(e){let t,i=0;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,o.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&(await e.onResults(t),i+=t.length)}while((0,d.isNotEmpty)(t)&&!(0,n.ending)()&&(null==e.maxResults||e.maxResults>i));return{resultCount:i,done:null==t||t.length<(0,o.maxBatchPluckSize)()}}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}async pluckBatched(e){let t=0;const i=(0,u.min)([e.limit??(0,o.maxBatchPluckSize)(),e.maxResults]);if(i<=0||(0,p.lte0)(e.maxResults))return{done:!1,resultCount:t};let r;for(;null==e.maxResults||e.maxResults<=0||t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},36908:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(42231),o=i(40958),l=i(76790),u=i(23838),c=i(31586),d=i(54993),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},57038:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(31832)),n=i(19851),a=i(56519),o=i(55835),l=i(68708);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},17036:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(77598),l=i(19851),u=i(50213),c=i(7282),d=i(37805),h=i(4867),f=i(51040),m=i(77740),p=i(38835),g=i(8769),y=i(57159),w=i(34102),v=i(73209),b=i(95696),S=i(43899),P=i(18454),T=i(28874),_=i(40958),M=i(42659),E=i(41400),D=i(98553),x=i(55835),k=i(34666),C=i(32639),F=i(45648),A=i(94715),I=i(27134);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,k.lt)((0,A.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,_.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,v.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:T.Settings.dbMaintenanceTimeoutMs.valueOrDefault},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=A.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(A.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.info("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,w.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),(0,c.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{if((0,m.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(M.secondMs,3*M.secondMs)),await(0,x.map)(e,(e=>e(r))),await(0,h.thenOrTimeoutError)({p:this.applyMigration_(r,i),timeoutMs:5*T.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch((e=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,F.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile(),r=(0,f.splitBatchSql)(i);if((0,_.isEmpty)(r))this.logger.info("No-op migration: "+e);else{t&&this.db.pragma("foreign_keys = OFF");for(const t of r)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,I.foreignKeyCheck_)(this.db)}}finally{t&&this.db.pragma("foreign_keys = ON")}}},94715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(97352),o=i(68852),l=i(81168),u=i(85810),c=i(42022),d=i(1971),h=i(79842),f=i(89724),m=i(17415),p=i(88600),g=i(20014),y=i(42231),w=i(87001),v=i(40958),b=i(55835),S=i(31586),P=i(97790),T=i(89937),_=i(54993),M=i(7656),E=i(36908),D=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),x=new RegExp(`^(${(0,o.escapeRegExp)(T.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function k(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function F(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)}function A(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>x.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=k,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=F,t.isoToPrecisionMs=A,t.Migrations={fix_root_tags:F,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},A),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},k),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},w.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,_.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,v.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:M.rebuildTagAssetCounts,create_tag_fts:e=>{e.exec("DROP TABLE IF EXISTS tag_fts"),e.exec("CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize=\"unicode61\");")},rebuild_null_island:e=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,y.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")}}},27134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(14121),s=i(19851),n=i(50213),a=i(84777),o=i(12959),l=i(5531),u=i(91872),c=i(99315),d=i(76187),h=i(51040),f=i(38835),m=i(57159),p=i(29882),g=i(95696),y=i(89966),w=i(38156),v=i(28874),b=i(63870),S=i(5233),P=i(42659),T=i(41400),_=i(50357),M=i(98553),E=i(56409),D=i(31586),x=i(20214),k=i(51926),C=i(12168),F=i(59455),A=i(54993),I=i(94448),O=i(9508),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){L().debug("pragmaOrThrow_()",{db:N(e),db_open:e?.open,pragma:t,okResult:i});const r=(0,k.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(r,i)||L().throw(`${t} failed for ${N(e)}: ${(0,M.stringify)({result:r})}`)}function N(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}function B(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function j(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function z(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>v.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:v.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function V(e){await(0,u.handleDbRetries_)("db.quickCheck",e,B),await(0,T.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",e,j),await(0,T.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",e,z)}function W(e){return(0,O.withDbSync)(e,V,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,I.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=B,t.integrityCheck_=j,t.foreignKeyCheck_=z,t.verifyDb_=V,t.verifyDbFile_=W,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=v.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,F.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,D.gt0)(n?.busy)&&i>0?(await(0,T.delay)(250),e({db:t,retries:i-1})):n};const U=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new w.PushProgressObserver({path:(0,A.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,A.toS)(e);U.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),await W(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,x.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,x.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},21074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(48884),s=i(68852),n=i(81168),a=i(12943),o=i(96249),l=i(98553),u=i(31586),c=i(68708),d=i(32639),h=i(54993);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},35052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(22573),s=i(23838);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},9508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(80632),s=i(28874),n=i(30301),a=i(54993);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)((()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i})));try{return t((function(){const e=o();return e.open?e:o.refresh()}))}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const n=(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i});try{return await t(n)}finally{n.close()}}},53493:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(50213),s=i(45608),n=i(69554),a=i(38790),o=i(53978),l=i(95696),u=i(48368),c=i(45200),d=i(40958),h=i(22573),f=i(38639),m=i(98553),p=i(31586),g=i(68708),y=i(5670),w=i(64526),v=i(37158),b=i(31503),S=i(57038),P=i(21074),T=i(43487),_=i(48723),M=i(94710),E=i(23523);!async function(){try{const e=new n.CLI(y.ServiceNames.list).add(b.LogArgs,a.ColorArgs,o.TimingArg);e.add({beforeParse:e=>e.option("--primary",'Only include the primary, or "best" asset file variation found for every asset. See https://phstr.com/dedupe for details.').option("--no-primary","Exclude primary asset file variation for every asset. This is mutually exclusive with the --primary option, and returns all rows that option omits.").option("--limit ","Emit at most LIMIT values.",p.toGt0).option("--query ","Apply the given query and return all matching asset file paths. Must be the last argument. Incompatible with --where.").option("-j, --json",'Emit a JSON object for every asset file with "hidden" and "shown" flags').option("--dump","Emit a JSON object that includes all column values").option("--where ","Apply a SQL WHERE clause to filter the rows returned. If this is omitted, only shown assets are returned: hidden, excluded, deleted, and incomplete assets will be omitted.").option("--orderby ","Apply a SQL ORDER BY clause to filter the rows returned.").option("-0, --print0",'Print each full native path name to standard output, followed by a null character (instead of the newline character).\nThis is suitable for properly handling filenames that include whitespace characters in shell pipelines using commands like xargs, which has a "--null" mode which expects filenames to be separated by the null character.\nThis cannot be used with --json or --dump.').option("--looks-like ","Find images that look like the photo or video specified by FILE. Use a full pathname.").option("--tasks","List the currently enqueued tasks that sync is process(ing). Implies --json. Does not support --print0.").option("--tags","List all tag paths along with their counts. Implies --json. Does not support --print0.")});const t=(await e.parse()).opts(),i=(0,d.mapNotEmpty)(t.query,(e=>e.join(" "))),D=(0,f.isTrue)(t.dump),x=D||(0,f.isTrue)(t.json),k=t.where;if(null!=i&&(0,h.notBlank)(k))throw new Error("--query cannot be used with --where");const C=new v.Service("list");await C.ready;const F=await w.Library.instanceRequired_().modelDb(),A=(0,r.mkLogger)("list");function I(e){for(const i of e)!0===t.print0?process.stdout.write(i+"\0"):console.log(i)}if((0,f.isTrue)(t.tags)){const V=_.Tag.ops().allf((e=>_.Tag.orderBy(e)));return void console.log((0,m.stringifyPretty)(V.map((e=>(0,g.pick)(e,"path","assetCount")))))}if((0,f.isTrue)(t.tasks)){const W=M.Task.ops().allf((e=>M.Task.orderBy(e)));return void(W.length>0?console.log((0,m.stringifyPretty)(W)):console.error("No pending items in any queues."))}let O=T.Asset.query().join("AssetFile","AssetFile.assetId","Asset.id").join("AssetTag","AssetTag.assetId","Asset.id");if(O=O.select({assetId:"AssetFile.assetId",assetFileId:"AssetFile.id",shownFile:"AssetFile.shown",mountpoint:"AssetFile.mountpoint",uri:"AssetFile.uri",hidden:"Asset.hidden",rating:"Asset.rating"}).distinct(),(0,h.notBlank)(t.looksLike)){const U=l.PosixFile.for(t.looksLike);A.info("Calculating image hash for "+U);const q=await U.sha(),H=await(0,u.imageHash)(U);if(null==H)throw new Error("Failed to generate image hash for "+U);A.info("Looking for assets with matching meanHash or SHA",{meanHash:H.meanHash,SHA:q}),O=O.where((e=>e.where("AssetFile.meanHash",H.meanHash).orWhere("AssetFile.sha",q)))}D&&(O=O.select((0,S.knex)().raw("AssetFile.*"),(0,S.knex)().raw("Asset.*"))),O=(0,h.notBlank)(k)?O.andWhere((0,S.knex)().raw(k)):T.Asset.shownUnhidden(O),!0===t.primary&&(O=O.andWhere("AssetFile.shown",1)),!1===t.primary&&(O=O.andWhere("AssetFile.shown",0)),(0,p.gt0)(t.limit)&&(O=O.limit(t.limit));const L=(0,h.toNotBlank)(t.order)??"uri",R=null!=i?(0,E.queryStringToSql_)(i,O).orderByRaw(L):O,N=(0,P.toSqlQuery)(R);A.info("Running SQL query...",{sq:N});const B=Date.now(),j=F.prepare(N.sql).iterate(N.bindings);A.info("query took "+(Date.now()-B)+"ms"),x&&console.log("[");let z=!0;for(const G of j){A.throwIfAborted_();const $=await(0,c.uri2nativePath)(G.uri,G.mountpoint);x?(z||process.stdout.write(","),process.stdout.write((0,m.stringify)({path:$,...(0,g.omit)(G,"id")}))):null==$?console.error("Failed to decode URI to native path: ",(0,m.stringify)(G)):I([$??G.uri]),z=!1}x&&console.log("]")}catch(J){await(0,s.exit)({error:J})}finally{await(0,s.exit)({status:0})}}()},43487:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(48884),c=i(19851),d=i(50213),h=i(88158),f=i(45393),m=i(56519),p=i(89724),g=i(38835),y=i(74128),w=i(79847),v=i(28874),b=i(47783),S=i(38010),P=i(40958),T=i(76790),_=i(75761),M=i(38639),E=i(11371),D=i(98553),x=i(55835),k=i(31586),C=i(20214),F=i(59455),A=i(64526),I=i(4407),O=i(54017),L=i(48722),R=i(37094),N=i(45295),B=i(39604),j=i(48723),z=i(41507),V=i(72761),W={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class U extends V.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,b.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,M.isTrue)(t.shown)})}const t=R.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(W):e.andWhere(W)}static findUnhiddenById(e){return(0,k.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return A.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{unlinkAssetFiles:i});const l=n.getAssetFiles({refresh:!0});if(t){(0,B.upsertToShaBlockslist)(...l.map((e=>e.sha)));for(const e of l)(0,y.syncReport)().onProgress({from:"Asset.remove",path:await e.getNativePath()??e.uri,state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}N.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),R.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&j.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,w.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(N.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,x.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,k.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,k.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,L.toAssetId)(this)}renderCaption(e){return(0,x.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:j.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,P.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return j.Tag.ops().all(j.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??N.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:j.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:j.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,P.uniq)((0,F.toA)(e.tagIdsToAdd).filter((e=>(0,k.gt0)(e)&&!t.includes(e)))),r=(0,P.uniq)((0,F.toA)(e.tagIdsToRemove).filter((e=>(0,k.gt0)(e)&&t.includes(e))));if((0,P.isEmpty)(i)&&(0,P.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&j.Tag.deltaAssetCountAndAncestors(t,-1),(0,P.isEmpty)(i)||N.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,P.isEmpty)(r)||N.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,P.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&j.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,z.coalesceStreams)((0,P.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,T.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,M.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,k.gt0)(this.id)&&(0,k.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,D.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,M.isTrue)(e.shown)))??this.getAssetFiles({refresh:!0})?.find((e=>(0,M.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,_.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,E.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,_.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,_.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,F.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,x.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,k.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,M.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=U,s=U,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("Asset.version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},U.$tableName="Asset",U.$uniqueColumnName="id",U.$booleanFields=["shown","hidden"]},54017:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(76760),o=i(19851),l=i(88158),u=i(45393),c=i(68852),d=i(81168),h=i(13991),f=i(54296),m=i(56519),p=i(76490),g=i(89724),y=i(98314),w=i(38835),v=i(8769),b=i(29882),S=i(95696),P=i(62105),T=i(74128),_=i(35721),M=i(69589),E=i(28874),D=i(28544),x=i(16170),k=i(45200),C=i(34238),F=i(87001),A=i(42233),I=i(21404),O=i(40958),L=i(17586),R=i(22573),N=i(38639),B=i(42659),j=i(33374),z=i(50357),V=i(75240),W=i(11371),U=i(55835),q=i(31586),H=i(68708),G=i(34666),$=i(89937),J=i(75020),K=i(64526),Z=i(41844),Y=i(43487),X=i(48723),Q=i(94710),ee=i(72761);class te extends ee.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>C.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=Y.Asset.shownUnhidden(e.q).join("AssetFile","AssetFile.assetId","Asset.id").where("AssetFile.version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("AssetFile.updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("AssetFile.mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("AssetFile.uri",i+"%");return t})).orderBy("AssetFile.id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,A.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,A.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("AssetFile.id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,q.gt0)(e)?te.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,R.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(te.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=te.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=te.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:te.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,H.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith($.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,H.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,U.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,F.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,q.closeTo)(i.mtime,this.mtime,2*B.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return E.Settings.forceSync.valueOrDefault?E.Settings.forceSync.key+"=true":this.version!==u.AssetFileVersion?"AssetFileVersion: "+this.version+" != "+u.AssetFileVersion:this.whyNotMatchesFile(e)}async inSyncWithFile(e){const t=await this.whyNotInSyncWithFile(e);return this.logger().tap({msg:"inSyncWithFile()",result:null==t,meta:{whyNotInSync:t}})}async fileFields_(e){const t=e??await this.posixFile_();return null==t?void 0:await(0,h.assetFileStatFields_)(t)}isInLibrary(){return this.uri.startsWith($.PS_LIBRARY_PROTOCOL)}async isNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){const t=await this.whyNotNoop(e);return this.logger().tap({msg:"isNoop()",result:null==t,meta:{whyNotNoop:t}})}async whyNotNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){if(!0===e.forceSync)return"forceSync is true";if(!(0,q.gt0)(this.id))return"missing .id";if(!(0,q.gt0)(this.assetId))return"missing .assetId";{const e=await this.whyNotInSyncWithFile();if(null!=e)return e}if(await(0,Z.mayCopyAssetsToLibrary)()){const e=K.Library.instanceRequired_().assetFileRepository(),t=e.whyNotCopyFile(await this.posixFile_());if((0,R.blank)(t)&&null==await e.existingLibraryAssetFile(this))return"need to copy into library"}this.syncState=T.AssetFileSyncStates.noop}isVersionUpToDate(){return(0,G.gte)(this.version,u.AssetFileVersion)}async siblingCount(){return te.dbl.pluckFirstf((e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=(0,M.forceContextOrSetting)()){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,q.gt0)(this.id)&&!t.forceSync)return void(null==this.syncState&&(this.upsert(),this.syncState??(this.syncState=T.AssetFileSyncStates.noop)));const i=await this.isFileDeleted();if(!0===i)return this.syncState=T.AssetFileSyncStates.deleted,this.delete(),!0!==t.skipAssetRepair&&Q.Task.addOne("repairAsset",{assetId:this.assetId}),this;if(!1===i){const i=await this.updateFromFile_(e,t);return this.syncState??(this.syncState=null==i?T.AssetFileSyncStates.noop:T.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=T.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,H.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e,t=(0,M.forceContextOrSetting)()){const i=Date.now(),r=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&!0!==t.forceSync&&await this.matchesFile(e))return void r.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=T.AssetFileSyncStates.deleted,void r.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,R.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,H.assignAllFields)(this,(0,H.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=T.SyncFileStates.synced,r.elapsed("finished",Date.now()-i,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,H.assignFields)(this,(0,H.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...te.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,q.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,k.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,R.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,F.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,R.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,R.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+w.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),D.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,j.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,N.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===W.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,v.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=C.URI.parse(this.uri),t=(0,U.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=C.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,L.at)((0,L.at)(e,-1)?.tagPath,-1)}(0,z.eql)(e[0]?.tagPath,[J.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===$.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,L.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===J.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===$.PS_LOCAL_FILE_SCHEME){const t=C.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,H.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,N.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:ie(this.createdAt),updatedAtLocale:ie(this.updatedAt)})))}get isVideo(){return(0,x.isVideoMimeType)(this.mimetype)}}function ie(e){return(0,U.map)(e,(e=>(0,V.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=te,r=new WeakSet,s=function(){if((0,R.blank)(this.uri))return"blank uri";if((0,R.blank)(this.sha))return"blank sha";if(!(0,q.gt0)(this.width))return"missing width";if(!(0,q.gt0)(this.height))return"missing height";if(!(0,q.gt0)(this.capturedAtLocal))return"missing capturedAtLocal";if(!(0,q.gte0)(this.capturedAtPrecisionMs))return"missing capturedAtPrecisionMs";if(E.Settings.useImageHashes.valueOrDefault){const e=[];for(const t of["dctHash","diffHash","meanHash"])(0,R.blank)(this[t])&&e.push(t);if(1===e.length)return"missing image hash: "+e[0];if(e.length>1)return"missing image hashes: "+e.join(", ")}return this.isVersionUpToDate()?void 0:"outdated version"},te.$tableName="AssetFile",te.$uniqueColumnName="uri",te.$booleanFields=["shown"],te.$transientFields=["nativePath","syncState"]},48722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(76596),s=i(31586);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},37094:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},45295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},61204:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(19851),s=i(50213),n=i(97352),a=i(75020),o=i(4407),l=i(48723),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},95700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(19851),s=i(56038),n=i(28874),a=i(42659),o=i(41400),l=i(69032),u=i(61204),c=i(49796);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h());try{await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())}catch{}};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},55046:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(57975),n=i(50213),a=i(7282),o=i(65211),l=i(40958),u=i(38639),c=i(45599),d=i(31586),h=i(68708),f=i(34666),m=i(54993),p=i(57038),g=i(94448),y=i(33572),w=i(63872);class v{constructor(){this.$instanceId=(0,a.isTest)()?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new w.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if((0,a.isProd)())throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}update(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("update()",{self:this.toJSON()}),this.class().ops().updateOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=v,r=v,v.$schema="models",v.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),v.db=g.modelDb,v.$pkColumnNames=["id"]},94448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},33572:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(50213),s=i(40958),n=i(22573),a=i(38639),o=i(97790),l=i(51926),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},63872:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(48884),m=i(19851),p=i(50213),g=i(81168),y=i(48299),w=i(12943),v=i(38835),b=i(34102),S=i(28874),P=i(40958),T=i(76790),_=i(22573),M=i(50357),E=i(96249),D=i(98553),x=i(55835),k=i(31586),C=i(68708),F=i(59455),A=i(86859),I=i(33572);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,I.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new A.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,k.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,x.mapOr)(this.db(),(e=>e.isOpen),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,w.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,F.toA)(e).filter(k.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,T.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,k.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,F.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+v.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+v.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,k.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,x.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+v.NonRetriableErrorFlag+v.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);if(null==s)return;return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){const t=[],i=this.allf((i=>{for(const r of e){const e=this.model.hasId(r)?this.model.pickId(r):this.$pickModelUcn(r);null!=e?(t.push([r,e]),i=i.orWhere(e)):h(this,s,"f").warn("reload(): given insufficient partial model",{fragment:r})}return i})),n=[];for(const[e,a]of t){const t=i.find((e=>(0,M.eqlSubset)(a,e)));if(null==t)h(this,s,"f").warn("reload(): failed to find result in db",{prior:e,dbArr:i});else{const i=h(this,r,"m",u).call(this,e);h(this,r,"m",l).call(this,i,t),i!==e&&h(this,r,"m",l).call(this,i,t),n.push(t)}}return n}upsert(e){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const t=this.columnNames(),i=[];for(const s of(0,f.batches)((0,F.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=new Map,n=new Set,a=(0,P.compact)(s.map((e=>this.fromJSON(e))));for(const t of a){const i=(0,D.stringify)(this.$pickModelUcn(t));e.set(i,t),this.model.hasId(t)||n.add(i),t.$beforeUpsert()}h(this,r,"m",c).call(this,a.map((e=>e.$toDbJSON(t))));const o=this.reload(a),l=new Map(o.map((e=>[(0,D.stringify)(this.$pickModelUcn(e)),e])));for(const e of a){const t=(0,D.stringify)(this.$pickModelUcn(e)),r=l.get(t)??e;n.has(t)&&r.$afterInsert(),r.$afterUpsert(),i.push(r)}}return i}delete(e){const t=(0,F.toA)(e).filter(k.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},49796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.toPct=void 0;const r=i(48161),s=i(1708),n=i(48884),a=i(50213),o=i(28874),l=i(40958),u=i(42659),c=i(45599),d=i(98553),h=i(55835),f=i(31586),m=i(68708),p=i(67478),g=i(51926),y=i(59455),w=i(54993),v=i(76386),b=i(33572),S=i(55009),P=i(72761),T=(0,c.defer)((()=>(0,a.mkLogger)("model.Progress")));function _(e){return null==e||!(0,f.isNumber)(e)||e<0||e>100?void 0:(0,f.sigFigs)(e,3)}t.toPct=_;const M=(0,g.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function E(){const e=o.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*u.dayMs}t.defaultMinCreatedAt=E;class D extends P.TimestampedModel{static vacuum(e=o.Settings.progressRetentionDays.valueOrDefault*u.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t)));for(const e of(0,n.batches)(i,o.Settings.dbBatchSelectSize.valueOrDefault))S.ProgressMeta.dbl.runf((t=>t.whereIn("progressId",e).delete())),D.dbl.runf((t=>t.whereIn("id",e).delete()))}static countCompletedDirectorySyncs(){return this.dbl.pluckFirstf((e=>e.where({state:"done"}).whereNotNull("completedAt").where("uri","like","ps%")))}static times(){return T().tap({msg:"times()",result:this.dbl.all({sql:M})})}static insertNew(e){const t=(0,h.map)(e.dek,d.stringify);return this.ops().insertOne({...(0,m.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&this.assignFromPojo(e),super.upsert()}$beforeUpsert(){super.$beforeUpsert(),null==this.id&&(this.pid??(this.pid=s.pid),this.hostname??(this.hostname=(0,r.hostname)())),"done"===this.state&&(this.completedAt??(this.completedAt=Date.now())),this.completePct=_(this.completePct),this.incompletePct=_(this.incompletePct),this.scanningPct=_(this.scanningPct)}$afterUpsert(){super.$afterUpsert(),(0,v.tellWebProgressUpdated)()}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,l.compactBlanks)((0,p.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,d.stringify)((0,l.compactBlanks)((0,y.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,m.omit)(e,"volume","uri"))}getMeta(){return S.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncomplete(e=E()){return this.logger().tap({msg:"priorIncompleteProgress()",result:D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc")))})}getLastCompletedAt(e=E()){return D.dbl.pluckFirstf((t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e)))}getLastIncompleteStartAt(){return D.dbl.pluckFirstf((e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0)))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),S.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,l.diff)(t.map((e=>e.name)),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),S.ProgressMeta.ops().upsert((0,m.entries)(e).map((([e,t])=>({progressId:this.id,name:e,value:(0,w.toS)(t)})))),(0,l.isNotEmpty)(i)&&S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).whereIn("name",i).delete()))}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),S.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,m.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},55009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},39604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(19851),s=i(50213),n=i(95696),a=i(40958),o=i(22573),l=i(86859),u=i(94448),c=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),d=(0,r.lazy)((()=>new l.DbRequest(u.modelDb,"ShaBlocklist")));function h(e){return null!=(0,u.modelDb)()&&!(0,o.blank)(e)&&c().tap({msg:"isShaBlockslisted",result:null!=d().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}function f(...e){if(null==u.modelDb.prior())return;const t=(0,a.uniq)(e).map((e=>({sha:e})));return(0,a.isEmpty)(t)?void 0:d().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,u.modelDb)())return null;const t=h(await n.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=h,t.upsertFileToShaBlockslist=async function(e){if(null==(0,u.modelDb)())return;const t=await n.PosixFile.for(e).sha();return null==t?void 0:f(t)},t.upsertToShaBlockslist=f},48723:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(56038),o=i(34102),l=i(19851),u=i(50213),c=i(36372),d=i(97352),h=i(28874),f=i(81168),m=i(42231),p=i(75020),g=i(40958),y=i(22573),w=i(42659),v=i(41400),b=i(50357),S=i(55835),P=i(31586),T=i(34666),_=i(20214),M=i(51926),E=i(59455),D=i(12168),x=i(6186),k=i(57038),C=i(21074),F=i(7656),A=i(43487),I=i(48722),O=i(45295),L=i(98784),R=i(41507),N=i(72761),B=4*w.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,v.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,M.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:A.Asset.dbl.pluckFirst(A.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset(),this.ops().clearDbCache()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{r.clear();for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.update({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,k.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,M.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:F.RecursiveAssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),this.ops().upsertOne(i)}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,k.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return A.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();return(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)})),r.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,M.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(A.Asset.dbl.all(t).map(I.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return A.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,M.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:F.RecursiveAssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?A.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(A.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(I.toAssetId))));for(const t of r)t.assetIdA.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(this.id??0),"Asset.id",i)).limit(t))).map(I.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!0,z.cmp=(e,t)=>(0,T.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=A.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(x.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e}),B);const V=(0,l.lazy)((()=>A.Asset.dbl.pluckFirstf((e=>e.count()))),w.minuteMs)},98784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(38156),s=i(3127),n=i(40958),a=i(41400),o=i(94715),l=i(55046),u=i(48723);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=new r.PushProgressObserver({op:"Rebuilding tag search index"},u.Tag.dbl.pluckFirstf((e=>e.count("*")))),t=this.dbl.db();o.Migrations.create_tag_fts(t.db),await u.Tag.ops().batched({qb:e=>e,onResults:t=>(this.$logger().throwIfAborted_(),this.insertFts(t),e.incrProgress(t.length),(0,a.delay)(1))}),e.completed()}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},41507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},94710:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Task=t.StaleTaskError=t.InvalidTaskError=t.TaskNames=t.Tasks=t.testTask=void 0;const c=i(78474),d=i(22454),h=i(23560),f=i(12089),m=i(76740),p=i(22911),g=i(99331),y=i(31562),w=i(38835),v=i(70025),b=i(8769),S=i(74128),P=i(28874),T=i(37692),_=i(40958),M=i(22573),E=i(42659),D=i(45599),x=i(98553),k=i(49769),C=i(68708),F=i(50989),A=i(59455),I=i(58723),O=i(34274),L=i(90901),R=i(61989),N=i(93755),B=i(69032),j=i(55046);t.testTask=(0,f.shim1)({name:"testTask",impl:async e=>{}}),t.Tasks={applyDeleted:I.applyDeleted,applyExcluded:I.applyExcluded,runTagMaintenance:B.runTagMaintenance,updateAssetFile:N.updateAssetFile_,repairAsset:async function(e){e.forceSync=!0,e.skipPreviews=!0,e.skipAssetTagging=!0;const t=await(0,R.updateAsset_)(e);return(0,_.isNotEmpty)(t?.assetIdsToUpdate)&&q.add(t?.assetIdsToUpdate.map((t=>({fn:"repairAsset",args:{...e,assetId:t},priority:W.repairAsset+1})))),null!=t&&!0!==t.deleted&&(0,M.blank)((0,A.toA)(t.rejected).join(""))&&(0,M.blank)(t.error)&&q.addOne("assetPostUpsertTasks",(0,C.omit)(e,"skipPreviews","skipAssetTagging")),t},assetPostUpsertTasks:L.assetPostUpsertTasks,syncFile:O.importFileToResult_,testTask:t.testTask},t.TaskNames=(0,F.strEnum)(...(0,C.keys)(t.Tasks));class z extends Error{}t.InvalidTaskError=z;class V extends Error{}t.StaleTaskError=V;const W={applyDeleted:16,applyExcluded:16,runTagMaintenance:14,updateAssetFile:13,repairAsset:12,assetPostUpsertTasks:10,syncFile:0,testTask:-1},U=["repairAsset"];class q extends j.Model{constructor(){super(...arguments),r.add(this),o.set(this,(0,D.defer)((()=>new m.Abortable)))}static countTaskNames(){const e={};for(const t of s.dbl.allf((e=>e.select("fn").count().groupBy("fn"))))e[t.fn]=t["count(*)"];return e}static orderBy(e){return e.orderBy([{column:"priority",order:"desc"},{column:"retries",order:"desc"},{column:"id",order:"asc"}])}static count(){return s.dbl.pluckFirstf((e=>e.count("id")))}static freeSlots(){return P.Settings.taskListCap.valueOrDefault-s.count()}static countByFn(e){return s.dbl.pluckFirstf((t=>t.where({fn:e}).count("id")))}static nextByFn(e,t=(e=>e)){return s.ops().allf((i=>s.orderBy(t(i.where({fn:e})))))}set args(e){this.argsJSON=(0,x.stringify)(e)}get args(){const e=(0,x.parseJSON)(this.argsJSON);return(0,C.notEmptyObj)(e)&&(e.halt=u(this,o,"f").call(this)),e}get isSerial(){return U.includes(this.fn)}toString(){return`Task#${this.fn}(${this.argsJSON})`}static addOne(e,t){return s.add([{fn:e,args:t}])[0]}static add(e,t=!1){if((0,_.isEmpty)(e))return[];const i=s.ops().upsert(e.map((e=>({fn:e.fn,argsJSON:(0,x.stringify)(e.args)})),t));return s.ee.emit("added",i),(0,h.isTaskListManager)()||(0,T.addStateEvent)("checkTasks"),i}$beforeUpsert(){this.priority??(this.priority=W[this.fn]),this.retries??(this.retries=P.Settings.maxRetries.valueOrDefault)}donePromise(){return(0,h.isTaskListManager)()?(0,k.getOrSet)(u(s,s,"f",n),this.id,(()=>new p.Deferred(this.toString(),{payload:this}))):(0,y.untilTrue)((()=>null==s.ops().findById(this.id)),{intervalMs:E.secondMs})}abort(e){this.logger().warn("aborting task",{reason:e,task:this}),u(this,o,"f").call(this).abort(e),this.delete(),(0,M.blank)(this.args.path)||(0,S.syncReport)().onProgress({path:this.args.path,from:this.fn,state:S.SyncFileStates.failed,details:e})}async _run(){if(this.retries<0)throw this.logger().warn(".run(): too many retries"+w.InternalErrorFlag,{job:this}),this.delete(),new z;if(!u(this,r,"m",l).call(this))throw this.logger().warn(".run(): someone already started this task",{job:this}),new V;try{const e=Date.now(),i=await t.Tasks[this.fn](this.args);return this.logger().throwIfAborted_(u(this,o,"f").prior()),s.taskResolvedCounts.incr(this.fn),s.ee.emit("resolved",this,i,Date.now()-e),this.delete(),u(s,s,"f",n).get(this.id)?.resolve(i),i}catch(e){if((0,g.ending)())throw this.logger().info("task failed, but we're ending. We'll leave it for next time.",{task:this}),e;throw s.taskRejectedCounts.incr(this.fn),(0,v.isRedoableError)(e)?(this.retries++,this.priority--,this.upsert()):!0===(0,v.isRetriableError)(e)&&this.retries>=0?this.logger().warn("run failed, but we can retry it later",{task:this,error:e}):(s.ee.emit("rejected",this,e),this.delete(),u(s,s,"f",n).get(this.id)?.reject(e),(0,b.onError)(this.toString()+" failed",e)),e}finally{u(s,s,"m",a).call(s)}}}t.Task=q,s=q,o=new WeakMap,r=new WeakSet,a=function(){for(const[e,t]of u(this,s,"f",n).entries())t.isSettled&&u(this,s,"f",n).delete(e)},l=function(){const e=this.retries;if(1===s.dbl.runf((t=>t.where({id:this.id,retries:e}).update({retries:e-1}))).changes)return--this.retries,!0;{const e=this.toJSON(),t=this.reload();return this.logger().warn(".#decrRetries(): someone already started this task",{before:e,reloaded:t}),!1}},q.$tableName="Task",q.$uniqueColumnName="fn,argsJSON",q.$useCache=!1,q.taskResolvedCounts=new d.CountingSet,q.taskRejectedCounts=new d.CountingSet,q.ee=new c.EventEmitter,n={value:new Map}},72761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),this.createdAt??(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},58723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyExcluded=t.applyDeleted=void 0;const r=i(50213),s=i(43487),n=(0,r.mkLogger)("ops.ApplyRemovable");async function a(e,t,i){const r=e?"Deleting":"Excluding",a=e?"deletedAt":"excludedAt";await s.Asset.dbl.batched({qb:e=>e.select("id").where("shown",0).andWhere(a,"<=",t),onResults:async t=>{for(const a of t){n.throwIfAborted_(i);try{await s.Asset.remove({assetId:a,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){n.error(r+" failed",{assetId:a,error:e})}}}})}t.applyDeleted=function(e){return a(!0,e.createdAt,e.halt)},t.applyExcluded=function(e){return a(!1,e.createdAt,e.halt)}},76386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)((()=>(0,s.mkLogger)("progress.Progress")));t.ProgressRateMs=(0,r.lazy)((()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:1.5))),t.tellWebProgressUpdated=(0,r.lazy)((async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch((e=>h().warn(".tellWebProgressUpdated: failed",{error:e})))}),(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},44694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryTermToFuzzyDate=void 0;const r=i(98725),s=(0,i(19851).lazy)((()=>new r.FuzzyDateParser({fuzzyDateParsing:!0,fuzzyYearParsing:!0})));t.queryTermToFuzzyDate=function(e){return s().parse(e)}},43786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToString=t.NormieQuerySymbols=t.SetQuerySymbols=t.isTrueTerm=t.flatTerms=t.findTerm=t.hasNsTerm=t.isQuery=t.isClause=t.isAndClause=t.isOrClause=t.isTerm=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(51926),o=i(54993);function l(e){return"object"==typeof e&&(0,s.notBlank)(e.term)&&(null==e.not||"boolean"==typeof e.not&&(null==e.ns||(0,a.isString)(e.ns)))}function u(e){return"object"==typeof e&&Array.isArray(e.queries)}function c(e){return"or"===e?.type&&u(e)}function d(e){return"and"===e?.type&&u(e)}function h(e){return d(e)||c(e)}function f(e,t){if(l(e))return t(e)?e:void 0;for(const i of e.queries){const e=f(i,t);if(null!=e)return e}}t.isTerm=l,t.isOrClause=c,t.isAndClause=d,t.isClause=h,t.isQuery=function(e){return l(e)||h(e)},t.hasNsTerm=function(e,t){return null!=f(e,(e=>e.ns===t))},t.findTerm=f,t.flatTerms=function e(t){return l(t)?[t]:(0,r.flatMap)(t.queries,e)},t.isTrueTerm=function(e){return(0,n.isTrue)(e?.not)?(0,n.isFalse)(e?.term):(0,n.isTrue)(e?.term)},t.SetQuerySymbols={not:"¬",and:"∧",or:"∨"},t.NormieQuerySymbols={not:"-",and:"AND",or:"OR"},t.queryToString=function e(i,r=t.SetQuerySymbols){if(null==i)return"";if(l(i)){let e=i.term;return null==i.term.match(/^[a-z]+$/i)&&(e='"'+e.replace(/"/g,'\\"')+'"'),`${(0,n.isTrue)(i.not)?r.not:""}${null==i.ns?"":i.ns+":"+(0,o.toS)(i.op)}${e}`}return"("+i.queries.map((t=>e(t,r))).join(` ${"or"===i.type?r.or:r.and} `)+")"}},7573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeTerm=t.isAssetTerm=t.AssetTermNs=t.AssetTermDateNs=t.AssetTermBoolNs=t.normalizeQuery=void 0;const r=i(48884),s=i(75020),n=i(40958),a=i(76790),o=i(22573),l=i(38639),u=i(50989),c=i(54993),d=i(44694),h=i(43786);function f(e){return(0,a.sortBy)((0,n.uniqBy)(e,h.queryToString),(e=>[(0,h.isTerm)(e)?0:(0,h.isOrClause)(e)?1:2,(0,h.queryToString)(e).replace(/[¬(]+/g,"")]))}t.normalizeQuery=function e(t){if((0,h.isTerm)(t))return g(t);const i=t.queries.map(e);if(0===i.length)throw new Error("empty query");if(1===i.length)return i[0];const[s,n]=(0,r.partition)(i,h.isTerm),[a,o]=(0,r.partition)(n,(e=>e.type===t.type));for(const e of a)s.push(...e.queries);const l={type:t.type,queries:f([...s,...o])};return l.queries.every((e=>(0,h.isTerm)(e)&&e.not))?e({type:"and"===t.type?"or":"and",queries:f(l.queries.map((e=>({...e,not:!1}))))}):l},t.AssetTermBoolNs=(0,u.strEnum)("deleted","excluded","liked","hidden"),t.AssetTermDateNs=(0,u.strEnum)("date","updated");const m={delete:t.AssetTermBoolNs.deleted,trash:t.AssetTermBoolNs.deleted,trashed:t.AssetTermBoolNs.deleted,exclude:t.AssetTermBoolNs.excluded,remove:t.AssetTermBoolNs.excluded,removed:t.AssetTermBoolNs.excluded,like:t.AssetTermBoolNs.liked,fav:t.AssetTermBoolNs.liked,fave:t.AssetTermBoolNs.liked,faved:t.AssetTermBoolNs.liked,favorite:t.AssetTermBoolNs.liked,favourite:t.AssetTermBoolNs.liked,hide:t.AssetTermBoolNs.hidden,archive:t.AssetTermBoolNs.hidden,archived:t.AssetTermBoolNs.hidden},p={kw:s.TagRoots.Keywords,keyword:s.TagRoots.Keywords,keywords:s.TagRoots.Keywords,dir:s.TagRoots.fs,directory:s.TagRoots.fs,folder:s.TagRoots.fs};function g(e){if((0,o.blank)(e.ns)&&null!=e.term.match(/^\d{4}[-\d]*$/)&&null!=(0,d.queryTermToFuzzyDate)(e.term))return{ns:"date",term:e.term};if("when"===(0,c.toS)(e.ns).toLowerCase())return g({...e,ns:t.AssetTermDateNs.date,term:e.term.replace(/\//g,"-")});let i=(0,o.notBlankOr)(e.ns,e.term).toLowerCase();if(i=m[i]??i,t.AssetTermBoolNs.includes(i)){let t=!(0,l.isFalse)(e.term);return!0===e.not&&(t=!t),{ns:i,term:(0,c.toS)(t)}}if(t.AssetTermNs.includes(i))return{...e,ns:i};if("before"===i||"after"===i){if(null!=e.op)throw new Error(i+": doesn't support operators");const r="after"===i&&!0!==e.not||!0===e.not;return{ns:t.AssetTermDateNs.date,op:r?">":"<",term:e.term}}return i!==e.term.toLowerCase()?{not:e.not,op:e.op,ns:p[i]??i,term:e.term}:e}t.AssetTermNs=(0,u.strEnum)(...t.AssetTermDateNs.values,...t.AssetTermBoolNs.values),t.isAssetTerm=function(e){return(0,h.isTerm)(e)&&t.AssetTermNs.includes(g(e).ns)},t.normalizeTerm=g},33693:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseQuery_=void 0;const s=r(i(31704)),n=i(19851),a=i(50213),o=i(7282),l=i(38835),u=i(31586),c=r(i(70471)),d=(0,n.lazy)((()=>(0,a.mkLogger)("query.QueryParser")));t.parseQuery_=function(e){try{const t=new s.default.Parser(s.default.Grammar.fromCompiled(c.default)).feed(e.trim()).finish();if(t.length>1&&!(0,o.isProd)()&&d().throw("parseQuery(): ambiguous grammar!",{input:e}),null==t[0])throw new Error("invalid query");return d().debug("parseQuery()",{input:e,result:t[0]}),t[0]}catch(t){const i=t.token?.col,r=`Query syntax error${(0,u.gt0)(i)?" around column "+i:""}: "${e}"`;throw d().warn("parseQuery(): bad query",{msg:r,err:t}),new Error(r+l.NonRetriableErrorFlag+l.DoNotSendErrorFlag)}}},23523:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToSql=t.queryStringToSql_=t.defaultAssetQuery=void 0;const r=i(19851),s=i(50213),n=i(66649),a=i(89724),o=i(70417),l=i(28874),u=i(42231),c=i(22573),d=i(38639),h=i(98553),f=i(54993),m=i(57038),p=i(43487),g=i(44694),y=i(43786),w=i(7573),v=i(33693),b=(0,r.lazy)((()=>(0,s.mkLogger)("query.QueryToSql")));function S(e,t,i){if((0,y.isTerm)(t))return function(e,t,i){return(0,w.isAssetTerm)(t)?function(e,t){switch(t.ns){case w.AssetTermNs.date:case w.AssetTermNs.updated:return function(e,t){const i=t.op??"=",r="date"===t.ns?"Asset.capturedAtLocal":"updated"===t.ns?"Asset.updatedAt":void 0;if(null==r)throw new Error("internal error: unexpected namespace for "+(0,h.stringify)(t));const s="Asset.updatedAt"===r?n.datedToMillis:a.maybeDatedToLocal,l=(0,g.queryTermToFuzzyDate)(t.term),u=s(l),c=l?.following()?.toDateTime(),d=s(c?.minus({second:1})),f=(0,o.max)([u,d]);if(null==l||null==u||null==f)throw new Error((0,y.queryToString)(t,y.NormieQuerySymbols)+" can't be parsed as a date");if("="===i)return e.whereBetween(r,[u,f]);if("<"===i)return e.where(r,i,u);if("<="===i)return e.where(r,i,f);if(">="===i)return e.where(r,i,u);if(">"===i)return e.where(r,i,f);throw new Error("internal error: unexpected op for "+(0,h.stringify)(t))}(e,t);case w.AssetTermNs.hidden:return e.where("Asset.hidden",T(t));case w.AssetTermNs.excluded:return M({qb:e,column:"Asset.excludedAt",whereNull:0===T(t)});case w.AssetTermNs.deleted:return M({qb:e,column:"Asset.deletedAt",whereNull:0===T(t)});case w.AssetTermNs.liked:return e.where("Asset.rating",P(t)?">=":"<",l.Settings.likeRating.valueOrDefault);default:throw new Error("not asset term:"+(0,y.queryToString)(t))}}(e,t):function(e,t,i){const r=t.term.startsWith("/"),s="="===t.op,n=function(e,t){if(null==t||"fs"!==e.ns)return e.term;const i=e.term.split("/"),r=i.findIndex(c.notBlank);if(-1===r)return e.term;const s=i[r];return i[r]=t.get(s)??s,i.join("/")}(t,i);if(r||s)return e.whereIn("Asset.id",(0,m.knex)()("AssetTag").join("Tag","Tag.id","AssetTag.tagId").select("assetId").whereLike("Tag._path",t.ns+(r?"":"%")+n.replace(/\//g,u.TagSep).replace(/\*/g,"%")+u.TagSep+(s?"":"%")));let a=(0,m.knex)()("AssetTag").join("tag_fts","tag_fts.rowid","AssetTag.tagId").select("assetId");const o="path:"+_(n.replace(/\//g," + "));if((0,c.blank)(t.ns)){if((0,d.isTrue)(t.not))throw new Error("Cannot negate without a namespace ("+(0,y.queryToString)(t)+")");a=a.where("tag_fts","MATCH",o)}else a=a.where("tag_fts","MATCH","(root:"+_(t.ns)+((0,d.isTrue)(t.not)?" NOT ":" AND ")+o+")");return e.whereIn("Asset.id",a)}(e,t,i)}(e,t,i);for(const r of t.queries)e=(0,y.isAndClause)(t)?e.andWhere((e=>S(e,r,i))):e.orWhere((e=>S(e,r,i)));return e}function P(e){const t=(0,d.isTrue)(e.term);return!0===e.not?!t:t}function T(e){return P(e)?1:0}function _(e){return e.includes("*")?e.split("*").map(_).join(" * "):`"${(0,f.toS)(e).replace(/"/g,'""')}"`}function M({qb:e,column:t,whereNull:i}){return i?e.whereNull(t):e.whereNotNull(t)}function E(){return p.Asset.ops().query().where("Asset.shown",1).join("AssetTag","AssetTag.assetId","Asset.id")}function D(e,t=E(),i){return e=(0,w.normalizeQuery)(e),(0,y.hasNsTerm)(e,w.AssetTermBoolNs.hidden)||(0,y.hasNsTerm)(e,w.AssetTermBoolNs.excluded)||(0,y.hasNsTerm)(e,w.AssetTermBoolNs.deleted)||(t=t.andWhere({"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null})),t.andWhere((t=>S(t,e,i)))}t.defaultAssetQuery=E,t.queryStringToSql_=function(e,t=E()){const i=(0,v.parseQuery_)(e);return null==i?(b().warn("assetQuery("+e+"): parsed to null"),t):D(i,t)},t.queryToSql=D},70471:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};function s(e){return e[0]}Object.defineProperty(t,"__esModule",{value:!0}),t.parseTerm=void 0;const n=r(i(80265)),a=i(40958),o=i(54993);function l(e){if(null==e[0]&&["and","or"].includes((0,o.toS)(e[1]).toLowerCase()))throw new Error("Unmatched "+e[1]);return{not:null!=e[0]?.[0]?.value,ns:e[0]?.[1]?.value,op:e[0]?.[3]?.value,term:e[1]}}function u(e){return e[0]?.value}t.parseTerm=l;const c=n.default.compile({qstr:[{match:/"(?:[^\\"]|\\.)*?"/,value:e=>e.slice(1,-1).replace(/\\"/g,'"')},{match:/'(?:[^\\']|\\.)*?'/,value:e=>e.slice(1,-1).replace(/\\'/g,"'")}],lp:"(",rp:")",not:/[-¬]/,col:":",op:/<=?|>=?|=/,or:/ +(?:or|OR|Or|∨|\|{1,2}) +/,and:/(?:and|AND|And|∧|\&{1,2}) +/,str:/[^\s:\(\)"'][^\s:\(\)]*/,ws:/ +/}),d={Lexer:c,ParserRules:[{name:"Expression$ebnf$1",symbols:[]},{name:"Expression$ebnf$1$subexpression$1",symbols:[c.has("or")?{type:"or"}:or,"Clause"]},{name:"Expression$ebnf$1",symbols:["Expression$ebnf$1","Expression$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Expression",symbols:["Clause","Expression$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[1]))]);return 1===t.length?t[0]:{type:"or",queries:t}}},{name:"Clause$ebnf$1",symbols:[]},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("and")?{type:"and"}:and],postprocess:s},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Clause$ebnf$1$subexpression$1",symbols:["__","Clause$ebnf$1$subexpression$1$ebnf$1","Factor"]},{name:"Clause$ebnf$1",symbols:["Clause$ebnf$1","Clause$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Clause",symbols:["Factor","Clause$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[2]))]);return 1===t.length?t[0]:{type:"and",queries:t}}},{name:"Factor",symbols:["Term"],postprocess:s},{name:"Factor",symbols:[c.has("lp")?{type:"lp"}:lp,"_","Expression","_",c.has("rp")?{type:"rp"}:rp],postprocess:function(e){const t=(0,a.compact)(e[2]);return 1===t.length?t[0]:t}},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("not")?{type:"not"}:not],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[c.has("op")?{type:"op"}:op],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1",symbols:["Term$ebnf$1$subexpression$1$ebnf$1",c.has("str")?{type:"str"}:str,c.has("col")?{type:"col"}:col,"Term$ebnf$1$subexpression$1$ebnf$2"]},{name:"Term$ebnf$1",symbols:["Term$ebnf$1$subexpression$1"],postprocess:s},{name:"Term$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term",symbols:["Term$ebnf$1","Value"],postprocess:l},{name:"Value",symbols:[c.has("qstr")?{type:"qstr"}:qstr],postprocess:u},{name:"Value",symbols:[c.has("str")?{type:"str"}:str],postprocess:u},{name:"_$ebnf$1",symbols:[c.has("ws")?{type:"ws"}:ws],postprocess:s},{name:"_$ebnf$1",symbols:[],postprocess:()=>null},{name:"_",symbols:["_$ebnf$1"]},{name:"__",symbols:[c.has("ws")?{type:"ws"}:ws]}],ParserStart:"Expression"};t.default=d},3996:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const a=i(19851),o=i(50213),l=i(79781),u=i(56519),c=i(56038),d=i(59189),h=i(38835),f=i(95696),m=i(48368),p=i(181),g=i(69589),y=i(28874),w=i(28544),v=i(47783),b=i(87001),S=i(40958),P=i(76790),T=i(22573),_=i(42659),M=i(55835),E=i(31586),D=i(43487),x=i(54017);t.isFileInSync=async function(e){return new C(f.PosixFile.for(e)).alreadySynced()};const k=new d.SerialLaterQueue;class C{constructor(e,t=(0,g.forceContextOrSetting)()){this.file=e,this.ctx=t,r.set(this,void 0),this.rejectedAssetIds=new Set,this.rejectedSiblingIds=new Set,this.alreadySynced=(0,c.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>n(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,c.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new x.AssetFile).updateFromFile_(this.file);return null==e?n(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,a.lazy)((async()=>{const e=await(0,v.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,a.lazy)((()=>y.Settings.useImageHashes.valueOrDefault?(0,m.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,a.lazy)((()=>(0,u.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,a.lazy)((async()=>{const e=await this.capturedAt_();return n(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,c.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,T.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return n(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await k.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return n(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new D.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,c.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,p.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtAndImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,c.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return n(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;n(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw n(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),s(this,r,(0,o.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f")}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),n(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}n(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(e=this.file){const t=await e.uri_();if(null!=t)return x.AssetFile.ops().firstf((e=>e.whereIn("uri",[...(0,b.uriEncodingVariants)(t),this.file.fileuri()])));n(this,r,"f").warn("byUri() uri is null",{file:e})}async assetByNormalizedPathUri(){const e=await this.file.normalize();return e.nativePath===this.file.nativePath?void 0:(await this.byUri(e))?.getAsset()}async assetBySha(){const e=await this.file.sha_();return D.Asset.findFirstByFile((t=>(t=t.where("AssetFile.sha",e),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds))),this.rejectedSiblingIds.size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),t)))}async assetByCapturedAtAndImageHash(){const e=await this.capturedAt_();if(null==e)return n(this,r,"f").throw("Cannot import, capturedAt is null"+h.InternalErrorFlag);if(y.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(x.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=y.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=x.AssetFile.query();return(0,E.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(_.secondMs,y.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,c.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)n(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(y.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void n(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const a=await this.dominantLabhashes();if((0,S.isNotEmpty)(a)){const t=e.localBoundaries({delta:4*s});if(null==t)n(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",a).orWhereIn("mode1",a).orWhereIn("mode2",a))));if(null!=e)return e}}const o=this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash));if(null!=o)return o;if(y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const r={};for(let e=0;e0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds)));const i=await this.firstSimilarAsset(x.AssetFile.ops().all(t));return null!=i&&n(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const s=(0,P.sortBy)(e.filter((e=>!this.rejectedSiblingIds.has(e.id)&&!this.rejectedAssetIds.has(e.assetId))),(e=>[(0,M.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of s)if(null!=e){await e.getNativePath();const i=x.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const s=(0,l.whyNotSameAsset)(t,e,i);if(null==s)return n(this,r,"f").info("Found sibling AssetFile",e),D.Asset.ops().findById(e.assetId);this.rejectedSiblingIds.add(e.id),n(this,r,"f").debug("Contemporary assetFile not similar: "+s,e?.uri)}}}t.AssetFileFinder=C,r=new WeakMap},34274:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult_=void 0;const u=i(19851),c=i(50213),d=i(73568),h=i(38835),f=i(95696),m=i(62105),p=i(74128),g=i(181),y=i(69589),w=i(28874),v=i(40958),b=i(22573),S=i(38639),P=i(59455),T=i(64526),_=i(19113),M=i(94710),E=i(3996),D=i(90901);t.importFileToResult_=async function(e){const t=T.Library.instanceRequired_();return(0,p.syncReport)().wrap_({path:e.path,from:"AssetFileImporter",fn_:()=>new x(f.PosixFile.for(e.path),t.assetFileRepository(),e).apply_()})};class x{constructor(e,t,i){r.add(this),this.file=e,this.repo=t,this.start=Date.now(),s.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else if(this.ctx.forceFilters||null==await this.prior()){const t=await(0,m.whyRejectFile)(this.file,(0,_.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,s,"f").throwIfAborted_();const i=await this.prior();if((0,v.isNotEmpty)(e)&&null!=i&&(l(this,s,"f").info("Deleting prior AssetFile",{rejected:e,prior:i}),i.delete(),this.ctx.skipAssetRepair?l(this,s,"f").info("Skipping asset repair",{assetId:i.assetId}):(l(this,s,"f").info("Scheduling asset repair",{assetId:i.assetId}),M.Task.addOne("repairAsset",{assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)}))),null!=i){const t=i.getAsset();null!=t?.deletedAt&&e.push("Asset is marked as deleted"),null!=t?.excludedAt&&e.push("Asset is marked as excluded")}if(l(this,s,"f").throwIfAborted_(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,b.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,s,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,s,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,s,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,r,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,s,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new E.AssetFileFinder(e,this.ctx),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=x,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(){l(this,s,"f").throwIfAborted_();const e=await l(this,s,"f").tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if((0,v.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,s,"f").throwIfAborted_();const t=await l(this,s,"f").tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,s,"f").throwIfAborted_();const i=await l(this,s,"f").tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return l(this,s,"f").throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return l(this,s,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,s,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,s,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;await l(this,s,"f").tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault}),l(this,s,"f").throwIfAborted_();try{o=await(0,D.assetPostUpsertTasks_)({asset:a,...this.ctx})}catch(e){e instanceof d.AbortError?l(this,s,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,s,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:r,assetFile:i,asset:a,uri:n,uris:[n,...(0,P.toA)(o?.newAssetFileUris)]}}},41844:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(50213),c=i(74128),d=i(81674),h=i(57902),f=i(4936),m=i(28874),p=i(47783),g=i(14245),y=i(67083),w=i(16170),v=i(54979),b=i(98604),S=i(40958),P=i(22573),T=i(98553),_=i(68708),M=i(89937),E=i(59455),D=i(54017),x=i(94710);t.mayCopyAssetsToLibrary=async function(){return m.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,u.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!0!==m.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,d.l)())return"no active subscription";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(m.Settings.libraryDir.valueOrDefault))return e+" already contained by "+m.Settings.libraryDir.valueOrDefault;const t=await(0,v.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,w.isMimeTypeIncluded)(t,m.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(M.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,E.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(D.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),x.Task.addOne("repairAsset",{assetId:t,forceSync:!0})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,T.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return a.addAssetFile(d),(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,p.readCapturedAt)(e),i=(0,f.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,p.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,p.readTags)(e);if(null!=i){if(m.Settings.writeGeolocationTagsToLibraryCopies.valueOrDefault){const e=(0,g.geolocationToXmp)(i);(0,_.isEmptyObj)(e)||await(0,p.writeTags_)(t,e)}return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred)}this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},90901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const r=i(50213),s=i(92434),n=i(73568),a=i(99331),o=i(39250),l=i(38835),u=i(57159),c=i(48604),d=i(66106),h=i(69589),f=i(40958),m=i(45599),p=i(23838),g=i(31586),y=i(64526),w=i(88224),v=i(43487),b=i(41844),S=i(68640),P=(0,m.defer)((()=>(0,r.mkLogger)("sync-file.AssetPostUpsertTasks"))),T=(0,m.defer)((()=>new o.LastOneInWins("Asset tasks")));async function _(e){const t=e,i=e,r=(0,g.toGt0)(t.asset?.id)??(0,g.toGt0)(i.assetId);if(null==r)throw new Error("assetPostUpsertTasks_(): unexpected null assetId"+l.InternalErrorFlag);const o=(0,h.forceContextOrSetting)(e),m=P().addContext(`.postUpsertAssetTasks_(Asset:${r})`);if(m.abortable=o.halt,o.skipPreviews&&o.skipAssetTagging)return void m.info("skipped (skipPreviews && skipAssetTagging)");const _=t.asset??v.Asset.ops().findById(r);if(null==_)return m.throw("unexpected null asset",{asset:_});try{return await T().enqueue({key:r,abortable:m.abortable,fn:()=>async function(e,t,i){const r=(0,h.forceContextOrSetting)(i),n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted_(),(0,f.isEmpty)(a)&&(await v.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,b.mayCopyAssetsToLibrary)())for(const[t,i]of(0,p.groupBy)(a,(e=>e.sha)).entries()){e.throwIfAborted_();try{for(const r of i)r.isInLibrary()&&await r.exists()&&e.debug("no-op for file SHA: already in library.",{sha:t,uri:r.uri});for(const e of i)if(await e.exists()){const t=await y.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,r);if(null!=t){o.newAssetFileUris.push(t.uri);continue}}}catch(r){e.warn("Failed to copy variation to library, but we'll try to continue",{sha:t,uris:i.map((e=>e.uri)),error:r})}}e.throwIfAborted_();const l=r.skipPreviews?void 0:await(0,S.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...r}),u=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?P().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,s.bestExistingAssetFile)(e.getAssetFiles())}(t,l);if(null==u)return e.throw("null primaryOrShownAssetFile_()",{asset:t});const m=await u.posixFile_();if(!0!==r.skipPreviews&&t.isVideo()){if(null==m)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});o.transcoded=null!=await(0,d.transcode_)(m,c.Previews.instance().ap(n).mp4(),{force:r.forceRebuildPreviews,halt:r.halt})}return e.throwIfAborted_(),t.markShownAndUpsert_(u),r.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,w.tagAndUpsertAsset_)(t),o}(m,_,{...e,...o})})}catch(e){if(e instanceof n.AbortError)return void m.warn("aborted, next caller will clean up my mess",{error:e});const t=[e];if(!(0,a.ending)()){m.error("failed, marking asset unshown",{error:e});try{_.markUnshownAndUpsert()}catch(e){m.error("failed to mark asset unshown",{upsertError:e}),t.push(e)}}throw new u.WrappedError("Failed to post-process assset "+_.id,{causes:t})}}t.assetPostUpsertTasks=function(e){try{return _(e)}catch(e){if(e instanceof n.AbortError)return void P().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=_},61989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset_=t.updateAsset=void 0;const r=i(48884),s=i(50213),n=i(45393),a=i(79184),o=i(79781),l=i(92434),u=i(56519),c=i(70417),d=i(69589),h=i(28874),f=i(40958),m=i(22573),p=i(38639),g=i(50357),y=i(43487),w=i(54017),v=i(3996),b=i(90901);async function S(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,r=(0,s.mkLogger)(`sync-file.UpdateAsset(${i})`);r.abortable=t.halt;const S=y.Asset.ops().findById(i);if(null==S)return r.throw("no such asset");const T=S.getAssetFiles({refresh:!0});if((0,f.isEmpty)(T))return r.warn("No asset files: deleting."),S.delete(),{asset:S,rejected:"Empty asset (no AssetFiles)"};const _=S.$clone(),M=S.getShown()?.$clone();for(const e of T)r.throwIfAborted_(),await e.upsertIfNeeded_(void 0,t);T.some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&S.clear(),await P(r,T);const E=(0,l.sortAssetFiles)(T),D=E?.[0];if((0,f.isEmpty)(E)||null==D)return r.warn("No existing files. Skipping for now."),S.markUnshownAndUpsert(),{asset:S,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!D.isVersionUpToDate())return r.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:D}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${D.id}, could not be updated. Un-showing Asset:${i}`};const x=await D.capturedAt();if(null==x)return r.warn("Best file failed to extract a captured-at",{bestAcceptedAF:D}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${D.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const k=new Set,[C,F]=await(0,u.partitionAsync)(E,(e=>(0,o.isSimilarAssetFile)(e,D)));if(r.throwIfAborted_(),(0,f.isNotEmpty)(F)){const e=await(0,a.aggregateAssetFiles)(F);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});k.add(e.id);for(const i of t)e.addAssetFile(i);w.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),r.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function A(e){return(0,f.uniq)(C.map((t=>t[e])))}const I=await Promise.all(C.map((e=>e.capturedAt()))),O=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,L=I.map((e=>e?.localBoundaries({delta:O}))),R=(0,c.min)(L.map((e=>e?.start)))??x.localBoundaries({delta:O})?.start,N=(0,c.max)(L.map((e=>e?.end)))??x.localBoundaries({delta:O})?.end,B=w.AssetFile.ops().all(w.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${D.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",A("sha")),null==R||null==N?r.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:R,endBoundary:N}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[R,N]),e.orWhereIn("AssetFile.meanHash",A("meanHash")).orWhereIn("AssetFile.diffHash",A("diffHash")).orWhereIn("AssetFile.dctHash",A("dctHash"))))));if(r.throwIfAborted_(),h.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const e=await D.posixFile();if(null==e)r.info("bestAcceptedAF has no posixFile, cannot expand query for fuzzy dates",{bestAcceptedAF:D});else{const i=new v.AssetFileFinder(e,t);for(const e of[...C,...B])i.rejectedAssetIds.add(e.assetId),i.rejectedAssetIds.add(e.id);let s=h.Settings.maxContemporaryAdoptionAssets.valueOrDefault;for(;--s>0;){r.throwIfAborted_();const e=await i.assetByCapturedAtAndImageHash();if(null==e){r.info("allowFuzzyDateImageHashMatches(): no additional assets found to adopt");break}if(r.info("allowFuzzyDateImageHashMatches(): found asset with similar image",{a:e}),null!=e){i.rejectedAssetIds.add(e.id);for(const t of e.getAssetFiles())r.info("found asset file by fuzzy date and image hash",{uri:t.uri,assetId:e.id}),B.push(t),i.rejectedAssetIds.add(t.id)}}}}r.info("asset file candidates for adoption: ",B.map((e=>e.posixPathFromGrandparent)));const j=[];for(const e of B){r.throwIfAborted_();try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,D)&&(r.info("adopting similar asset file",{af:e}),k.add(e.assetId),e.shown=!1,S.addAssetFile(e),e.upsert(),j.push(e))}catch(t){r.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}}r.info("fetched expansion",{retainAFs:C.map((e=>e.id)),rejectAFs:F.map((e=>e.id)),externalAssetFiles:B.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:j.map((e=>e.posixPathFromGrandparent))}),await P(r,[...C,...j]),t.skipPreviews&&t.skipAssetTagging?(r.info("skipping previews and tagging",t),S.upsert()):await(0,b.assetPostUpsertTasks_)({...t,asset:S});const z=!(0,g.eql)(_,S),V=!(0,g.eql)(M,S.getShown()),W=!(z||V||t.forceRebuildPreviews||t.forceSync);return r.tap({msg:"updateAsset() result",level:"info",result:{asset:S,assetIdsToUpdate:Array.from(k),assetFiles:S.assetFiles,skipped:W},meta:{ctx:t,assetChanged:z,primaryAssetFileChanged:V}})}async function P(e,t){const[i,s]=(0,r.partition)(t,(e=>e.isVersionUpToDate()));for(const t of s){e.throwIfAborted_();const r=i.find((e=>e.sha===t.sha));if(null!=r){e.info("backfilling",{sibling:r,dest:t});const i=await t.updateFromShaSibling_(r);null!=i&&i.upsert()}}}t.updateAsset=async function(e){try{const t=await S(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}},t.updateAsset_=S},93755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t.updateAssetFile_=t.updateAssetFile=void 0;const r=i(50213),s=i(92434),n=i(98314),a=i(74128),o=i(69589),l=i(87001),u=i(40958),c=i(22573),d=i(68708),h=i(43487),f=i(54017),m=i(94710);async function p(e){const t=Date.now(),i=e,s=e,n=s.af?.id??i.assetFileId,u=(0,r.mkLogger)(`updateAssetFile(${n})`),d=s.af??f.AssetFile.ops().findById(n);if(null==d)return u.throw("db record not found",{assetFileId:n});const h=await d.posixFile_(),p=(0,o.forceContextOrSetting)(e),w={id:n,assetFileId:n,path:h?.nativePath,uri:d?.uri};if(null==h){const e=["cannot resolve URI"];return(0,c.blank)(d.mountpoint)||e.push("is "+d.mountpoint+" mounted?"),(0,a.syncReport)().onProgress({path:d.uri,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:e.join(": "),state:a.SyncFileStates.skipped}),{...w,error:"file for URI not found"}}const v=await(h?.isDeletedUri(d.uri));if(null==v)return u.info("no-op: file URI points to an unmounted volume",w),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:((0,c.toNotBlank)(d.mountpoint)??"volume")+" is not currently mounted",state:a.SyncFileStates.skipped}),{...w,skipped:!0};const b=e.whyReject??await d.whyRejected();if(v||!(0,c.blank)(b)){const e={...w,rejected:b,deleted:v};return u.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:v?"file no longer exists":"rejected: "+b,state:a.SyncFileStates.deleted}),d.delete(),!0!==p.skipAssetRepair&&m.Task.addOne("repairAsset",{assetId:d.assetId}),e}const S=await h.uri_();if(!await(0,l.uriIsEquivalent)(S,d.uri)){const e=await g(d,S,p);if(null!=e)return{...w,...e}}return!p.forceSync&&await d.matchesFile()?(u.info("no-op: file already matches db record",w),d.touch(),{...w,skipped:!0}):{...w,...await y(d,p)}}async function g(e,t,i){const n=(0,r.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,u.uniq)([...(0,l.uriEncodingVariants)(e.uri),...(0,l.uriEncodingVariants)(t)]);n.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const o=f.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,u.isNotEmpty)(o)){n.warn("Found other AssetFiles with equivalent URIs.",{afIds:o.map((e=>e.id))});const t=[e,...o],r=(0,s.sortAssetFiles)(t);if((0,u.isEmpty)(r))return n.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,d.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const l=t.map((e=>e.id));for(const e of r)if(await e.exists()){f.AssetFile.dbl.runf((t=>t.whereIn("id",l.filter((t=>t!==e.id))).delete()));const r=y(e,i);return h.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,u.uniq)(t.map((e=>e.assetId)))))),r}}n.info("no-op, no duplicate URIs.")}async function y(e,t){const i=Date.now();return null!=await e.upsertIfNeeded_(void 0,t)&&h.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:await e.getNativePath(),elapsedMs:Date.now()-i,from:"updateAssetFileIfNeeded()",state:e.syncState??a.SyncFileStates.unknown}),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await p(e)}catch(t){return{id:e.assetFileId,...e,error:(0,n.errorToS)(t)}}},t.updateAssetFile_=p,t.handleAssetFileUriChange=g,t.updateAssetFileIfNeeded=y},68640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const r=i(99331),s=i(38835),n=i(48604),a=i(50213),o=i(69589),l=i(87001),u=i(40958),c=i(45599),d=i(50357),h=i(31586),f=i(68708),m=i(59455),p=i(43487),g=(0,c.defer)((()=>(0,a.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,m.toA)(e.assetFiles).find((e=>(0,h.gt0)(e.assetId)))?.assetId,i=(0,o.forceContextOrSetting)(e),a=g().addContext(".Asset:"+t);if(i.skipPreviews)return void a.warn("skipPreviews is true: no-op");if(!(0,h.gt0)(t))return a.throw("invalid assetId",{assetId:t});const c=e.asset??p.Asset.ops().findById(t);if(null==c)return a.throw("Asset:"+t+" not found");a.throwIfAborted_(i.halt);try{const e=await c.getExistingAssetFiles();if((0,u.isEmpty)(e))return void a.warn("no existing assetFiles",{asset:c});const r=n.Previews.instance().ap(t),o=await r.readInfo();a.throwIfAborted_(i.halt);const h=await(0,n.buildAssetPreviews_)({...i,assetId:t,assetFiles:e}),m=e.find((e=>e.id===h?.assetFileId))??e.find((e=>(0,l.uriIsEquivalent)(h?.uri,e.uri)));a.info("buildAssetPreviews_()",{result:h,primaryAssetFile:m});const p=await(m?.posixFile_());if(null==m||null==p||!0!==await(p?.exists()))return a.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:h,assetFiles:e.map((e=>(0,f.pick)(e,"id","uri"))),primaryAssetFile:m,primaryPosixFile:p});const g=(0,d.eql)(o,h),y=null==h||g;return{...h,noop:y}}catch(e){throw(0,r.ending)()||(a.warn("Failed to update previews. Un-showing asset "+t,{error:e}),c.markUnshownAndUpsert()),e}}},7656:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.DirectAssetCountForTagQuery=t.RecursiveAssetCountForTagQuery=t.nonLeafTagIds=void 0;const r=i(50213),s=i(56038),n=i(95704),a=i(38156),o=i(42659),l=i(45599),u=i(41400),c=i(31586),d=i(51926),h=(0,l.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function f(e){return e.prepare((0,d.compressWhitespace)("SELECT"," t1.id,"," count(t2.id) AS cnt","FROM"," Tag t1"," JOIN Tag t2 ON t1.id = t2.parentId","GROUP BY"," 1","HAVING"," cnt > 0")).pluck().all()}async function m(e,i=[]){const r=e.prepare(t.RecursiveAssetCountForTagQuery).pluck(),o=e.prepare(t.DirectAssetCountForTagQuery).pluck(),l=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId"),c=new Set(f(e)),d=new a.PushProgressObserver({op:"Rebuilding tag asset counts"},e.prepare("SELECT count(*) FROM Tag").pluck().get());await(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e){const e=!c.has(t);(0,s.timeSync)("db.rebuildTagAssetCounts("+(e?"leaf":"cte")+")",(()=>{const s=(e?o:r).get({tagId:t});l.run({tagId:t,assetCount:s,updatedAt:Date.now()}),d.incrProgress(),h().debug("_rebuildTagAssetCounts()",{isLeaf:e,whereClauses:i,tagId:t,assetCount:s})})),t%10==0&&(h().throwIfAborted_(),await(0,u.delay)(1))}}}),d.completed()}t.nonLeafTagIds=f,t.RecursiveAssetCountForTagQuery=(0,d.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.DirectAssetCountForTagQuery=(0,d.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," AssetTag"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," AssetTag.tagId = :tagId"," AND Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL;"),t.rebuildTagAssetCounts=async function(e,t=o.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>m(e,["assetCount IS NULL"]))),(0,c.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rm(e)))}},69032:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(1728),c=i(56038),d=i(34102),h=i(49076),f=i(69589),m=i(28874),p=i(42231),g=i(85087),y=i(98770),w=i(59107),v=i(63870),b=i(7014),S=i(22573),P=i(42659),T=i(41400),_=i(75240),M=i(31586),E=i(34666),D=i(51926),x=i(75020),k=i(54017),C=i(48723),F=i(98784),A=i(7656),I=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>F.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return I().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=((0,o.isTest)()?5:30)*P.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=I().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.throwIfAborted_(i?.halt),await L(),i.recountAllTags&&(s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)(),s.info("rebuilding tag asset counts..."),await(0,A.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0))}catch(e){I().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,M.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),I().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const L=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{I().info("updating tag mountpoints...");const e=C.Tag.findByPath([x.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await N(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function R(){t.tagFtsRebuild.unset(),L.unset()}async function N(e){if(null==e||2!==e.depth||!e._path.startsWith(x.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===x.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,v.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,T.later)((()=>{(0,d.ee)().on("clearCache",R),m.Settings.libraryDir.watchLater(R)})),t.fixFileRootTag=N,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):k.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,v.volumeMetadataTtlMs)()}),(0,T.later)((()=>{w.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},16436:e=>{"use strict";e.exports=require("@sentry/node")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},87550:e=>{"use strict";e.exports=require("better-sqlite3")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},66150:e=>{"use strict";e.exports=require("fast-xml-parser")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},31832:e=>{"use strict";e.exports=require("knex")},51168:e=>{"use strict";e.exports=require("luxon")},93973:e=>{"use strict";e.exports=require("ml-kmeans")},80265:e=>{"use strict";e.exports=require("moo")},31704:e=>{"use strict";e.exports=require("nearley")},4927:e=>{"use strict";e.exports=require("papaparse")},83058:e=>{"use strict";e.exports=require("picomatch")},57272:e=>{"use strict";e.exports=require("plist")},85949:e=>{"use strict";e.exports=require("process")},90595:e=>{"use strict";e.exports=require("punycode")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},49378:e=>{"use strict";e.exports=require("trash")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},29907:e=>{"use strict";e.exports=require("cluster")},76982:e=>{"use strict";e.exports=require("crypto")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=53493);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463:(e,t,i)=>{const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),w=m(y,f);return a(s,t,o,p,w)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),w=m(g,p);if(!l(s,w))throw new o("decryption failed");const v=await y(a,f,r.subarray(16));if(!v)throw new o("decryption failed");return v},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),w=u.subarray(32),v=await g(e,y,w),b=n(o,l,v,t,s),S=m(b,p);return a(o,t,l,v,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),w=p.subarray(0,32),v=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,w,v);if(!P)throw new o("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223:e=>{const t=36e5,i=24*t,r=7*i,s=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const n=s.exec(e);if(!n)throw new TypeError(`invalid time period format ("${e}")`);const a=parseFloat(n[1]);switch(n[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*a);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*a);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(a*t);case"day":case"days":case"d":return Math.round(a*i);case"week":case"weeks":case"w":return Math.round(a*r);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*a)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227:(e,t,i)=>{const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120:(e,t,i)=>{const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827:(e,t,i)=>{const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015:(e,t,i)=>{const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function w(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...w(e.slice(i+1))]}function v(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return T(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function T(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function x(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return w(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=v,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=T,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[T(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await x(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),w=i(25764),v=i(38836),b=i(99331),S=i(95937),P=i(98314),T=i(38835),_=i(70025),M=i(8769),E=i(43334),D=i(95402),x=i(28874),k=i(63870);class F extends v.EndableWrapper{constructor(e,t,i=w.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>n(this,r,"m",s).call(this)),i,"worker"===e?(0,k.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,D.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,S.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+T.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&D.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,b.ending)()||!0===(0,_.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=F,r=new WeakSet,s=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(E.isWin?3:1)*c.minuteMs,maxTasksPerProcess:x.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:x.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:x.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,k.commandTimeoutMs)(),taskTimeoutMillis:x.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,s.set(this,void 0),n.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,s,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]=t))}get length(){return u(this,n,"f")}set length(e){l(this,n,(0,d.clamp)(0,u(this,n,"f"),e),"f")}clear(){this.length=0}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,n,"f")),e<0||e>=u(this,n,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,s,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,n,"f"){u(this,s,"f")[e]=c}));return u(this,n,"f")}pop(){return u(this,r,"m",o).call(this,u(this,n,"f")-1,(e=>{var t;return l(this,n,(t=u(this,n,"f"),--t),"f"),u(this,s,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,n,"f"){u(this,s,"f")[e]=c,l(this,a,e,"f")}));return u(this,n,"f")}shift(){return u(this,r,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,n,(i=u(this,n,"f"),--i),"f"),u(this,s,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",o).call(this,u(this,n,"f")-1-e,(e=>{const i=u(this,s,"f")[e];u(this,s,"f")[e]=u(this,s,"f")[t],u(this,s,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=n(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),s=i(31586),n=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),s=i(65843),n=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),s=i(20014),n=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)((()=>!1))},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),s=i(98553);var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},57206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(77988),s=i(51168),n=i(45599),a=i(98553),o=i(68708),l=i(24689),u=i(21330),c=i(57159),d=i(28544),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},19851:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function w(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(w()??await(m.isWin?P():m.isMac?_():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(w);const v=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=v.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const T={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],T))}async function M(){return S(w((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],T)})))}t.localeMac=_,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),s=i(32105),n=i(14593);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),s=i(55835),n=i(59455),a=i(48884);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),s=i(54557);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),s=i(42659),n=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,s]of(0,l.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,l.keys)(e))if(r[n]=t(n,e[n]),s++,(0,o.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,n.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),s=i(73024),n=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),w=i(30933),v=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return F();case"win32":return C();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function T(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function M(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){v().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=T,t.hasApt=function(){return P()||T()},t.isFedora=_,t.isAlpine=M;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function x(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const k=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function F(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return x(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return v().warn("osNameMac(): unknown release",e),b()}}function C(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":x(e,D);return null!=t?`Windows ${t} (${e})`:(v().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=F,t.osNameWin=C,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,w.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(C())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(T())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(M())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},45393:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=4},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(72993),s=i(50213),n=i(23560),a=i(43334);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(85949).title=t}catch(e){(0,s.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},92782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),s=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),s=i(56409),n=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}async function w(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return s.promise}const v=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return w(...e)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),w(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),s=i(54993);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),w=i(34102),v=i(43334),b=i(24399),S=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,w.ee)().on("clearCache",(()=>M.prior()?.clear()))));const T=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>v.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>T().includes(e.toLowerCase())))};let _=!0;const M=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(v.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(1708)),n=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),s=i(57150),n=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,n.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,s.logStartup)())}},28850:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),s.set(this,void 0),n(this,r,e,"f")}_call(){return(0,l.time)(a(this,r,"f")+(null==a(this,s,"f")?"(local)":"(remote)"),null==a(this,s,"f")?this.impl():a(this,s,"f").call(this))}setShim(e){n(this,s,e,"f")}hasShim(){return null!=a(this,s,"f")}clearShim(){n(this,s,void 0,"f")}}r=new WeakMap,s=new WeakMap},12089:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=a,s.set(this,void 0),n.set(this,void 0),l(this,s,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",a).call(this,e),(()=>u(this,r,"m",o).call(this,e)))}setShim(e){l(this,n,e,"f")}hasShim(){return null!=u(this,n,"f")}clearShim(){l(this,n,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",a).call(this,e))}}s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,s,"f")+(null==u(this,n,"f")?"(local)":"(remote)"),null==u(this,n,"f")?this.impl(e):u(this,n,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return s(this,r,"f")[Symbol.iterator]()}get length(){return s(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=s(this,r,"f").length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),a=this.valueOf(s(this,r,"f")[n]);if(e===a)return{found:!0,index:n};e>a?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&s(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...s(this,r,"f")];const a=t=>t<0||t>s(this,r,"f").length-1?null:(i??this.diff)(s(this,r,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return s(this,r,"f").shift()}at(e){return(0,a.at)(s(this,r,"f"),e)}toA(){return[...s(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===s(this,r,"f").length-1){const e=[...s(this,r,"f")];return s(this,r,"f").length=0,e}return s(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return s(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),s=i(82328),n=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),s=i(95705);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const w=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" …(+"+s+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const v=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return v.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const T=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return T.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['‘’].*['‘’]$/,D=/^["“”„«»〃].*["“”„«»〃]$/;function x(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>w.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=k,t.sortNaturalBy=F,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>F(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const C=/#.*$/gm;t.stripComments=function(e){return e.replace(C,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function w(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=v(i),t=v(r);return 2*b(e,t).length/(e.length+t.length)}))}function v(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function T(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=w,t.bigrams=v,t.nonUniqIntersection=b,t.lnsDiff=T;const _=/[^\da-z]+/gi;function M(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=M,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:w(e,t),lns:T(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),s=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},75387:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},65211:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(19851),s=i(76790),n=i(22573),a=i(54993),o=i(7282),l=i(55222);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!(0,o.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),u=0}},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),s=i(55835),n=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},79184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(59455),s=i(48884),n=i(22859),a=i(28874),o=i(79781),l=i(92434);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(50357),o=i(55835),l=i(31586),u=i(68708),c=i(12168),d=i(23467),h=i(73168),f=i(50213),m=i(86580),p=i(48368),g=i(80361),y=i(28874),w=i(28544),v=i(75767),b=i(16170),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} ≠ ${o}`}function T(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function _(e,t){return[T(e),T(t)]}function M(e,t,i){const r=(0,v.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.aKey}:${r.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=w.CapturedAt.fromAssetFile(e),f=w.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const T=a.isFuzzy||f.isFuzzy;if(T&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",_)??P(e,i,"model",_);if(null!=E)return E;const D=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),x={cameraId:M(e,i,"cameraId")??null,imageId:M(e,i,"imageId")??null,lensId:M(e,i,"lensId")??null,exposureSettings:(0,v.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(D,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(D)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:x});const k=(0,s.compact)((0,u.values)(x));if((0,s.isNotEmpty)(k))return k.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:T});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(x).filter((e=>null==x[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos ≠ images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=E(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},13991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(19851),s=i(55835),n=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function w(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function v(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([w(e),v(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=w,t.assetFileStatFields_=v,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),w=i(14036),v=i(45200),b=i(34238),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function T(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function M(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=T,t.sortScale=_,t.mtime2sort=M;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,F).reverse()}function x(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=T(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,w.isSupportedByCurrentBrowserExt)(n.ext),mtime:M(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function k(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function F(e){const t=x(e);if(null==t)return;const i=[];for(const e of k())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=x,t.assetFileSortFields=k,t.assetFileSortCriteria=F,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,v.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),s.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,n(this,s,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return n(this,s,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,n(this,s,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=n(this,r,"f")&&clearTimeout(n(this,r,"f")),a(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,s=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(87997)),n=i(31586);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const w=y(i(87997)),v=y(i(57975)),b=i(45599),S=i(26905),P=i(55835),T=i(31586),_=i(68708),M=i(20214),E=i(57153),D=i(85556),x=i(50213),k=i(70025),F=i(95937),C="TIMEOUT",A=(0,b.defer)((()=>(0,x.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,T.gt0)(t)?new s(C).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const s=i[r];if(s.isSettled){if(s.name===C)return void A().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield s.value}}if(i.every((e=>e.name===C)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[v.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(w.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,T.gt0)(e)&&(g(this,h,w.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,F.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,s=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),w.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>v()),10*n.minuteMs);const y=5*n.secondMs;async function w(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function v(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>w(e))))},t.end=w,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),v();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>w(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,s.compact)(g.valuesFlat()).map((e=>w(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class w extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=w,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,s=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function w(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=w,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{w({reason:`${e}:${t}`,status:0,error:i})}))}))},39250:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(23838),a=i(54993),o=i(15674),l=i(73568),u=i(76740),c=i(99331),d=i(42638);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new d.Promises(e,t)}vacuum(){return s(this,r,"f").filterInPlace(((e,t)=>t.isPending&&!0!==t.payload?.aborted)),s(this,r,"f").valueCount()}enqueue({key:e,abortable:t,fn:i}){for(const t of s(this,r,"f").get(e)??[])t.payload?.abort("aborted by new work");if(this.vacuum(),(0,c.ending)())throw new l.AbortError("ending");const n=t??new u.Abortable,o=this.p.serial((0,a.toS)(e),(()=>i(n)),n);return s(this,r,"f").add(e,o),o}},r=new WeakMap},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),w=i(22911),v=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new b(e,t,i,r)};class b extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,n,0,"f"),d(this,s,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,r,"m",u).call(this,w.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,n,"f")}isStale(){return null==c(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,s,"f")?void 0:Date.now()-c(this,s,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(v().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,n,(i=c(this,n,"f"),++i),"f")}},u=function(e){d(this,s,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof w.Deferred?e:new w.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),s=i(80049);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},22781:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),s.set(this,!1),n.set(this,!1)}_call(){return a(this,s,"f")?(o(this,n,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,r,"f")):(o(this,s,!0,"f"),o(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,s,!1,"f"),!0===this.runLaterIfBusy&&a(this,n,"f")&&(o(this,n,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,s,"f")}prior(){return a(this,r,"f")}async force(){return await a(this,r,"f"),this._call()}}r=new WeakMap,s=new WeakMap,n=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),w=i(15674),v=i(42638);var b=i(20214);async function S(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function T({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,l.gt0)(s)?(0,c.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function _({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,w.maxCpus)()))<=1)return T({arr:e,f:t,name:i,timeoutMs:n});const u=a??(o.length<=s?v.PermissivePromises:new v.Promises(i,(()=>s))),d=(0,l.gt0)(n)?e=>(0,c.thenOrTimeoutError)(t(e),n):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=S,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await S(s);r.push(...await S(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=T,t.mapAsyncSerial=async function(e){return(await T(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await _({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){s=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await _({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),w=i(25764),v=i(38836),b=i(73614);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function T(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new v.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),w.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=T,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>T(e,t)),i)}},42638:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),w=i(54993),v=i(89788),b=i(82647),S=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,w.toS)(e)};class T{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new v.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=T,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new T(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new T(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},59189:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(1708)),n=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),w=i(50213),v=i(7282),b=i(88158),S=i(45969),P=i(43334),T=i(28874),_=i(3790);function M(e){return E().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const E=(0,n.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(T.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,b.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,T.allSettings)())t.watchLater(e)}));const D=["HOME","LANG","USER"],x=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],k=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?D:x),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,T.pathWithDefaults)(),e}));function F(e){const t={NODE_ENV:(0,v.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,S.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,T.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,o.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(s.default.env,(e=>M(e)||!(0,_.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=F,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:A({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let C=!1;function A({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...k(),...i?(0,g.childProcLocale)():{},...F(r),...e??{}});for(const e of(0,T.transientSettings)())e.deleteFromEnv(s);if((0,y.isLogged)("debug")&&!C){C=!0;const e=(0,w.mkLogger)("child.ChildEnv"),t=(0,l.entries)(s).map((([e,t])=>[e,(0,_.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return s}t.childEnv=A},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),w=i(79089),v=i(45255),b=i(22911),S=i(4867),P=i(73614),T=i(70025),_=i(57159),M=i(36868),E=i(66184),D=i(45643),x=i(95402),k=i(9727),F=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function C(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function A(e,t=30*u.secondMs){if(null==e)return!1;F().debug("endProcess()",C(e));const i=e.pid;if(null==i||i<=0)return F().warn("endProcess(): asked to end invalid pid",C(e)),!1;if(i===n.default.pid)return F().warn("endProcess(): asked to end MY pid",C(e)),!1;if(i===n.default.ppid)return F().warn("endProcess(): asked to end my parent pid",C(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();F().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,x.killPid)(i).catch((e=>{F().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,D.waitForPidExit)(i,t))return F().debug("endProcess(): exitted",C(e)),!0;{x.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");F().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,x.killPid)(i,!0).catch((e=>{F().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,D.waitForPidExit)(i,5e3)}function I(e,i,r,s=0){const a=new Date,o=[];return(0,w.niceable)(i,r)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,w.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&A(e)}),s-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,x.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,k.spawnOptions)(r);return(0,E.isLogged)("trace",F().context)?F().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):F().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new b.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(a.stdin);const w=new d.Latch;null==a.stdout?w.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>w.resolve())));const P=new d.Latch;null==a.stderr||s?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),F().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,S.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),F().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:w.state(),stderr:P.state()}),await(0,S.thenOrTimeoutError)({p:w.promise,timeoutMs:v.ShortCommandTimeoutMs,halt:i.halt}),await(0,S.thenOrTimeoutError)({p:P.promise,timeoutMs:v.ShortCommandTimeoutMs,halt:i.halt});const E=p.join("");(0,l.notBlank)(E)&&g.push(new Error(E)),!r&&(0,o.isNotEmpty)(g)&&F().warn(f+" resulted in errors:",g);const D=i.isIgnorableError??T.isIgnorableError,x=g.filter((e=>!0!==D(e)));if(x.length>0)throw 1===x.length?x[0]:new _.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!n&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:E}}catch(e){throw F().error("stdoutResult_() failed",e),await(0,x.killPid)(a.pid,!0),e}}t.endProcess=A,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,k.spawnOptions)(r);return F().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return F().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),s=i(41400),n=i(19851),a=i(28874);(0,s.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,n.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},85100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(23560),s=i(28874),n=i(45255);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?s.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},34330:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),w=i(54993),v=i(27395),b=i(25764),S=i(99331),P=i(42638),T=i(38835),_=i(8769),M=i(57159),E=i(66003),D=i(50213),x=i(45643),k=i(28874),F=i(84777);t.mkBasicWatchedChild=function(e){return new C({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,F.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class C{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new M.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,v.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=C,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,x.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,F.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+T.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,w.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+T.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),s=i.sibling(r);if(s.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",s.posixPathFrom((0,l.examples)()));const n=(0,d.originalsDir)();if(s.isSelfOrDescendantOf(n))return a.join("$library",s.posixPathFrom(n));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",s.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(6858),a=i(1708),o=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return s(this,r,"f").push(...e),this}async parse(e=a.argv,t){let i=(0,m.addHelpFooter)(new n.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of s(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":o.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,a.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of s(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),s=i(38639),n=i(17181),a=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,s.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),a.Settings.logColor.envValue=e,(0,n.setupLogFormatter)()}))}}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(1708)),n=i(22573),a=i(38639);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},53978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},54772:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),w=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function v(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void w().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void w().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(v)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=v,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return T(v(e))}function y(e){return(0,f.clampRGB)(M(_(e)))}function w(e){return(0,t.LabBitZip)().clampValue(e)}function v(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return w([116*i-16,500*(t-i),200*(i-r)])}function _(e){const[t,i,r]=w(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function M(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=T,t.lab2xyz=_,t.xyz2rgb=M,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function x(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function k(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function F(e){return C(k(e))}function C(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function A(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function I(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(D,e,(()=>x(e,t))):x(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=k,t.rgbhex2hsl=function(e){return F((0,f.rgbhex2triplet)(e))},t.rgb2hsl=F,t.hsl2rgb=function(e){return I(A(e))},t.hsv2hsl=C,t.hsl2hsv=A,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},42079:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(31586),s=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),w=(0,s.sqrt)(g*g+h*h);let v=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);v+=2*(v<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=w-y;let T=y*w==0?0:b-v;T-=2*(T>Math.PI?1:0)*Math.PI,T+=2*(T<-Math.PI?1:0)*Math.PI;const _=2*(0,s.sqrt)(y*w)*Math.sin(T/2),M=(i+c)/2,E=(y+w)/2;let D;y*w==0?D=v+b:(D=(v+b)/2,D-=(Math.abs(v-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const x=(M-50)**2,k=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),F=1+.015*x/(0,s.sqrt)(20+x),C=1+.045*E,A=1+.015*E*k,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*I)*O;return(0,s.sqrt)(Math.pow(S/(n*F),2)+Math.pow(P/(a*C),2)+Math.pow(_/(o*A),2)+L*P/(a*C)*_/(o*A))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(40958),s=i(31586),n=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},32848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(48884),o=i(31843),l=i(70417),u=i(3048);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},40401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),w=i(85810),v=i(3048),b=i(76490),S=i(1971),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,w.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??v.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,w.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function x(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const F=f.length<=g?[]:(0,s.compact)(T.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...M,seed:e}),s=k(r.centroids,f.length);if(s.lengtht&&x(g-1);const n=s.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,w.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n),2);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:F.map((e=>(0,u.pick)(e,"description","score")))});const C=(0,c.leastBy)(F,(e=>e.score));if(null==C)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),D(a,t);const A=(0,o.stringify)({...C?.description,elapsedMs:Date.now()-i}),I=(0,n.sortBy)(C?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:A,score:C?.score,totalColors:a.size,totalPixels:f.length,iters:C?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:A,dominantColorScore:C?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,v.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,v.ciede2000_delta_e)(e.centroid,r))}return i};const T=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:v.cie76_delta_e,cie94:v.cie94_delta_e,ciede2000:v.ciede2000_delta_e},M=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function D(e,t){const i=e.countSum,r=e.size;x(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function x(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,w.unlabhash)(r),a=i.find((e=>(0,v.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function k(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,v.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{M.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=x,t.mergeNearCentroids=k},85409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(31586),s=i(68708),n=i(50989);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),w=i(21330),v=i(928),b=i(54261),S=i(73389),P=i(51275),T=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof w.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function M(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof w.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),x(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof w.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void T().warn("datedToDateTime() failed",{d:e,error:t})}}function x(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,v.getMillisecond)(e)))return 0;if((0,c.gt0)((0,v.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,v.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,v.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,v.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,v.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=M(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function F(e,t,i,r){const[s,n]=(0,a.sortBy)([k(e,i),k(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function C(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??w.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=M,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=x,t.isoToPrecisionMs=function(e){return(0,u.map)(C(e),x)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=x(e)),r??(r=x(t)),F(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,w.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,w.setZone)(t,s)??t),F(e,t,i,r)},t.isoToDated=C,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),s=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),s=i(31586),n=i(54557),a=i(91655),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),s=i(40958),n=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function w(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),w=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(w)??i,rawValue:e,tzoffsetMinutes:w})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??w(e,b(),t)},t.parseExifDateTimeRe=w;const v=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,v,p.monthRE,v,p.dayRE,/[T\s]/,p.hourRE,v,p.minuteRE,v,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),w=i(79842),v=i(66649),b=i(98247),S=i(98725),P=i(928),T=i(54261),_=i(73389),M=i(89724),E=i(17415),D=i(88600),x=i(51275);function k(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class F{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,D.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(S.ISO_YMD_RE.exec(e)?.groups??S.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tk(e))).join("-")}toLocal(){return(0,M.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new F(t.year,t.month,t.day)}}function C(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,T.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,E.zoneToTzOffsetMinutes)((0,v.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(s=>(0,d.map)((0,P.getDay)(e),(n=>(0,d.map)((0,P.getHour)(e),(a=>(0,b.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=F,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,h.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${k(n)}:${k(a)}`},t.toExifDateTime=C,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,T.hasTime)(e)||(i??(0,w.datedToPrecisionMs)(e))>=c.dayMs?O(e):C(e,(0,x.getZoneName)(e))?.toISOString({includeOffset:t})};const A="yyyy:MM:dd HH:mm:ss.SSS",I=A+"ZZ";function O(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>k(e))).join(t)}function L(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new F(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(v.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,w.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,x.hasZone)(t)?I:A):void 0},t.datedToYMD=O,t.toFuzzyDate=L,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,v.datedToMillis)(e)||null==(0,v.datedToMillis)(t))return;const[s,n]=[e,t].map((e=>(0,v.datedToMillis)(e))).sort(),o=(n-s)/(r+1),l=(0,x.getZoneName)(e),u=l===(0,x.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,T.hasTime)(e)))?L(c):c},t.setZone=function(e,t,i){const r={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,x.hasZone)(e)},s=(0,E.normalizeZone)(t);return null!=e&&null!=s&&(0,T.hasTime)(e)?e instanceof y.DateInterval?e.setZone(s,r):C(e)?.setZone(s,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,w.datedToDateTime)(e);if(null==i)return;const r=(0,x.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),w=i(68852),v=i(4001),b=i(28874),S=i(24689),P=i(79842),T=i(66649),_=i(98247),M=i(21330),E=i(54261),D=i(73389),x=i(16400),k=i(88600),F=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return F().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,T.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,w.concatRegexp)([/^/,t.yearRE,w.RegExpOptional.from(/-/,t.monthRE,w.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,w.concatRegexp)([/^/,t.yearishRE,w.RegExpOptional.from(/-/,t.monthishRE,w.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const C=new Map;function A(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(C,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void F().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void F().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(v.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>A(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const e of n){const t=a(e);if(null!=t&&(0,k.isValidDate)(t))return t}}t.parseDated=I;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;M.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new w.RegExpEscaped("(?"+(0,x.monthNames)().map(w.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,w.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return M.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,x.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),s=i(31586),n=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),s=i(31586),n=i(68708);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),s=i(19851),n=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,s.lazy)((()=>w(l.Settings.datesBeforeAreEstimated.valueOrDefault)??w(l.Settings.datesBeforeAreEstimated.defaultValue)));function w(e){return(0,a.map)((0,c.isoToDated)(e),v)}function v(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function T(e,t){return _(Date.now()-e,t)}function _(e,t){return v(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},42499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(51168),s=i(19851),n=i(19043),a=i(28874);t.setupLuxon=(0,s.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,n.locale)()}))},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=T,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:T(i)};const _=/\b(?Z|UTC|GMT)\b/,M=/(?[-±+−])/,E=/[-−]/,D=/(?[01]\d)/,x=/(?[01]?\d)/,k=/(?::(?\d\d))/;function F(e){return b(e)?0:C((0,t.TimezoneOffsetRE)().exec(e))}function C(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return w(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),M,D,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=F,t.timezoneOffsetFromRegExpMatch=C;const A=/\b(?(?:Etc\/)?GMT)\b/,I=(0,n.lazy)((()=>(0,m.concatRegexp)([A,M,x,m.RegExpOptional.from(k)])));function O(e){return C(I().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??F(e);if(null!=i)return T(i);if(null!=t){const i=S(e);if(null!=i)return T(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),w=(0,s.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),v=(0,s.lazy)((()=>(0,n.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),b=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,p.datedToISO)(e)))))),S=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,y.datedToLocal)(e)))))),P=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,m.datedToMillis)(e))))));function T(e){if(null==e)return!1;const t=M(e);return w().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return T(e)?e:void 0},t.isValidDate=T;const _=String(new Date("bad"));function M(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===_)return _;const t=(0,n.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,E())&&s.push("year is in the future"),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):S().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):b().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(t)).join("; "))}catch(t){return w().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=M;const E=(0,s.lazy)((()=>r.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return T(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==M({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),s=i(31586),n=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},82261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},92407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(19851),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},55332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(19851),s=i(50213),n=i(76187),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},91872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i,r){const a=Date.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}))}},12943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(79842),s=i(66649),n=i(40958),a=i(68708);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},65753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(19851),s=i(7282),n=i(28874);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*((0,s.isTest)()?.25:5))))},80632:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(54993),u=i(50213),c=i(23560),d=i(65211),h=i(29882),f=i(53265),m=i(66430),p=i(66184),g=i(28874),y=i(15674),w=i(87550);function v(){const e=g.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,a.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=g.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=g.Settings.logSql.valueOrDefault}){e=(0,f.resolve)(e),(0,h.mkdirpSync_)((0,r.dirname)(e));const b=(0,h.posixPathFromGrandparent)(e),S=(0,m.nativePathSizeSync)(e),P=(0,u.mkLogger)("db.mkdb("+b+")");if(null!=S){const E=Math.round(S/o.MiB),D=Math.ceil(1.5*E);D>g.Settings.dbCacheSizeMb.valueOrDefault&&(P.info("Dynamically setting dbCacheSize to "+g.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:E}),g.Settings.dbCacheSizeMb.envValue=D);const x=Math.round(1.5*E);x>g.Settings.maxMemoryMb.valueOrDefault&&(P.warn("Large database: setting maxMemoryDb to "+x+"MB",{dbFileSizeMb:E,"Settings.maxMemoryMb":g.Settings.maxMemoryMb.valueOrDefault}),g.Settings.maxMemoryMb.envValue=x)}P.info("Opening "+e+"...");const T={fileMustExist:!1,readonly:!1};if((0,a.gt0)(t)&&(T.timeout=Math.ceil(t)),i){const k=(0,u.mkLogger)("SQLite("+b+")"),F=(0,p.defaultLogLevel)();function C(e,...t){var i;(0,n.blank)(e)||k.log(F,(i=e,(0,l.toS)(i).replace(/\s{2,}/g," ")),{args:t})}T.verbose=C}const _=new w(e,T);P.info("Open. Setting PRAGMAs...");for(const A of(0,s.compact)(['encoding = "UTF-8"',"threads = "+(0,y.maxCpus)(),"foreign_keys = ON","page_size = "+v(),"trusted_schema = 0","cache_size = -"+Math.round(g.Settings.dbCacheSizeMb.valueOrDefault*o.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL",(0,a.gt0)(g.Settings.dbBusyTimeoutMs.valueOrDefault)?"busy_timeout = "+g.Settings.dbBusyTimeoutMs.valueOrDefault:null,"temp_store = MEMORY","synchronous = "+g.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,c.isDbJanitorService)()?(0,l.toS)(g.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+g.Settings.dbAutoVacuumMode.valueOrDefault]))P.tapThunk({msg:"PRAGMA "+A,result:()=>_.pragma(A)});const M=_;return M.__uid=(0,d.uid)(),M},t.pageSizeBytes=v},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},95704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(40958),s=i(31586),n=i(59455),a=i(65753),o=i(51040);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},76187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(17217),s=i(87391),n=i(7311);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},51040:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+$/gm,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(19851),s=i(50357),n=i(30976),a=i(50213),o=i(95696),l=i(80632),u=i(76187),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},87391:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),w=i(70698),v=i(64680),b=i(29882),S=i(45969),P=i(43334),T=i(28874),_=i(41692),M=i(32774),E=i(80612),D=i(32551),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+x()),preexistingDir:i});return e}}function F(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:M.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,D.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,D.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,D.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=F,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:F(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),T.Settings.cacheDir.watchLater(A)}));function A(){T.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=T.Settings.cacheDir.valueOrDefault;try{return(0,b.mkdirpSync_)(e),(0,w.writeCachedirTag_)(e).then((()=>(0,v.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=A},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),s=i(45969),n=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),s=i(45969),n=i(32774);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),s=i(96706),n=i(29882);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),s=i(49776),n=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),s=i(54993),n=i(29882),a=i(28874);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),s=i(55835),n=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function w(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function v(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(v(e),!1)}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function T(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(T(e))}async function M(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await w(t);return(0,r.uniq)([t,i,await b(t),await P(t),await _(t),await M(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=w,t.libraryOriginalsDirPosixFile=v,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=T,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=M},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),w=i(80612),v=i(32551);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,v.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,v.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,w.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,v.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),s=i(7282),n=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),s=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),w=i(59958),v=i(6012),b=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(w.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,n.join)((0,m.homeDir)(),".psenv"));const t=(0,b.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,d.debom)(s.default.readFileSync((0,g.resolve)(r))),n=(0,v.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(n))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),s=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(1708)),n=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),s=i(19851),n=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),w=i(70025),v=i(57159);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,w.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,w.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function T(e,t){return e instanceof v.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(T(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=T,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),T(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),s=i(26905),n=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},68301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(19851),s=i(42659),n=i(75240),a=i(55835),o=i(31586),l=i(68708),u=i(59455),c=i(54993),d=i(50213),h=i(45255),f=i(37628),m=i(99331),p=i(46292),g=i(38835),y=i(32144),w=i(29882),v=i(95696),b=i(55222),S=i(28874),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function T(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*s.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=s.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,w.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),s=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=s,meta:{event:T(e),recentEventCount:r,maxErrorsPerDay:s,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:T(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:T(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new _(v.PosixFile.for(e).join("events"))))))},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),s=i(38639),n=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function w(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function v(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function b(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function S(e){return!!((0,s.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||b(e))||void 0}t.isSqliteBusyError=w,t.isSqliteDisconnectedError=v,t.isSqliteConstraintError=b,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===S(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||w(e)||v(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=S;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),s=i(31586),n=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),s.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(n(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),s=i(19851),n=i(15197);t.ee=(0,s.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new n.CapturingEventEmitter(e)}))},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(73024)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(76760)),n=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),s=i(76760);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),w=f(i(1708)),v=i(46466),b=f(i(57975)),S=f(i(38522)),P=i(19851),T=i(40958),_=i(5233),M=i(22573),E=i(42659),D=i(50357),x=i(96249),k=i(98553),F=i(55835),C=i(31586),A=i(68708),I=i(97790),O=i(39926),L=i(51926),R=i(59455),N=i(54993),B=i(48884),j=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),q=i(76850),H=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Z=i(43334),Y=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),se=i(89968),ne=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),we=i(27794),ve=i(73428),be=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const Se=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,T.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,M.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const s=(0,fe.resolve)(i),n=new Pe(s,t);return Se().set(i,n),Se().set(s,n),n}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,F.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,T.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,T.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,T.isNotEmpty)(e)?(0,T.includesAll)(t,e):(0,T.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,T.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,C.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,T.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,F.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,T.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,T.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,F.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,q.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,be.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,ve.writeFileSync_)(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,A.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,we.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,we.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,T.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,C.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),Te)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,F.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,C.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,n=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,F.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,v.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*E.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let Te=!0;t.useFsWatch=function(e){Te=e},t.execDir=function(){return Pe.for(w.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),s=i(88840),n=i(14036),a=i(29882);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,n.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),w=i(14427),v=i(17217),b=i(16287),S=i(68284);class P{constructor(e,t){this.base=e,(0,w.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const T=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,v.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void T().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void T().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void T().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),w=i(54557),v=i(50213),b=i(88158),S=i(56519),P=i(46292),T=i(32551),_=i(35280),M=i(87290),E=i(96706),D=i(57902),x=i(43334),k=i(78984),F=i(33995),C=i(28874),A=i(21144),I=i(83278),O=i(48313),L=i(85772),R=i(78133),N=i(46356),B=i(17217),j=(0,u.lazy)((()=>(0,v.mkLogger)("fs.ExcludeGlobs"))),z=new w.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:C.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((x.isWin?"*":"")+"/"+t.s+"/",t.desc));if(x.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}x.isLinux&&e.push(new U(`${(0,T.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Z=(0,u.lazy)((()=>{C.Settings.excludeGlobsOmitDefaults.watchLater(J),C.Settings.excludeGlobsAdd.watchLater(J),C.Settings.excludeGlobsOmit.watchLater(J),C.Settings.globsCaseInsensitive.watchLater(J),C.Settings.libraryDir.watchLater(K),C.Settings.originalsDir.watchLater(K),C.Settings.scanPaths.watchLater(K),C.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ne,whyNoMedia:L.whyNoMedia,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ne}])),t.excludeGlobs=(0,u.lazy)((()=>{Z();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!C.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of C.Settings.excludeGlobsOmit.values)i(e);for(const e of C.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Y=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return C.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return F.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return C.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return C.Settings.disableAllFilters.valueOrDefault?void 0:k.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ne(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,M.libraryDirPosixFile)(),(0,M.libraryOriginalsDirPosixFile)(),...C.Settings.argvScanPaths.values,...C.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,A.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ne},88561:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class w extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=w,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,n.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),s=i(17217),n=i(16287),a=i(68284);async function o(e){return(0,r.pick)(await(0,n.stat_)((0,s.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,s.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),s=i(19851),n=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,s.set(this,[]),n.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,n,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,s,"f").push(e)}close(){u(this,n,"f").close()}}t.FileWatcher=m,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,s,"f"))t(e,this.nativePath)}}},73209:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const T=i(58587),_=P(i(44652)),M=i(87997),E=i(40958),D=i(17586),x=i(42659),k=i(50357),F=i(75240),C=i(55835),A=i(31586),I=i(30976),O=i(13538),L=i(54993),R=i(7282),N=i(68852),B=i(23560),j=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),q=i(55222),H=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,s,Math.max(Date.now(),b(this,s,"f",n)+1),"f",n),(0,E.compactBlanks)([q.TokenRadix.encode(b(this,s,"f",n)),B.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,A.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return b(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>b(this,r,"m",v).call(this)),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=s,s,(i=b(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(b(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await b(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+b(this,l,"f")),this.staleMs=(0,A.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),b(s,s,"f",o).push(this)}get acquired(){return b(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await b(this,r,"m",f).call(this,e)??b(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,D.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==b(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:x.secondMs);S(this,c,setInterval((()=>b(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=b(this,c,"f")&&(clearInterval(b(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(b(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(b(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?b(this,r,"m",w).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>b(this,r,"m",w).call(this)),(0,A.toGt0)(this.staleMs)??x.secondMs),"f"),b(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(b(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,A.gt0)(this.staleMs)&&Date.now()>b(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await b(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await b(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,A.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+x.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,A.gt0)(t)&&!(0,T.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),b(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await b(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},w=async function(){await b(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},v=function(){(0,E.filterInPlace)(b(s,s,"f",o),(e=>b(e,l,"f")!==b(this,l,"f")))},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),s=i(51926),n=i(54993),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(73024)),n=i(57075),a=i(46466),o=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44652)),n=r(i(73024)),a=i(46466),o=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),w=i(16287),v=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return v().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;v().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await T(n.default.createReadStream(i)),stats:(0,u.pick)(await(0,w.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function T(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=T,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),s=i(42659),n=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),s=i(54993),n=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,n.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,n.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,n.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,n.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(51926),n=i(54993);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(76760)),n=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},61704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(21144),s=i(17217);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=n(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),w=i(83278),v=i(70698),b=i(88561),S=i(65238),P=i(16287),T=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),_="NoMedia",M=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+_+"$","im"),E=Object.freeze(["."+_,_]),D=Object.freeze((0,u.flatten)(E.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function x(e){return null!=M.exec(e)}t.isNoMediaName=x;const k=(0,o.lazy)((()=>new b.FileCache({name:"fs.noMediaDirsCache"})));async function F(e,t){if(null==e)return null;const i=w.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return x(i.base)||await(0,v.isCachedirTagFile)(i)?k().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):F(i.parent());{const e=await k().getOrSetAsync(i.nativePath,(()=>C(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:F(i.parent())}}async function C(e){if(x(e.base))return k().set(e.parent().nativePath,e.nativePath),T().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,S.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([A(e.nativePath,i),(0,S.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,v.isCachedirTagDirectory)(e)?T().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(v.CACHEDIR_TAG).nativePath)}):null}async function A(e,t){for(const i of g.isCaseSensitiveFs?D:E){if(!0===t?.aborted)return null;const r=a.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return T().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(x(r.basename))return T().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,r.basename))});if(r.basename===v.CACHEDIR_TAG){const t=(0,a.join)(e,r.basename);if(await(0,v.isCachedirTagFile)(t))return T().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await F(e,t)},t.whyNoMedia=F,t.whyNoMediaDir=C,t._dirHasNoMediaChild=A},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),w=i(78133),v=i(53265),b=i(17217),S=i(16287),P=i(66430),T=i(5545);function _(e){return((0,b.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return F(e).some(_)},t.isNotHiddenPosixPath=function(e){return F(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,b.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,w.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return n.default.dirname((0,b.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=M.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function D(e){const t=n.default.parse((0,b.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,n.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,b.toNativePath_)(e.ancestor),i=(0,b.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(y.isLinux?r===s:(0,p.equalsIgnoreCase)(r,s))}function F(e){return(0,b.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return(0,u.notBlank)(e)&&F(e).length===(y.isWin?1:0)}function A({p:e,maxLength:t}){const i=(0,b.toNativePath_)(e);if(i.length<=t)return i;const r=F(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),O([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),O([...s,...n])}function I(e){return e.startsWith("\\\\")}function O(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),y.isWin?"":n.default.sep)}t.parseNativePath=E,t.parentBasename=D,t.grandParentBasename=function(e){return D(n.default.parse((0,b.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return k(b.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(b.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(b.toNativePath_,e,t)},t.toPathnames=F,t.pathIsRoot=C,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:F(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,b.toNativePath_)(e),r=(0,b.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,w.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,w.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=A,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(A({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return F(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return F(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(T.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;if(C(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await s.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,b.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,b.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),w=i(64660),v=i(21144),b=i(16287),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function T(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,w.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=T,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...M(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await T(i))return y.isLinux?i:(0,v.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,w.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),w=i(76790),v=i(5233),b=i(22573),S=i(42659),P=i(26905),T=i(75240),_=i(55835),M=i(31586),E=i(68708),D=i(13538),x=i(89937),k=i(12168),F=i(54993),C=i(48884),A=i(50213),I=i(45255),O=i(81168),L=i(56519),R=i(56038),N=i(31562),B=i(84777),j=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),q=i(43334),H=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Z=i(34238),Y=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),se=i(73209),ne=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,C.contextFilter)(function(e){return(0,w.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,A.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),r=new fe(i,t);return(0,O.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,F.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===x.PS_LIBRARY_SCHEME?1:t.scheme===x.PS_LOCAL_FILE_SCHEME?2:t.scheme===x.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,C.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,v.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,M.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,D.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,T.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,M.clamp)(I.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*k.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,M.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*k.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),w=i(83278),v=i(19748),b=i(92423),S=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function T(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):null}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function M(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function x(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function k(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function F(e){return(0,w.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function C(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function A(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function I(e){return[{isSupportedFileExtension:v.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:F},{notFileTooSmall:C,notFileTooBig:A}]}function O(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:k},{notDimensionsTooSmall:T},{notVideoTooShort:_},{notVideoTooLong:M},{notRejectedRating:D},{notExcludedKeyword:x}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=T,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=F,t.notFileTooSmall=C,t.notFileTooBig=A,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(76760)),n=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(s.default.join((0,p.execDir)(),"resources"),s.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=s.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),s=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),s=i(84542);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(51455)),n=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),w=i(28874),v=i(63870),b=i(88561),S=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(w.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function T(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=T;const _=(0,a.lazy)((()=>new b.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function E(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=D(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(w.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(s===f.Timeout&&(0,g.onTimeout)({soft:!1}),s!==f.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{w.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),T()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?T():M(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(w.Settings.readdirCacheMs.valueOrDefault)?E(e):D(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=D},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const s=i(73024),n=r(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=n.default.resolve(t,...e);if((0,s.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??n.default.resolve(...e))},t.execDir=(0,l.defer)((()=>n.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(22454),s=i(28874),n=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),s=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const s=r(i(73024)),n=r(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,g.statTimeoutMs)(),!0)}function v(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function S(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(S(r),S(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}t.stat_=w,t.statMaybe=v,t.statToType=b,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await v(e,t)},t.isEmptyFile=async function(e,t){const i=await v(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await v(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await v(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await v(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await v(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await v(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await v(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),s=i(56409);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(57075)),n=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),w=i(19851),v=i(40958),b=i(22573),S=i(42659),P=i(98553),T=i(31586),_=i(68708),M=i(50989),E=i(51926),D=i(85556),x=i(54993),k=i(89788),F=i(23467),C=i(7282),A=i(23560),I=i(77377),O=i(71567),L=i(73568),R=i(25764),N=i(38836),B=i(99331),j=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),q=i(5012),H=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Z=i(84542),Y=i(73428);t.AssetFileSyncStates=(0,M.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,M.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,M.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,M.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const X={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,_.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,M.strEnum)(...(0,_.keys)(new class{constructor(e,t,i,r,s,n,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,w.lazy)((()=>(0,Y.writeTextfile_)(re().nativePath,(0,E.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(X)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=S.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,H.isCsvExt)(e)&&(0,T.gte)(e.mtimeMs(),t)))},t.syncReport=(0,w.lazy)((()=>new se));class se extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new k.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,s,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,b.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,q.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,x.toS)(e.path),state:e.state,details:(0,x.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:t,at:new Date(t).toISOString(),...i,...(0,_.pick)(e,"from","elapsedMs","url")};(0,_.isEmptyObj)(e.meta)||(s.meta=(0,P.stringify)(e.meta)),(0,C.isTest)()&&process.stdout.write((0,P.stringify)(e)+Z.Newline),f(this,r,"m",u).call(this,s)}}maybeSystemData(e){(0,A.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:n}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,B.ending)()||r instanceof L.AbortError?t.SyncFileStates.canceled:r instanceof D.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return f(this,n,"f")??f(this,r,"m",h).call(this)}async flushClose(){return f(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,n,"f");return m(this,n,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,s,"f")}}t.SyncReport=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,F.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,r,"m",c).call(this,i):(f(this,r,"m",c).call(this,{...i,details:(0,v.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Z.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,s,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,j.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,s,"f").nativePath),this.logger.info("Opening new report: "+f(this,s,"f")),(0,C.isTest)()&&(0,O.stdoutWrite)({syncReport:f(this,s,"f").nativePath},!1),m(this,n,(0,g.createWriteStream)(f(this,s,"f").nativePath),"f"),f(this,n,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Z.Newline),f(this,n,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(48161)),n=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44652)),n=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},79847:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkFileUri=t.trashOrUnlinkFileUris_=void 0;const o=n(i(51455)),l=a(i(49378)),u=i(40958),c=i(22573),d=i(13538),h=i(83104),f=i(45255),m=i(31562),p=i(98314),g=i(34102),y=i(28874),w=i(45200),v=i(63870),b=i(16287),S=i(74128),P=i(84258),T="fs.Trash";async function _(e){const t=Date.now(),i=(0,v.commandTimeoutMs)(),r=(0,c.toNotBlank)(e.nativePath)??await(0,d.thenOrTimeout)((0,w.uri2nativePath)(e.uri,e.mountpoint),i);if((0,c.blank)(r)||r===h.Timeout)return(0,S.syncReport)().onProgress({from:T,state:"failed",details:"Could not convert URI to native path",path:e.uri,elapsedMs:Date.now()-t}),{uri:e.uri,unlinked:!1};const s=await(0,b.statMaybe)(r);if(null==s)return(0,S.syncReport)().onProgress({from:T,state:"noop",details:"Failed to delete: no such file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(!s.isFile())return(0,S.syncReport)().onProgress({from:T,state:"noop",details:"Failed to delete: not a file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(y.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,d.thenOrTimeoutError)((0,l.default)(r,{glob:!1}),i),await function(e){return(0,m.untilTrue)((async()=>null==await(0,b.statMaybe)(e)),{timeoutMs:f.ShortCommandTimeoutMs})}(r))return(0,S.syncReport)().onProgress({from:T,state:"deleted",details:"Moved file to trash",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0};(0,P.logger)().warn("soft-delete("+r+") didn't seem to work: the file is still there?")}catch(e){(0,S.syncReport)().onProgress({from:T,state:"note",details:"Failed to soft-delete file to trash: "+(0,p.errorToS)(e),path:r,elapsedMs:Date.now()-t}),(0,P.logger)().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}try{return await(0,d.thenOrTimeoutError)(o.unlink(r),i),(0,g.ee)().emit("fileChanged",r),(0,P.logger)().info("unlink("+r+") successful"),(0,S.syncReport)().onProgress({from:T,state:"deleted",details:"Permanently deleted file",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0}}catch(i){return(0,S.syncReport)().onProgress({from:T,state:"failed",details:"Could not move file to trash or delete: "+(0,p.errorToS)(i),path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!1}}}t.trashOrUnlinkFileUris_=async function(e){const t=[];for(const{uri:i,mountpoint:r}of(0,u.uniqBy)(e,(e=>e.uri)))try{t.push(await _({uri:i,mountpoint:r}))}catch(e){t.push({uri:i,unlinked:!1,error:e})}return t},t.trashOrUnlinkFileUri=_},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),s=i(41400),n=i(55835),a=i(92782),o=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),h=i(87128),f=i(95696);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=n(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await a.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(76760)),n=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),w=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function v(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function T(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=v,t.zcat=async function(e,t){try{return v(e,t)}catch(t){return void w().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void w().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=T,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await T(e,t)}catch(t){w().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},87408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(63870),s=i(18454),n=i(89035),a=i(82638);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...s.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:s.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},18454:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b,S,P,T=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},_=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const M=i(19851),E=i(40958),D=i(76790),x=i(22573),k=i(41400),F=i(50357),C=i(26905),A=i(50268),I=i(55835),O=i(68708),L=i(30976),R=i(51926),N=i(13538),B=i(42279),j=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),q=i(50213),H=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Z=i(77740),Y=i(98314),X=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),se=i(21525),ne=i(82638),ae=(0,M.lazy)((()=>(0,q.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{T(this,s,"f",l).push(e+": failed: "+(0,Y.errorToS)(t)),this.onResultChange()})),T(this,s,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return T(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){T(this,s,"f",l).push((0,R.isString)(e)?e:(0,Y.errorToS)(e)),this.onResultChange()}static lastErrors(){return T(this,s,"f",l).toA()}static addLoadingMsg(e){T(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,E.compact)((0,j.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:T(this,s,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[T(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=T(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>T(this,s,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return T(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,A.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=T(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=s.summary();if(e.pendingCount>0){const t=await Promise.all(s.testResultsCritical());e=s.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){s.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,C.shortStack)());else{this.onResultChange(),T(this,s,"f",l).clear(),T(this,s,"f",d).clear(),T(this,s,"f",h).clear(),T(this,s,"f",c).clear(),this.summary.clear(),_(this,s,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new s(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return T(this,s,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,n,o,l,u,c,d,h,f,m,S,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=n,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=S,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),v.set(this,(0,M.lazy)((async()=>{await T(this,p,"f").prior(),(0,F.eql)(T(this,g,"f"),T(this,r,"m",w).call(this))||(this.onReset?.(),await this.refresh(),T(this,v,"f").unset())}))),this.refresh=(0,M.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await T(this,p,"f").prior();const e=T(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,q.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[A.HealthCheckSections.ordinal(this.section),l??999,this.id],_(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>T(s,s,"f",a).enqueue({name:this.id,l:()=>T(this,r,"m",b).call(this,o)}),ttlMs:S}),"f"),this.isCritical&&T(this,p,"f").watchLater({onChange:s.onCriticalResult,onError:s.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>T(this,v,"f").call(this)))}isStale(){return T(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return T(this,p,"f").settledCount()}reset(){return T(this,p,"f").unset(),this.onReset?.(),_(this,g,{starting:!0},"f"),this}setTTL(e){T(this,p,"f").setTTL(e)}result(){return T(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return T(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return T(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??T(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,E.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,E.isNotEmpty)(i)&&(r.links=(0,E.uniqBy)(i)),(0,E.isNotEmpty)(t)&&(r.buttons=(0,E.uniqBy)(t)),r}t.HealthCheck=oe,s=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,v=new WeakMap,r=new WeakSet,o=function(){return(0,E.filterInPlace)(T(this,s,"f",n),(e=>!e.isPending)),T(this,s,"f",n)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,ne.summarizeHealthChecksSync)({errors:T(this,s,"f",l),skipPending:T(this,s,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&_(this,s,!0,"f",u),i.state!==T(this,s,"f",c).last?.state&&T(this,s,"f",c).push({state:i.state,ts:Date.now()}),i},w=function(){return(0,O.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},b=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,C.shortStack)()}),_(this,g,T(this,r,"m",w).call(this),"f");try{if((0,Z.getDevEnvFlag)("PS_SLOMO")&&await(0,k.delay)((0,L.randomInt)(.3*i,.7*i)),this.isSkipped())return T(this,r,"m",S).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const s=await(0,N.thenOrTimeoutError)(e(),i);return T(this,r,"m",S).call(this,{test:s,elapsedMs:Date.now()-t})}catch(e){return T(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},S=function({test:e,src:t="#toResult",elapsedMs:i}){var r,n;const a=s.normalizeMsg(e.msg),o=e.level??((0,z.toS)(a).toLowerCase().includes("error")?"error":(0,z.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,E.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(_(this,y,(n=T(this,y,"f"),r=n++,n),"f"),r),(0,$.ending)()?u:this.logger.tap({level:se.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const s=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,x.toNotBlank)((0,Y.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,X.isFatalError)(e)&&s.toLowerCase().includes("warn")?"warn":"error"),T(this,r,"m",S).call(this,{test:{msg:s,level:t},src:"#toErrorResult",elapsedMs:i})},n={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new U.CountingSet},f={value:[]},oe.all=(0,M.lazy)((()=>Object.freeze((0,D.sortBy)(T(s,s,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,H.debounce)((()=>{ae().info("onCriticalResult()",s.summary.refresh())}),250),oe.summary=(0,M.lazy)((()=>T(s,s,"m",m).call(s))),oe.resetDebounced=(0,H.debounce)((()=>s.reset()),50)},85021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function w({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await w(e)})};const v=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...v(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...v(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...v(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>v.unset()))})),t.summarizeHealthChecksSync=b},95242:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),w=i(57159),v=i(83278),b=i(95696),S=i(62105),P=i(84258),T=i(38156),_=i(69589),M=i(28874),E=i(47783),D=i(29990),x=i(16047),k=i(42725),F=i(4192),C=i(32876),A=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class O{constructor(e,t,i){r.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,_.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(r=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,S.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await n(this,r,"m",s).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:n,height:a,sha:l,mimetype:u}=t;if(null==s||null==n||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,D.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:n,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(k.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,D.equivalentFitSizes)(r,s)){const n=(0,D.fitSizes)(e,e.mimetype),a=(0,o.diff)(r,s);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=n.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:n});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=O,s=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new T.PushProgressObserver({path:e.nativePath,op:"Building previews"},k.ImageSize.sq().length+k.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:k.ImageSize.largestFit().max});if(null==a)throw new w.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,x.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,v.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,D.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=k.ImageSize.largestSq(),b=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,h.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of l){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&r.reducer===C.Fit&&M.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of k.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=M.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(r)+" -> "+(0,u.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new w.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),w=i(70417),v=i(35721);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,v.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,v.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,w.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,v.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},33106:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(9288)),n=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(e);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(40958),s=i(33374),n=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),w=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function v(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){w().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void w().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=v(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void w().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=v,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void w().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),s=i(54993),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),s=i(19851),n=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),w=i(55222),v=i(63870),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+w.TokenRadix.randomChars(2),w.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,v.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(9288)),n=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),w=i(88561),v=i(95696),b=i(17217),S=i(50213),P=i(23624),T=i(28874),_=i(12089),M=i(16170),E=i(1078),D=i(33106),x=i(86580),k=i(78011),F=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const C=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void C().warn("imageHash() failed for "+e,t)}};const A=(0,n.lazy)((()=>new w.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=v.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,x.fitToResolution)(i.dimensions,Math.round(T.Settings.dominantColorPixels.valueOrDefault)),n=await(0,F.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,x.fitToResolution)(i.dimensions,T.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,F.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,F.toSharp)(t).removeAlpha();(0,M.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),w=await(p?k.meanDiffHash:k.meanDiffHashCIELAB)(y()),v=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(w.meanHash),diffHash:(0,P.b64encodeBits)(w.diffHash),dctHash:(0,P.b64encodeBits)(v),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,M.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:A,impl:I}),t._imageHash_=I,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},80361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(33374),l=i(57924),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(21605),m=i(48884),p=i(50213),g=i(97352),y=i(85810),w=i(3048),v=i(32848),b=i(82647),S=i(38812),P=i(70417),T=i(23624),_=i(28874),M=i(86580),E=i(48368),D=i(2090),x=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,w.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,w.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const k=/A{20}=?$/;function F(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(k))}function C(e,t,i=E.HashDim){const r=(0,T.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function A({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=C(e,i,r),l=C(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));x().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function I(e,t,i="debug",r={}){return x().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??F(r.meanHash))||(s.isGreyscale??F(s.meanHash))),f=A({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,M.validRotations)(r,s)}),m=A({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=A({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,v.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void x().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,w=(0,M.aspectRatio)(r),S=(0,M.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=w&&null!=S&&!(0,o.isCloseAspectRatio)(w,S);let T=0,k=0;n&&(k+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,T+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(k+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,T+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(T+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,k+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const C=R((T+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),I=R((k+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,D.fmtAspectRatio)(w)} vs ${(0,D.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,C)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,C)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=I,z=j&&N.avg>=C;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:C,imageCoeffDelta:T,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:I,colorCoeffDelta:k,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:w,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return x().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=F,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(k))?(0,h.padding)("0",2*i*i):"",s=C(e,t,i);return f.Rotations.map((e=>(0,T.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=A,t.isSimilarImage=I,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return I(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},42725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},4192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},78011:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(9288)),n=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},48604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),s=i(31586),n=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(9288)),n=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,n.lazy)((()=>{s.default.simd(l.Settings.enableSIMD.valueOrDefault),s.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),s.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(77988),n=r(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),w=i(56519),v=i(56038),b=i(57159),S=i(95696),P=i(17217),T=i(28874),_=i(47783),M=i(16170),E=i(95141),D=i(54979),x=i(1078),k=i(63870),F=i(86580),C=i(277),A=i(16047),I=i(13940),O=i(5733),L=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await z(e,t))?.nativePath}async function j(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,k.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=j,t.toSharp=function(e){const t=e;if((0,O.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:T.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,v.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=N().addParameterContext(e.nativePath);(0,O.setupSharp)();const n=await(0,D.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,x.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,M.isVideoMimeType)(n),S=(0,M.isLibrawMimeType)(n),P=a.dimensions,k=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==k?.width||null==k?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:k,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const I=(0,F.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),z=(0,M.isSharpMimeType)(n)&&null==t,V=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||z||V)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:z,isMirrorOrientation:V});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...T.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...T.Settings.embeddedThumbnails.values);const a=k.width*k.height*.2,u=k.width*k.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>j(e,n,t,k,I)))}}}(0,M.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,C.isHeifSupported)()&&f("heif",(()=>(0,w.thenMap)((0,C.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,w.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,L.isVideoSupported)())try{return await(0,w.thenMap)((0,L.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,v.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=z},181:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(9288)),n=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),w=i(54979),v=i(63870),b=i(5733),S=i(50961),P=i(66106),T=i(51210),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&_().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const M=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,v.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return M().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:M,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,w.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,T.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),w=i(56038),v=i(31562),b=i(98314),S=i(34102),P=i(88561),T=i(95696),_=i(17217),M=i(74128),E=i(31843),D=i(70417),x=i(33847),k=i(28874),F=i(94678),C=i(43207),A=i(47783),I=i(16170),O=i(95141),L=i(1078),R=i(63870),N=i(89782),B=i(13940),j=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,j.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,E.lerp2d)(e,{x:76800,y:k.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:k.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function q(e){return await(0,t.isVideoSupported)()?T.PosixFile.for(await(0,t._extractVideoFrame_)((0,_.toNativePath_)(e))):void 0}async function H(e,t){const i=V("extractVideoFrame",e),r=T.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,j.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,B.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,A.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,N.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,C.extractDurationSec)(l),m=Math.min(f??0,k.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,j.ffmpegFrame_)(t),!1===await(0,v.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,A.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function G(){return k.Settings.transcodeVideos.valueOrDefault&&await(0,j.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,A.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,C.extractDurationSec)(i);if(!(0,c.gt)(n,k.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=q,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await G())return;const n=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,A.readTags)(e),h=(0,L.extractSizeInfoFromTags)(d),m=(0,C.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,A.readRawTags)(t),r=await(0,A.readRawTags)(e),s=(0,C.extractDurationSec)(r),n=(0,C.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),s=k.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,F.extractBitrateKbps)(i)??k.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,w.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new x.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:r.halt,...g},m=k.Settings.transcodeMaxDim.valueOrDefault,p=(0,D.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,j.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,M.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-n})}catch(t){throw(0,M.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:Date.now()-n}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await q(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,j.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),w=i(84258),v=i(28874),b=i(76280),S=i(63870),P=i(19769),T=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function _(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:v.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=_;const M=/ffmpeg version n?(?\S+)/i,E=(0,u.lazy)((async()=>{const e=await _();if(null==e)return void T().info("failed to find ffmpeg in $PATH",{ffmpegPath:v.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=M.exec(t.result)?.[1];return T().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function D(){E.unset(),t.ffmpegVersionDescription.unset()}function x(e){const t=e?.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function k(e){const t=[...v.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(v.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function F(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function C(e){const t=v.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(E(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",D),(0,g.ee)().on("clearToolCache",D)})),t.ffmpegVersion_=async function(){return await E.prior()??E.refresh()},t.isFFmpegSupported=async function(){return null!=await E()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=k,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...k(t),...C(t),...x(t),"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...F(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){T().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return T().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return T().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await _(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(19851),s=i(42659),n=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),w=i(89782),v=i(13940),b=i(42725),S=i(19769),P=(0,r.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,v.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>D(e,t)})};const T=["-T"],_=["-Z","-"],M=["-o","1"],E=["-t","0","-j"];async function D(e,t){const i=await(0,w.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=b.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[...T,..._,...M,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],v={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:v});const D=(0,c.execFile)(g,y,void 0,v),x=[];function k(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});x.push(r)}}if(D.on("error",k),D.stderr.on("data",k),await t.writeStream_(D.stdout),(0,s.isNotEmpty)(x))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:x,path:e.nativePath});(0,c.endProcess)(D)}t.dcraw_emu_=D},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},42042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(22573),s=i(28874),n=i(81674);t.getEmail=async function(){const e=s.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),w=i(50213),v=i(56519),b=i(76596),S=i(46292),P=i(87290),T=i(77740),_=i(34102),M=i(83278),E=i(28874),D=i(37692),x=i(71706),k=i(83950),F=i(72042),C=i(33603),A=i(48132);t.k=(0,y.rolazy)((()=>(0,x.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,w.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,F.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,T.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function L(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:k.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,v.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await L((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,A.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function B(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=L,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await L(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof k.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,T.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:A.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),(e=>M.BaseFile.for(e))),s=(n=(0,l.flatten)((await(0,v.someOrTimeout)([()=>function(e){return L(E.Settings[(0,t.k)().L].value,"Settings",A.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:A.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,f.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l))),(e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,o.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset())),D.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=B,t.l=async function(){try{return await B()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await B()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},84194:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(40958),a=i(76790),o=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),h=i(19851),f=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function w(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=w,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(w(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const v=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||v.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=w(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==w(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(45599),o=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),h=i(50213),f=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),w=i(45879),v=i(70854),b=i(57902),S=i(72308),P=i(43334),T=i(24399),_=i(7014),M=i(30933),E=i(71706),D=i(84194);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const x=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function k(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=k;const F=(0,a.defer)((()=>(0,m.thenMap)(k(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),C=/o\.e\.m\./i;async function A(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,w.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(C)))}async function I(){return P.isLinux?(await A("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function O(){return P.isLinux?(await A("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await A("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void x().warn((0,t.k)().i+" failed",e)}}async function N(){return(await T.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,M.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,r.compactBlanks)(await A("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,v.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,v.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,F,R,V,W,z,I,O,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return x().tap({msg:"sids()",result:(0,D.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,f.isTest)())for(const t of e)H.add(t)},t.clearSids=function(){(0,f.isTest)()&&H.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},34474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(40958),s=i(42659),n=i(41400),a=i(96249),o=i(68708),l=i(34666),u=i(20214),c=i(71371),d=i(50213),h=i(42638),f=i(31562),m=i(98314),p=i(89968),g=i(28874),y=i(4904),w=i(57902),v=i(89241),b=i(83954);function S(e=10*s.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(w.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-s.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new v.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*s.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-s.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),s=i(23560),n=i(66184),a=i(72210);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),s=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function w(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...w(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),w=i(31256),v=i(28538),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new w.GelfLogFormatter,this.logFilter=new v.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),s=i(42659),n=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),s=i(31586),n=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),s=i(57902);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,s.set(this,[]),n.set(this,(0,l.lazy)((()=>{o(this,s,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,s,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,n,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,r,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,r,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){if(null==e||0===o(this,s,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,s,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),s=i(50989),n=i(28874);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=n.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},89241:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),h=i(38522),f=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),w=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),s.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,s,!0,"f")})),this.stream.on("end",(()=>{u(this,s,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,s,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,s,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,s,!0,"f");else{const t=(0,w.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),s=i(76760),n=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),w=i(22277),v=i(25764),b=i(38836),S=i(99331),P=i(42638),T=i(76596),_=i(98314),M=i(89968),E=i(29882),D=i(28874),x=i(28981),k=i(20839),F=i(21727),C=i(66184),A=i(57902),I=i(72210),O=i(98192);function L(e){const t=(0,x.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),v.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new w.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await M.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,C.ifLog)(A.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,_.errorToS)(t))))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,T.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,F.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,_.errorToS)(e))))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await M.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),s=i(82328),n=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),w=i(31586),v=i(409),b=i(23560),S=i(81168),P=i(78406),T=i(25764),_=i(20197),M=i(14977),E=i(36868),D=i(28874),x=i(32105),k=i(20839),F=i(21727),C=i(66184),A=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:T.EndableRanks.logger,unref:!0,onEnd:()=>c(this,s,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:x.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:b.processName,logFilter:C.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,v.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,A.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,w.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,F.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,M.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),s=i(84542),n=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),s=i(76790),n=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),s=i(41400),n=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),w=i(66184),v=i(28538),b=i(24068),S=i(43705),P=i(51879);function T(){(0,w.logFilter)()instanceof v.LogFilterImpl||w.logFilter.set(new v.LogFilterImpl),_();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new S.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,n.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&b.LogTail.instance()}function _(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=T,t.setupLogFormatter=_,(0,s.later)((()=>{h.Settings.logStdout.watchLater(T),h.Settings.logDir.watchLater(T),h.Settings.tailLogs.watchLater(T),h.Settings.logColor.watchLater(_),h.Settings.logLevel.watchLater((()=>w.defaultLogLevel.unset()))}))},83954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(89179);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},82647:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p69(){return n(this,r,"m",s).call(this,.5)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,s=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},44983:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(76790),s=i(93973);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},36372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(76790),s=i(42659),n=i(31586),a=i(97238),o=i(50597),l=i(9103),u=i(55222);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},38812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(21605);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}×${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),s=i(65713);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function w(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=w;class v{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new v;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function T(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=w(t,((t,r)=>(t-i)*(r-e))),s=w(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=T,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(T(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(38522),s=i(22573),n=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(48161)),n=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),w=i(34102),v=i(26293),b=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==b.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=S.exec(e)}function T(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=T,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=T(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const _=(0,s.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,w.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=T(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),s=i(19851),n=i(54993);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(22573),s=i(51926),n=i(83556);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),s=i(59455),n=i(31562);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),w=i(97790),v=i(59455),b=i(54993),S=i(54557),P=i(19851),T=i(50213),_=i(88158),M=i(409),E=i(78406),D=i(25764),x=i(99331),k=i(56519),F=i(46292),C=i(8769),A=i(83278),I=i(32144),O=i(29882),L=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,T.mkLogger)("proc.Pids"))),j=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,O.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,v.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??L.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,f.isEmpty)(s))return B().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,N.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){B().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!z(r,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:r}),a.push(W(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,C.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,s,"f").delete(l),o(this,s,"f").getOrSet(l,(async()=>{const i=o(this,r,"m",n).call(this,e.pid),s=(0,w.opt)((0,_.Try)((()=>(0,O.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:s,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,s,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,v.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,r,"m",n).call(this,e);return(0,k.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new E.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:D.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=U,s=new WeakMap,a=new WeakMap,r=new WeakSet,n=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,F.configDir)(),(e=>new U(A.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const s=i(31421),n=i(48161),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),w=i(84968),v=i(48963),b=i(56519),S=i(84777),P=i(8103),T=i(45879),_=i(43334),M=i(24399),E=i(45643),D=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function k(e){if(_.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,T.readFileMaybe)("/proc/"+i+"/stat")));return D().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,E.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:N)).filter((e=>x(e)&&t.includes(e.pid)));return D().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=x,t.pidInfo=async function(e){return(0,b.thenMap)(k([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,b.thenMap)((0,E.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=k;const F="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function A(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return R(e);const t=[F,"-Id",A(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,v.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,v.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===a.default.pid))||r.push({pid:a.default.pid,start:new Date(w.StartTs),cmd:"node "+a.default.title}),r}async function N(e){return t=(await(0,S.stdoutResult_)("ps",["-p",A(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(_.isLinux)return(0,c.toGt0)((0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){D().warn("clk_tck failed",{error:e})}return 100})),j=(0,g.lazy)((()=>Date.now()-(0,n.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,s=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(s)?{pid:i,cmd:r,start:new Date(j()+s/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),s=i(42659),n=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),w=i(99331),v=i(56519),b=i(31562),S=i(84777),P=i(34102),T=i(43334),_=i(28874),M=i(63870),E="{ready}",D=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,v.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,w.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,v.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,s.lazy)((()=>{if(!T.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,w.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),s=i(91655),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874),l=(0,n.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,s.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,s.pick)(e??{},"retries","halt","path"),...(0,s.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},86941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(19851),s=i(59455),n=i(72993),a=i(46292),o=i(95696),l=i(50213),u=i(83179),c=i(28874),d=i(2858),h=i(84438),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),n=await t.resolve_();if(null==r||null==n||n.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=n.join("licenses");for(const r of(0,s.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=n.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),s=i(22573),n=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function w(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function v(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){T(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&w(),y("strictDeduping",e)&&v(),(y("optOut",e)||y("noNetwork",e))&&_()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(m.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=w,t.setStrictDeduping=v;const b=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],S={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function T(e){for(const t of b)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:S;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function _(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=T,t.disableExternalNetworkRequests=_},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),s=i(53265),n=i(87652);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},4936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(55835),l=i(51926),u=i(50213),c=i(81168),d=i(79842),h=i(21330),f=i(51275),m=i(29882),p=i(28874),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+e.replace(/'/g,"′")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),s=i(83556);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),w=i(40583),v=i(81168),b=i(44198),S=i(96706),P=i(34102),T=i(28283),_=i(81075),M=i(98778),E=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?n(this,r,"m",s).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?n(this,r,"m",s).call(this,e??t)+": "+i:null==this.fromEnv(e)?n(this,r,"m",s).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,v.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,S.caseInsensitiveEnv)():new w.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,b.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,T.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(T.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return _.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,b.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&S.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,b.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&S.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new w.CaseInsensitiveValued(e)))??(0,S.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,v.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],E.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,v.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],E.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,v.wrap)(["",e+": "+r],E.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,s=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),s=i(51168),n=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),w=i(40583),v=i(79840),b=i(7282),S=i(12801),P=i(4328),T=i(70488),_=i(84248),M=i(5531),E=i(99315),D=i(34365),x=i(34580),k=i(96706),F=i(50274),C=i(33866),A=i(52086),I=i(48584),O=i(45969),L=i(43334),R=i(24540),N=i(70379),B=i(71300),j=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),q=i(30577),H=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Z=i(71988),Y=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),se=i(57039),ne=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(b.isProd);const we=()=>!(0,t.isProd)();function ve(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function be(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>we()?"1":"25"}),imageCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>we()?32:1024}),quiet:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:be}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Y.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:be}),useFsWatch:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new se.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>H.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:H.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>H.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Y.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new Y.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),minDelayBetweenSpawnMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,T.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>we()?"5s":"5m"}),streamFlushMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>v.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ne.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>we()?50:500,min:1,max:5e3}),enableArchive:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ve()}),enableRemove:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ve()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:D.SynchronousModes,defaultValue:D.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>we()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:we()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>we()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Y.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Y.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!we()||!(0,O.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:C.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Y.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Y.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:q.UpdateChannels}),autoUpdateCheck:new Y.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Y.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Y.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Y.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Y.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Y.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Y.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Y.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":s.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Y.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Y.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!we()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:F.SidecarExts,defaultValue:F.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new ne.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Y.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Y.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!we()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:A.CropStrategies.attention,strEnum:A.CropStrategies}),videoFrameAtSec:new ne.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Y.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Y.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Z.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Y.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>j.DefaultIncludedPreviewTags}),disableAllFilters:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Y.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new se.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ne.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!we()}),tagKeywordsFromPath:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Y.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new ne.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!we()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Y.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Y.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function Se(e){const i=((0,u.blank)(e)?"":e).split(n.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(n.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=Se,t.pathWithDefaults=(0,a.lazy)((()=>Se((0,k.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const Te=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Te().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new w.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(31586),n=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),w=i(15674),v=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=c.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,v.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>(0,n.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,n.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,w.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel,v.Settings.minBusyPct.opts.defaultValue=()=>(0,s.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),w=i(54993),v=i(50213),b=i(81168),S=i(83556),P=i(87290),T=i(98314),_=i(34102),M=i(83278),E=i(95696),D=i(60865),x=i(4175),k=i(83179),F=i(81075),C=i(28874),A=i(41692),I=i(84438),O=i(32707),L=i(6707),R=i(98778),N=i(55018),B=i(10357),j=(0,r.lazy)((()=>(0,v.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,O.systemSettingsFile)()){if(null!=e)return X(M.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,L.readTomlFile_)((0,O.systemSettingsFile)()))?.[C.Settings.libraryDir.name])}catch{return}}function U(e){return(0,L.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function q(){return U((0,O.systemSettingsFile)())}function H(e){return U(z(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:C.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,k.settingsToObj)(i),wip:r}),r){const t=await(0,L.readTomlFile_)(s),i=await(0,L.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function K(e=(0,O.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,C.persistedSystemSettings)()),t}function Z(e){return X(z(e))}async function Y(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,C.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,C.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,T.errorToS)(e)),[]}}async function Q(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,L.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,C.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,C.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}})));return t.info("loaded",{settings:(0,k.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,x.handleDeprecatedSettings)(),(0,x.handleMetaSettings)(a),{settings:a,warnings:n}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return C.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=q,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await q()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await H()&&await Y()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",G),(0,_.ee)().on("settingsChanged",G),C.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,D.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(E.PosixFile.for(e),(0,C.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=Y,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([C.Settings.noNetwork,C.Settings.httpPort,C.Settings.license,C.Settings.logStdout,C.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(C.Settings))ee().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),C.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(E.PosixFile.forMaybe((0,O.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,_.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${D.versionMajorMinor}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,w.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>function(e,t){return(0,r.compact)((0,a.splitStringArray)(e)?.map((e=>t.getCI(e))))}(t,e.strEnum),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),s=i(55835),n=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),s=i(44652),n=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),s=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),s=i(81168);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),w=i(81168),v=i(76596),b=i(79842),S=i(66649),P=i(21330),T=i(98725),_=i(928),M=i(54261),E=i(89724),D=i(17415),x=i(88600),k=i(51275),F=i(29882),C=i(17217),A=i(68284),I=i(57902),O=i(28874),L=i(65162),R=i(71300),N=i(14036),B=i(61424),j=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,b.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,b.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,A.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,T.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,D.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,D.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,M.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,_.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,x.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,D.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,b.datedToStartDateTime)(this.date)??(0,b.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,b.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function q(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],s=r;if((0,x.isValidDate)(t)){if((0,D.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||R.OverrideUTCZoneTags.includes(s))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,w.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,b.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,b.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,b.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function H(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,T.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,b.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,T.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,x.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,w.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,F.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",q(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??s("tags",q(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("stat+bname",await(0,B.extractStatBname)(e)))??(n?void 0:s("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",H(e,t)))??(n?void 0:s("path",G(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await $(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return q(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),s=i(97352),n=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(77988),n=r(i(76760)),a=r(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),w=i(12168),v=i(56038),b=i(4867),S=i(36557),P=i(98247),T=i(21330),_=i(98725),M=i(23467),E=i(88561),D=i(95696),x=i(17217),k=i(16287),F=i(50213),C=i(17921),A=i(7282),I=i(88158),O=i(23560),L=i(28874),R=i(12089),N=i(81168),B=i(63870),j=i(15674),z=i(28544),V=i(43207),W=i(72180),U=i(75767),q=i(12788),H=i(80495),G=i(14036),$=i(67083),J=i(3432),K=i(28630),Z=i(15912),Y=i(30748),X=i(16170),Q=i(95141),ee=i(7330),te=i(54979),ie=i(1078),re=i(61424),se=i(8791),ne=(0,o.lazy)((()=>(0,F.mkLogger)("exiftool.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,S.batchClusterOptions)((0,A.isTest)()?8:(0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeoutError)({p:le().version(),timeoutMs:L.Settings.statTimeoutMs.valueOrDefault})},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,B.commandTimeoutMs)()})))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,x.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*w.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,N.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),s=await e.sidecar(),n=(0,X.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,X.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=D.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void ne().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ne().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,X.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,v.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values])if(!(0,W.isUtcTagName)(t)){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,T.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l)}const c=o?(0,Y.extractMakeAndModel)(n):await(0,re.inferMakeAndModel)(e,n);c.Make!==(0,Y.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,Y.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(n),h=await(0,z.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,V.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};(0,A.isTest)()&&(y.__parsedBy__=a.default.pid);const w={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(w,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(w)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,M.eqlAsync)(e.sha(),t.sha())||await(0,M.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,x.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,x.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,v.time)("exiftool.overwriteTags:"+e,(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,v.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,v.time)("exiftool.writeTags:"+e,(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await me(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=D.PosixFile.for(t),s=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:s}),await le().write(r.nativePath,s,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...L.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,G.isVideoExt)(n.default.extname(e))?[]:["-fast"]],r=await(0,v.time)("exiftool.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),ae&&(r.__instance=(0,C.safeUUID)()),r}}),t.parseTags=ge},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),w=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const v=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function T(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([T(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(T)):(0,u.compactBlankValues)(t)}function M({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of v){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of v)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of v){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>M({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>M({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>M({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>M({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,w.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),s=i(40958),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function w(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=w,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return w(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return w(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return w(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return w(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return w(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return w(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return w(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return w(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),s=i(45599),n=i(68708),a=i(50213),o=(0,s.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,n.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:s}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[s])&&(t[i]=t[s]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,n.pick)(e,"Directory","FileName"));for(const t of(0,n.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),w=i(50213),v=i(81168),b=i(66649),S=i(17415),P=i(29882),T=i(95696),_=i(17217),M=i(28874),E=i(47783);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>x({action:e,key:t,value:i})))}function x({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=x,t.InferAction="infer";const k=(0,s.lazy)((()=>(0,w.mkLogger)("tags.History")));function F(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function C(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function A(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,v.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,r){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!F(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=T.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=F,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,v.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=C(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=C,t.inferredToTags=A,t.ensureInferredHistoryRecords=async function(e,i,r){const s=D(t.Actions.infer,r),n=(M.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?A(r):void 0)??{};return M.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),I(i,s,n)},t.ensureHistoryRecords=I},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(53705)),n=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),w=i(72180),v=i(14245),b=i(61424),S=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,v.omitInvalidGeolocationTags)(t);{const e=T(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,w.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=_(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function T(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return S().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function _(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,u.toDated)(t[r]);if(null==s||(0,f.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return S().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return S().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=T,t.inferTzOffsetMinutesFromFilename=_},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),w=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function v(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):v(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>w.unset()))})),t.keywordToPath=function(e){const t=w();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=v,t.splitKeywords=b;const P=/^\(?none\)?$/i;function T(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function M(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,M);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,M).map((t=>[e.Keyword,...t]))}t.parseCategories=T,t.isKeywordStruct=_,t.parseKeywordStruct=M,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=T(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(_(i)?t.push(...M(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const w=/([\d. -]+)\s?mm\b/i,v=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=w.exec(e)?.[1].replace(/\s/g,""),i=v.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function w(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=w(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=w;const v={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(v))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},38010:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(50213),g=i(84885),y=i(66649),w=i(98725),v=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function T(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return v().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return v().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return v().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,w.parseDated)({input:e.When}));return null==r?v().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?v().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):v().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-T(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),s=i(54993),n=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},66039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(75020),u=i(59455),c=i(50213),d=i(68852),h=i(81168),f=i(70417),m=i(28874),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,w=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,v=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,w),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function T(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,v),null!=e&&(T(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(T(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(T(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(T(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const _=(0,s.compactBlanks)(t.split(/\s+/)),M=l.length,E=b.length;if(_.length>0)if(0===M&&E>0)l.push(..._);else if(0===E&&M>0&&1===_.length)b.push(..._);else if(1===_.length)l.push(..._);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?_.pop():_.shift()),l.push(..._)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function T(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function _(e,t,i){return T("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=T([t.modifier,t.lifespan]),r=T(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?T([r,e]):_(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),s=i(54993),n=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),s=i(40958),n=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,s.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),w=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),v=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return w().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return w().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return v().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},3127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(54993),s=i(42231);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),w=i(79842),v=i(21330),b=i(98725),S=i(51275),P=i(35280),T=i(19748),_=i(88561),M=i(95696),E=i(65238),D=i(17217),x=i(57902),k=i(28874),F=i(80496),C=i(65162),A=i(28544),I=i(47783),O=i(88840),L=i(30748),R=i(16170),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return k.Settings.siblingInference.valueOrDefault===F.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===F.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:x.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,v.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,v.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,v.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,T.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7,i=!0){if(!await j(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(r,(e=>(0,C.bname)(e))),n=(0,D.findFileIndex)(e,s);if(n<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),H(e,t,!1)):void 0;const l=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[s.slice(n-2*t,n),s.slice(n+1,n+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,C.bname)(e,!0),(0,C.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,w.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,w.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function w(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function v(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=w,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(w(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=v,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>v(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),s=i(22573),n=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),w=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function v(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await v(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void w().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?w().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=v,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),s=i(57975),n=i(57160),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",w=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class v{static isUri(e){return e instanceof v||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return M(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=w.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=k(i[4]||g),n=(i[5]||g).split("/").map(k).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?v.file(r.win32.join(M(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=v;const b=h.isWinPortable?1:void 0;class S extends v{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=M(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function T(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:T;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:T(o,!1)),r}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=T,t.uriToFsPath=M;const x=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(x)?e.replace(x,(e=>D(e))):e}t.percentDecode=k,t.toURI=function(e){return v.isUri(e)?e:v.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),s=i(40958),n=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),s=i(22573),n=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(9103),a=i(37628);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),s=i(30577);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),s=i(22573),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),s=i(9595),n=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},42233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(45200),s=i(98770),n=i(7014);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),s=i(22573),n=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),w=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function v(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=v,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await w());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(v)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),w=i(24399),v=i(28874),b=i(24541),S=i(60224),P=i(63870),T=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function M(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(M(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(M(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function x(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(M(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return w.PowerShell.instance().executeJsonToA(k())};const F=/\{([-a-z\d]{7,})\}/i;function C(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function A(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void T().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void T().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([C(e.HealthStatus,"healthy"),C(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return T().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,T().tap({msg:"uniqueId2uuid",result:(0,l.map)(F.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function I(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>w.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:v.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(x)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>w.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(T().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:v.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(A)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));T().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=A,t.volumeInfoWin=I},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),w=i(83278),v=i(8103),b=i(16287),S=i(45969),P=i(43334),T=i(69108),_=i(98770),M=i(44224),E=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,v.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,M.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>w.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,T.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await x(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,E.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const x=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),s=i(5233),n=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),w=i(98770),v=i(63870),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),T=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,w.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await T()],{timeoutMs:(0,v.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,w.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,v.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),s=i(19851),n=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),w=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(v)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?w().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){w().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const v=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),w=i(84777),v=i(34330),b=i(8769),S=i(34102),P=i(17217),T=i(16287),_=i(43334),M=i(28874),E=i(8540),D=i(68884),x=i(44224),k=i(24541),F=i(69375),C=i(63870),A=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function O(e=(0,C.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function L(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{M.Settings.libraryDir.watchLater(I),M.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&M.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),O((0,C.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux){const i=(0,x.maybeWatchProcMounts)();await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),O((0,C.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),O((0,C.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=M.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?k.mountpointsWin:x.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,C.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||M.Settings.validateMountpoints.valueOrDefault&&!await(0,T.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,S.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),I()})),M.Settings.mountpointsTtlMs.watch(O)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>L(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),L()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,w.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,C.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>L(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),w=i(28874),v=i(69108),b=i(68884),S=i(59107),P=i(69375),T=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await D()??await(0,c.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,b.isGioSupported)())try{await(0,c.thenMap)((0,b.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){T().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function M(e){return!w.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,P.isExcludedMountpoint)(e)&&(!w.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function D(e=_,t=M,i=E){if(y.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return T().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return T().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void T().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=D,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(_)?new h.FileWatcher(_,{recursive:!1,persistent:!1},(()=>{T().info("detected change in "+_),(0,d.setUnrefTimeout)((()=>S.mountpoints.refresh()),n.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),s=i(42659),n=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),w=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await M()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const v=["LocalName","RemoteName","Status"],b=["NETUSE","get",v.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function T(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,u.parseFixed)(v,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=T,t._netInfoWinWmic=_;const M=(0,w.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(T(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),s=i(12168),n=i(28874);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),w=i(95696),v=i(45969),b=i(28874),S=i(59107),P=i(63870),T=i(68995),_=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function E(e){return(0,a.isTrue)(e.ignorable)||(0,v.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function D(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function x(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=D(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function k(e){if(b.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of b.Settings.volumeUuidFilePaths.values){const i=w.PosixFile.for(e.mountpoint).join(t),r=await x(i).catch((e=>_().info("Failed to read "+i,{error:e})));if(null!=r)return _().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,T.volumeUuidSubpath)());if("/"===e.mountpoint)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(b.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(b.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,T.writeVolumeUuid)(e);if(!(0,n.blank)(t))return _().tap({msg:"readVolumeUUID(): wrote new "+(0,T.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return _().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),S.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(E(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>k(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>_().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=E,t.toVolumeUUID=D,t.readUuidFile_=x,t.readVolumeUUID=k},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),w=i(59455),v=i(48884),b=i(50213),S=i(7282),P=i(23560),T=i(28850),_=i(45255),M=i(81168),E=i(56519),D=i(4867),x=i(49776),k=i(9595),F=i(77740),C=i(44198),A=i(96706),I=i(8769),O=i(57159),L=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),j=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),q=i(43334),H=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Z=i(27461),Y=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=s.default.platform(),ne=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,ne),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,x.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ne.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,M.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:se}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))n.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function me(e,i){const r=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(r))return;const s=await(0,L.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function pe(e,t,i){const r=i.filter((e=>(0,M.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,M.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,W.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,M.equalsIgnoreCase)(n,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,S.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,w.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,D.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,O.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,T.shim0)({name:"fs.volumes",impl:async function(){if((0,S.isTest)()){const e=(0,p.toInt)((0,C.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeoutError)({p:q.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeoutError)({p:q.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,M.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,v.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),h=i(34238),f=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const a=n(i(37067)),o=n(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),h=i(50213),f=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),w=(0,u.defer)((()=>(0,h.mkLogger)("net.get")));async function v(e,t){return b({...t,url:e})}async function b(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?a.request:"https"===t.scheme?o.request:w().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??f.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",h=e?.agent??!1,b=r(t.toString(),{method:c,headers:u,timeout:n,agent:h},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const a={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&y.HttpStatusIs.redirect(a.statusCode)&&!(0,l.blank)(e.headers.location)?(w().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(v(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(w().debug("complete",{...a,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(a))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||b.write(e.body),b.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=v,t.httpRequest_=b},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),s=i(37692);let n=!1;function a(){return n}function o(e=!0){l(e),(0,s.writeStateFile)({paused:e})}function l(e){e!==n&&(n=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=a,t.pause=o,t.resume=function(){return o(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return a()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),s.minuteMs);function v(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=v,t.targetCpuLoadPct=b,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(b()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(b()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=v();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,w());return t=(0,a.clamp)(1,s,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const s=r(i(78474)),n=i(40958),a=i(76790),o=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),h=i(87290),f=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),w=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let v;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new s.default;let b=0;function S(){const e=(0,h.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-b>o.minuteMs;i&&(b=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(v?.nativePath)||(v?.close(),v=void 0),r&&null!=e&&(v??(v=new f.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=S()?.readJsonSync();for(const i of e?.events??[])T.get(i.e)!==i.ts&&(w().info("emitting event "+i.e),t.stateEvents.emit(i.e),T.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const T=new Map;function _(e){const i=S();if(null==i)w().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),s=function(e){const t=Date.now()-10*o.minuteMs;return(0,n.uniqByLast)((0,a.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:s};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=_,t.addStateEvent=function(e){const t=Date.now();T.set(e,t),_({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),s=i(87997),n=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function w(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:w((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=w,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return w(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return w(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},75761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function w({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function v({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const v=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=v):p.src=v,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(w({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=w,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...v({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=v},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),s=i(31586),n=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),s=i(22573),n=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function w(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function v(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=w,t.fmtLocalToShort=function(e){return(0,a.map)(w(e),m)},t.nextMidnightTs=v,t.msUntilMidnight=function(){return v()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),s=i(73872);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const w=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,w),w}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s.hasPrior=()=>r,s}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),s=i(21605),n=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),s=i(68708),n=i(34666),a=i(32639);function o(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,n.isPrimitive)(e)||(0,n.isPrimitive)(t))return e===t;if(!(0,s.isObject)(e)||!(0,s.isObject)(t))return!1;for(const i of(0,s.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),s=i(42659),n=i(55835),a=i(31586),o=i(12168),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),s=i(50357),n=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class s extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=s},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,(t=>!e(i,t,s)));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),s=i(22573),n=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=w(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,s){return!(null==s||!o(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,s.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function w(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function v(e){return o(e)&&e>0}function b(e){return o(e)&&e>=0}function S(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function T(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function _(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=v,t.firstGt0=function(...e){for(const t of e){if(v(t))return t;const e=y(t);if(v(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return v(t)?String(t):void 0},t.mapNumeric=S,t.map2Numeric=function(e,t,i){return S(e,(e=>S(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,n.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return S(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=T,t.toPrecisionMaybe=function(e,t){return d(e,(e=>T(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=_,t.times=function(e,t){if(!v(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return _(0,100,v(t)?P(100*(v(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function w(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function v(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=w(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=w,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=v,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=v(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),s=i(30976),n=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),s=i(54993),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),s=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=w,t.ensureSuffix=v,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return v(w(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=w((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),s=i(68708),n=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let s=!0;const n=setTimeout((()=>{s&&(s=!1,i(a.Timeout))}),t);try{n.unref?.();const t=await e;s&&(s=!1,i(t))}catch(e){s&&(s=!1,r(e))}finally{clearTimeout(n)}}))}async function c(e,t,i=!0){const s=await u(e,t,i);if(s===a.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return s}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?a.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return c(e,s,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,n.tot)(i);const s=await u(e,t,r);return s===a.Timeout?(0,n.tot)(i):s}},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),s=i(30301),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(30301),s=i(54993);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},58939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(55835),s=i(31586);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),s=i(30301),n=i(31586),a=i(97238),o=i(29652);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return n(e)??[]},t.optToA=n},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),s=i(23541),n=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},64526:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(27395),u=i(25764),c=i(38836),d=i(99331),h=i(45608),f=i(15056),m=i(87290),p=i(38835),g=i(57159),y=i(61704),w=i(95696),v=i(18454),b=i(13940),S=i(48604),P=i(19851),T=i(23560),_=i(28874),M=i(2858),E=i(7014),D=i(63870),x=i(15674),k=i(22573),F=i(38639),C=i(42659),A=i(56409),I=i(68708),O=i(25470),L=i(22526),R=i(41844);class N extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,T.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,k.blank)(e)||!(0,M._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired_(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new A.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted_(),await(0,M.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted_();const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,F.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,x.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted_(),(0,T.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted_(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),v.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.previews=(0,P.lazy)((()=>(0,I.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new R.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,T.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.onEnd=(0,P.lazy)((async()=>{if(!(0,d.ending)())for(const{ea:e,t}of[{ea:this.dbModelJanitor.clear(),t:5*C.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=w.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise.then((()=>this))}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup_(){return(await this.dbModelJanitor())?.backup_()}}t.Library=N,r=N,n=new WeakMap,s={value:void 0}},19113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(62105),s=i(181),n=i(94448),a=i(39604);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},18449:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(7282),s=i(96706),n=i(29325),a=i(28874);t.sentryEnabled=function(){return(0,s.isEnvTrue)("ENABLE_SENTRY")||(0,r.isProd)()&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},95629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(16436)),l=a(i(48161)),u=a(i(1708)),c=i(19851),d=i(19043),h=i(50213),f=i(31578),m=i(7282),p=i(96175),g=i(23560),y=i(84968),w=i(81168),v=i(37805),b=i(25764),S=i(38836),P=i(99331),T=i(85100),_=i(98314),M=i(68301),E=i(70025),D=i(8769),x=i(34102),k=i(34592),F=i(42042),C=i(34474),A=i(20839),I=i(57902),O=i(45969),L=i(43334),R=i(40958),N=i(22573),B=i(42659),j=i(41400),z=i(98553),V=i(55835),W=i(12168),U=i(59455),q=i(54993),H=i(18449),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,T.serviceExitTimeoutMs)(e.name),release:v.release,environment:(0,m.nodeEnv)(),maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(M.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,w.ellipsize)(i,256));const r=await X(e);return await(M.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,x.ee)().on("fatal",$),(0,x.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Z(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Z(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,F.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=v.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,k.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*A.DefaultLogFlushMs);const e=await(0,C.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,w.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,w.isString)(e.meta)?(0,w.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Z,t.sentryExceptionToS=Y,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[I.LogLevels.fatal,"fatal"],[I.LogLevels.error,"error"],[I.LogLevels.warn,"warning"],[I.LogLevels.info,"info"],[I.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},37158:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const p=m(i(29907)),g=m(i(1708)),y=i(57206),w=i(19851),v=i(50213),b=i(59880),S=i(23560),P=i(19913),T=i(71567),_=i(37805),M=i(38836),E=i(99331),D=i(45608),x=i(56038),k=i(55534),F=i(42499),C=i(49776),A=i(96706),I=i(98314),O=i(38835),L=i(70025),R=i(8769),N=i(57159),B=i(34102),j=i(33456),z=i(87408),V=i(85021),W=i(17181),U=i(86941),q=i(28874),H=i(41692),G=i(2858),$=i(69385),J=i(22573),K=i(42659),Z=i(41400),Y=i(56409),X=i(55835),Q=i(41583),ee=i(54993),te=i(95629);t.setupEventHandlers=(0,w.lazy)((()=>{(0,B.ee)().on("resume",(()=>(0,$.resume)())),(0,B.ee)().on("pause",(()=>(0,$.pause)()))}));class ie extends M.EndableWrapper{constructor(e){super(e),r.add(this),s.set(this,void 0),n.set(this,new Y.Latch),a.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,x.time)("Service.setup",(()=>f(this,r,"m",o).call(this))))),u.set(this,(0,w.lazy)((()=>{const e=g.default.stdin.pipe(new j.LineReader);return e.on("data",(e=>f(this,r,"m",d).call(this,(0,ee.toS)(e)))),e}))),(0,S.isBillingService)()||(0,H.setSettingsDefaults)(),h(this,s,(0,v.mkLogger)("Service("+this.name+")"),"f"),f(this,r,"m",c).call(this),this.setup_()}get name(){return super.name}get ready(){return f(this,n,"f").promise}get isReady(){return f(this,n,"f").isResolved()}setInputHandler(e,t){f(this,a,"f").set(e.trim().toLowerCase(),t)}}t.Service=ie,s=new WeakMap,n=new WeakMap,a=new WeakMap,u=new WeakMap,r=new WeakSet,o=async function(){try{(0,J.mapNotBlank)((0,A.getEnv)("PS_FATAL_"+this.name),(e=>{throw new N.WrappedError(e,{fatal:!0})})),(0,J.mapNotBlank)((0,A.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new N.WrappedError(e)}),5*K.secondMs)})),(0,P.setServiceName)(this.name),(0,b.setProcessTitle)(),(0,S.isMainService)()&&await(0,U.mergeUserDataDirs_)(),await(0,G.readSettings)(),await f(this,r,"m",l).call(this),(0,W.setupLogger)(),(0,y.addDefaultJsonRevivers)(),(0,C.cacheDir)(),(0,t.setupEventHandlers)(),f(this,u,"f").call(this),await(0,F.setupLuxon)(),q.Settings.startPaused.valueOrDefault&&(0,$.pause)(),(0,E.ending)()?f(this,n,"f").reject():f(this,n,"f").resolve()}catch(e){console.error((0,I.errorToS)(e)),f(this,n,"f").reject((0,Q.toErr)(e)),(0,D.exit)({reason:(0,L.addErrorFlags)(this.name+" setup failed: "+(0,I.errorToS)(e),O.FatalErrorFlag),status:14})}},l=async function(){(0,S.isPermaService)()||(0,B.ee)().on("fatal",(e=>(0,D.exit)({error:e,status:12}))),g.default.on("unhandledRejection",(e=>(0,X.map)(e,(e=>(0,R.onError)("unhandledRejection",e))))),g.default.on("uncaughtException",(e=>(0,X.map)(e,(e=>(0,R.onError)("uncaughtException",e))))),g.default.on("SIGINT",(()=>(0,D.exit)({reason:"SIGINT",status:0}))),g.default.on("SIGHUP",(()=>(0,D.exit)({reason:"SIGHUP",status:0}))),g.default.on("SIGTERM",(()=>(0,D.exit)({reason:"SIGTERM",status:0}))),p.default.isWorker&&g.default.on("disconnect",(()=>(0,D.exit)({reason:"disconnect",status:0}))),await(0,te.installSentry)(this)},c=function(){this.setInputHandler("--version",(()=>(0,T.stdoutWrite)({version:_.version}))),this.setInputHandler(k.ServiceExitCommand,(()=>(0,Z.later)((()=>(0,D.exit)({reason:k.ServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,T.stdoutWrite)(x.PromiseTimer.instance().report()))),this.setInputHandler(V.HealthCheckCommand,(async()=>(0,T.stdoutWrite)(await(0,z.getStatusSummary)({refresh:!0}))))},d=async function(e){if(f(this,s,"f").debug("onLine()",{line:e,ending:this.ended||(0,E.ending)()}),await this.setup_(),e.startsWith("--")){const t=e.split(/\s+/,1)[0],i=f(this,a,"f").get(t);null==i?(f(this,s,"f").error("onLine(): unknown command",{line:e,knownCommands:[...f(this,a,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else f(this,s,"f").error("onLine(): failed to process",{line:e})}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},46628:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(47783),c=i(97573),d=i(42231),h=i(40958),f=i(22573),m=i(68708),p=i(75020),g=i(54993),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function w(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function v(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(w));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...v(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...v(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=v},88224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(28874),o=i(42231),l=i(40958),u=i(20214),c=i(43487),d=i(46628),h=i(63175),f=i(4407),m=i(58886),p=i(32646),g=i(48144),y=i(60047),w=i(6186),v=i(42003),b=i(43723),S=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function P({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];if(t=(0,l.uniqBy)([e,...t],(e=>e.nativePath)),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,y.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),a.Settings.tagGeo.valueOrDefault)for(const e of t){const t=await(0,p.geoTagFile)(e);if(null!=t){u.push(t);break}}await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,b.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,g.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,v.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{S().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const P=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(w.normalizeTagRoot),o.joinTagPath)),T=await(0,w.tagDeltas)(i,P);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:P,result:T}),T}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await P({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=P},63175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(47783),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},4407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(47783),h=i(40958),f=i(55835),m=i(31586),p=i(75020),g=i(54993),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),w=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function v(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:v(e)})))}function T(e){if((0,m.within)(1,12,e))return(0,f.map)(w()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function M(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),T);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),w.unset()})),t.yearToOrdinal=v,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=T,t.dayTagRef=_,t.dateTag=M,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:M(r.date)}},58886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(19851),s=i(50213),n=i(42231),a=i(21404),o=i(40958),l=i(89937),u=i(75020),c=i(54017),d=i(94448),h=i(69032),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},32646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTagFile=t.geoTag=void 0;const r=i(48884),s=i(56519),n=i(50213),a=i(28874),o=i(47783),l=i(14245),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)((()=>(0,n.mkLogger)("curators.GeoTagger")));function p(e){const t=a.Settings.tagGeoMaxDistanceKm.valueOrDefault;if(t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t))return void m().warn("geoTag(): GeolocationDistance too large, skipping geo tag",(0,f.pickDeep)(e,...l.GeolocationFields));const i=a.Settings.tagGeoSynonyms.synonymMap(),s=a.Settings.tagGeoTemplate.valueOrDefault.map((t=>(0,r.first)(i.get(t)??[t],(t=>(0,f.pluckDeep)(e,t)?.value)))),n=(0,c.compactBlanks)(s);return m().tap({msg:"geoTag",result:0===n.length?void 0:(0,c.compact)([u.TagRoots.Where,...n]),meta:{picked:s}})}t.geoTag=p,t.geoTagFile=function(e){return(0,s.thenMap)((0,o.readTags)(e),p)}},48144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(47783),h=i(97573),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),w=i(96249),v=i(55835),b=i(75020),S=i(54993),P=i(6186),T=i(43723),_=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),M=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return _().tap({msg:"extractDashDashTags()",result:(0,v.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,v.mapOr)(M(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function D(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>M.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=D;const x=/\w{2,7}:\/\/\S+/g;function k(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(x,(e=>(i.push(e),"")));s.push(...(0,v.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,w.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function F(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function C(e,t){const[i,s]=(0,r.partition)(k(e),T.isWhoTag),n=(0,w.flatten)(i.map(T.nameTag)),a=(0,m.uniq)((0,w.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=F([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=k,t.dedupeKeywordPaths=F,t.processKeywords=C,t.keywordTagFiles=async function(e,t){return C([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,w.flatten)(e.map(D)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,w.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},60047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(56519),s=i(28874),n=i(47783),a=i(75020),o=i(40958),l=i(22573),u=i(55835);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},6186:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhereRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(50213),s=i(28874),n=i(42231),a=i(75020),o=i(40958),l=i(22573),u=i(45599);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.WhereRoot={name:a.TagRoots.Where,ordinal:5},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,t.WhereRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Where,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase()))),g=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhereRoot,...e.slice(1)]:g.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},42003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[w(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function w(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}t.friendlySubtype=y,t.fixCase=w},43723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(19851),s=i(50213),n=i(28874),a=i(47783),o=i(28630),l=i(66039),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(v)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function w(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function v(e){if(!(0,d.blank)(e))return Array.isArray(e)?(w(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=w,t.nameTag=v},98348:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(48884),d=i(19851),h=i(23560),f=i(25764),m=i(38836),p=i(99331),g=i(5916),y=i(12959),w=i(55332),v=i(91872),b=i(80632),S=i(51040),P=i(44955),T=i(15056),_=i(70025),M=i(57159),E=i(18454),D=i(28874),x=i(5233),k=i(42659),F=i(31586),C=i(68708),A=i(30976),I=i(17036),O=i(27134),L=i(35052);class R extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=k.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),D.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*k.secondMs),this.migrate_=(0,g.lazyAsync)({desc:"db.migrate",later:async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{await(0,O.verifyDb_)((()=>this.db))}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||D.Settings.dbForceRecover.valueOrDefault)&&(E.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new I.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e}}}),this.tableInfo_=(0,d.lazy)((()=>(0,L.localTableInfo)(this.db)))}toJSON(){return(0,C.pick)(this,"schema","dbFile")}get isOpen(){return!0===l(this,n,"f")?.open}get inTransaction(){return this.isOpen&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(t||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,b.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===D.Settings.dbAutoVacuumMode.valueOrDefault&&(0,F.gt0)(D.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%D.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&(this.logger.info("running incremental_vacuum..."),l(this,n,"f")?.pragma("incremental_vacuum")),l(this,n,"f")}async verify_(){await(0,O.verifyDb_)((()=>this.db))}assertHeartbeat_(){const e=(0,A.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{this.logger.info("closing db",l(this,n,"f")),await(0,x.retryOnReject_)((()=>{!0===l(this,n,"f")?.open&&l(this,n,"f")?.close()}),{timeoutMs:D.Settings.dbBusyTimeoutMs.valueOrDefault,maxRetries:5,errorIsRetriable:_.isSqliteBusyError,retryDelay:k.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>this.db),(()=>(0,O.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db),(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db),(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,O.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,T.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,P.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,y.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,w.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=R,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,F.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},25470:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(66364),d=i(50213),h=i(23560),f=i(78406),m=i(25764),p=i(38836),g=i(99331),y=i(56038),w=i(12959),v=i(55332),b=i(76187),S=i(73209),P=i(28874),T=i(42659),_=i(75240),M=i(95700),E=i(22526),D=i(45648),x=5*T.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class k extends f.EndableInterval{static for(e){return new k(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:T.minuteMs,rank:m.EndableRanks.db,endTimeoutMs:5*T.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new p.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),m.EndableRanks.postdb,x),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*T.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,M.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,y.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,w.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=k,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:x,endableRank:m.EndableRanks.postdb,noopIfContested:!1});(0,h.isDbManager)()&&await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,b.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),await this.db.closeDb()},o=function(){return this.ended||(0,g.ending)()||(0,c.isSuspended)()}},22526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(19851),s=i(50213),n=i(92407),a=i(55332),o=i(44955),l=i(15056),u=i(87290),c=i(98314),d=i(38835),h=i(73209),f=i(95696),m=i(17217),p=i(18454),g=i(57902),y=i(28874),w=i(2858),v=i(40958),b=i(22573),S=i(42659),P=i(94448),T=i(98348),_=i(45648),M=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,w._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function x(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return k((0,l.pathToDb)(t,"models"))}function k(e){return e.sibling("db-info.json")}async function F(e=x(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw M().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=x,t.libraryDbInfoFromDbFile=k,t.assertValidDbInfo_=F,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=k(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await F(u,t);o=new T.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>M().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new T.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return M().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,v.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw M().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return M().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},86859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(54557),s=i(50213),n=i(99331),a=i(56038),o=i(65753),l=i(66184),u=i(70417),c=i(28874),d=i(40958),h=i(22573),f=i(45599),m=i(96249),p=i(31586),g=i(51926),y=i(57038),w=i(21074),v=(0,f.defer)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,y.knex)()(this.tableName)}prep(e,t=!1){const i=(0,w.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return v().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&v().log((0,l.defaultLogLevel)(),i+"(): "+(0,w.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;v().throw(t,{method:i,...(0,w.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,a.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,g.replaceAll)((0,g.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,w.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,m.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}async batched(e){let t,i=0;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,o.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&(await e.onResults(t),i+=t.length)}while((0,d.isNotEmpty)(t)&&!(0,n.ending)()&&(null==e.maxResults||e.maxResults>i));return{resultCount:i,done:null==t||t.length<(0,o.maxBatchPluckSize)()}}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}async pluckBatched(e){let t=0;const i=(0,u.min)([e.limit??(0,o.maxBatchPluckSize)(),e.maxResults]);if(i<=0||(0,p.lte0)(e.maxResults))return{done:!1,resultCount:t};let r;for(;null==e.maxResults||e.maxResults<=0||t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},36908:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(42231),o=i(40958),l=i(76790),u=i(23838),c=i(31586),d=i(54993),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},57038:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(31832)),n=i(19851),a=i(56519),o=i(55835),l=i(68708);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},17036:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(77598),l=i(19851),u=i(50213),c=i(7282),d=i(37805),h=i(4867),f=i(51040),m=i(77740),p=i(38835),g=i(8769),y=i(57159),w=i(34102),v=i(73209),b=i(95696),S=i(43899),P=i(18454),T=i(28874),_=i(40958),M=i(42659),E=i(41400),D=i(98553),x=i(55835),k=i(34666),F=i(32639),C=i(45648),A=i(94715),I=i(27134);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,k.lt)((0,A.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,_.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,v.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:T.Settings.dbMaintenanceTimeoutMs.valueOrDefault},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=A.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,F.isFunction)(s);return o?await s.bind(A.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.info("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,w.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),(0,c.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{if((0,m.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(M.secondMs,3*M.secondMs)),await(0,x.map)(e,(e=>e(r))),await(0,h.thenOrTimeoutError)({p:this.applyMigration_(r,i),timeoutMs:5*T.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch((e=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,C.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile(),r=(0,f.splitBatchSql)(i);if((0,_.isEmpty)(r))this.logger.info("No-op migration: "+e);else{t&&this.db.pragma("foreign_keys = OFF");for(const t of r)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,I.foreignKeyCheck_)(this.db)}}finally{t&&this.db.pragma("foreign_keys = ON")}}},94715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(97352),o=i(68852),l=i(81168),u=i(85810),c=i(42022),d=i(1971),h=i(79842),f=i(89724),m=i(17415),p=i(88600),g=i(20014),y=i(42231),w=i(87001),v=i(40958),b=i(55835),S=i(31586),P=i(97790),T=i(89937),_=i(54993),M=i(7656),E=i(36908),D=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),x=new RegExp(`^(${(0,o.escapeRegExp)(T.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function k(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function F(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function C(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)}function A(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>x.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=k,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=F,t.fix_root_tags=C,t.isoToPrecisionMs=A,t.Migrations={fix_root_tags:C,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},A),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},k),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},w.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,_.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},F),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,v.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:M.rebuildTagAssetCounts,create_tag_fts:e=>{e.exec("DROP TABLE IF EXISTS tag_fts"),e.exec("CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize=\"unicode61\");")},rebuild_null_island:e=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,y.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")}}},27134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(14121),s=i(19851),n=i(50213),a=i(84777),o=i(12959),l=i(5531),u=i(91872),c=i(99315),d=i(76187),h=i(51040),f=i(38835),m=i(57159),p=i(29882),g=i(95696),y=i(89966),w=i(38156),v=i(28874),b=i(63870),S=i(5233),P=i(42659),T=i(41400),_=i(50357),M=i(98553),E=i(56409),D=i(31586),x=i(20214),k=i(51926),F=i(12168),C=i(59455),A=i(54993),I=i(94448),O=i(9508),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){L().debug("pragmaOrThrow_()",{db:N(e),db_open:e?.open,pragma:t,okResult:i});const r=(0,k.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(r,i)||L().throw(`${t} failed for ${N(e)}: ${(0,M.stringify)({result:r})}`)}function N(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}function B(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function j(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function z(e){const t=(0,C.toA)(e.pragma("foreign_key_check"));t.length>v.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:v.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function V(e){await(0,u.handleDbRetries_)("db.quickCheck",e,B),await(0,T.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",e,j),await(0,T.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",e,z)}function W(e){return(0,O.withDbSync)(e,V,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,C.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,I.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=B,t.integrityCheck_=j,t.foreignKeyCheck_=z,t.verifyDb_=V,t.verifyDbFile_=W,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=v.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,C.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,D.gt0)(n?.busy)&&i>0?(await(0,T.delay)(250),e({db:t,retries:i-1})):n};const U=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*F.MiB,await(0,d.sqliteSizeBytes)(i)),n=new w.PushProgressObserver({path:(0,A.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,A.toS)(e);U.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),await W(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,x.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,x.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},21074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(48884),s=i(68852),n=i(81168),a=i(12943),o=i(96249),l=i(98553),u=i(31586),c=i(68708),d=i(32639),h=i(54993);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},35052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(22573),s=i(23838);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},9508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(80632),s=i(28874),n=i(30301),a=i(54993);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)((()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i})));try{return t((function(){const e=o();return e.open?e:o.refresh()}))}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const n=(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i});try{return await t(n)}finally{n.close()}}},53493:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(50213),s=i(45608),n=i(69554),a=i(38790),o=i(53978),l=i(95696),u=i(48368),c=i(45200),d=i(40958),h=i(22573),f=i(38639),m=i(98553),p=i(31586),g=i(68708),y=i(5670),w=i(64526),v=i(37158),b=i(31503),S=i(57038),P=i(21074),T=i(43487),_=i(48723),M=i(94710),E=i(23523);!async function(){try{const e=new n.CLI(y.ServiceNames.list).add(b.LogArgs,a.ColorArgs,o.TimingArg);e.add({beforeParse:e=>e.option("--primary",'Only include the primary, or "best" asset file variation found for every asset. See https://phstr.com/dedupe for details.').option("--no-primary","Exclude primary asset file variation for every asset. This is mutually exclusive with the --primary option, and returns all rows that option omits.").option("--limit ","Emit at most LIMIT values.",p.toGt0).option("--query ","Apply the given query and return all matching asset file paths. Must be the last argument. Incompatible with --where.").option("-j, --json",'Emit a JSON object for every asset file with "hidden" and "shown" flags').option("--dump","Emit a JSON object that includes all column values").option("--where ","Apply a SQL WHERE clause to filter the rows returned. If this is omitted, only shown assets are returned: hidden, excluded, deleted, and incomplete assets will be omitted.").option("--orderby ","Apply a SQL ORDER BY clause to filter the rows returned.").option("-0, --print0",'Print each full native path name to standard output, followed by a null character (instead of the newline character).\nThis is suitable for properly handling filenames that include whitespace characters in shell pipelines using commands like xargs, which has a "--null" mode which expects filenames to be separated by the null character.\nThis cannot be used with --json or --dump.').option("--looks-like ","Find images that look like the photo or video specified by FILE. Use a full pathname.").option("--tasks","List the currently enqueued tasks that sync is process(ing). Implies --json. Does not support --print0.").option("--tags","List all tag paths along with their counts. Implies --json. Does not support --print0.")});const t=(await e.parse()).opts(),i=(0,d.mapNotEmpty)(t.query,(e=>e.join(" "))),D=(0,f.isTrue)(t.dump),x=D||(0,f.isTrue)(t.json),k=t.where;if(null!=i&&(0,h.notBlank)(k))throw new Error("--query cannot be used with --where");const F=new v.Service("list");await F.ready;const C=await w.Library.instanceRequired_().modelDb(),A=(0,r.mkLogger)("list");function I(e){for(const i of e)!0===t.print0?process.stdout.write(i+"\0"):console.log(i)}if((0,f.isTrue)(t.tags)){const V=_.Tag.ops().allf((e=>_.Tag.orderBy(e)));return void console.log((0,m.stringifyPretty)(V.map((e=>(0,g.pick)(e,"path","assetCount")))))}if((0,f.isTrue)(t.tasks)){const W=M.Task.ops().allf((e=>M.Task.orderBy(e)));return void(W.length>0?console.log((0,m.stringifyPretty)(W)):console.error("No pending items in any queues."))}let O=T.Asset.query().join("AssetFile","AssetFile.assetId","Asset.id").join("AssetTag","AssetTag.assetId","Asset.id");if(O=O.select({assetId:"AssetFile.assetId",assetFileId:"AssetFile.id",shownFile:"AssetFile.shown",mountpoint:"AssetFile.mountpoint",uri:"AssetFile.uri",hidden:"Asset.hidden",rating:"Asset.rating"}).distinct(),(0,h.notBlank)(t.looksLike)){const U=l.PosixFile.for(t.looksLike);A.info("Calculating image hash for "+U);const q=await U.sha(),H=await(0,u.imageHash)(U);if(null==H)throw new Error("Failed to generate image hash for "+U);A.info("Looking for assets with matching meanHash or SHA",{meanHash:H.meanHash,SHA:q}),O=O.where((e=>e.where("AssetFile.meanHash",H.meanHash).orWhere("AssetFile.sha",q)))}D&&(O=O.select((0,S.knex)().raw("AssetFile.*"),(0,S.knex)().raw("Asset.*"))),O=(0,h.notBlank)(k)?O.andWhere((0,S.knex)().raw(k)):T.Asset.shownUnhidden(O),!0===t.primary&&(O=O.andWhere("AssetFile.shown",1)),!1===t.primary&&(O=O.andWhere("AssetFile.shown",0)),(0,p.gt0)(t.limit)&&(O=O.limit(t.limit));const L=(0,h.toNotBlank)(t.order)??"uri",R=null!=i?(0,E.queryStringToSql_)(i,O).orderByRaw(L):O,N=(0,P.toSqlQuery)(R);A.info("Running SQL query...",{sq:N});const B=Date.now(),j=C.prepare(N.sql).iterate(N.bindings);A.info("query took "+(Date.now()-B)+"ms"),x&&console.log("[");let z=!0;for(const G of j){A.throwIfAborted_();const $=await(0,c.uri2nativePath)(G.uri,G.mountpoint);x?(z||process.stdout.write(","),process.stdout.write((0,m.stringify)({path:$,...(0,g.omit)(G,"id")}))):null==$?console.error("Failed to decode URI to native path: ",(0,m.stringify)(G)):I([$??G.uri]),z=!1}x&&console.log("]")}catch(J){await(0,s.exit)({error:J})}finally{await(0,s.exit)({status:0})}}()},43487:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(48884),c=i(19851),d=i(50213),h=i(88158),f=i(45393),m=i(56519),p=i(89724),g=i(38835),y=i(74128),w=i(79847),v=i(28874),b=i(47783),S=i(38010),P=i(40958),T=i(76790),_=i(75761),M=i(38639),E=i(11371),D=i(98553),x=i(55835),k=i(31586),F=i(20214),C=i(59455),A=i(64526),I=i(4407),O=i(54017),L=i(48722),R=i(37094),N=i(45295),B=i(39604),j=i(48723),z=i(41507),V=i(72761),W={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class U extends V.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,b.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,M.isTrue)(t.shown)})}const t=R.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(W):e.andWhere(W)}static findUnhiddenById(e){return(0,k.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return A.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{unlinkAssetFiles:i});const l=n.getAssetFiles({refresh:!0});if(t){(0,B.upsertToShaBlockslist)(...l.map((e=>e.sha)));for(const e of l)(0,y.syncReport)().onProgress({from:"Asset.remove",path:await e.getNativePath()??e.uri,state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}N.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),R.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&j.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,w.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(N.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,x.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,k.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,k.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,L.toAssetId)(this)}renderCaption(e){return(0,x.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:j.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,P.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return j.Tag.ops().all(j.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??N.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:j.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:j.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,P.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,k.gt0)(e)&&!t.includes(e)))),r=(0,P.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,k.gt0)(e)&&t.includes(e))));if((0,P.isEmpty)(i)&&(0,P.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&j.Tag.deltaAssetCountAndAncestors(t,-1),(0,P.isEmpty)(i)||N.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,P.isEmpty)(r)||N.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,P.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&j.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,z.coalesceStreams)((0,P.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,T.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,M.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,k.gt0)(this.id)&&(0,k.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,D.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,M.isTrue)(e.shown)))??this.getAssetFiles({refresh:!0})?.find((e=>(0,M.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,F.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,_.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,E.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,_.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,_.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,F.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,x.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,k.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,M.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=U,s=U,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("Asset.version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},U.$tableName="Asset",U.$uniqueColumnName="id",U.$booleanFields=["shown","hidden"]},54017:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(76760),o=i(19851),l=i(88158),u=i(45393),c=i(68852),d=i(81168),h=i(13991),f=i(54296),m=i(56519),p=i(76490),g=i(89724),y=i(98314),w=i(38835),v=i(8769),b=i(29882),S=i(95696),P=i(62105),T=i(74128),_=i(35721),M=i(69589),E=i(28874),D=i(28544),x=i(16170),k=i(45200),F=i(34238),C=i(87001),A=i(42233),I=i(21404),O=i(40958),L=i(17586),R=i(22573),N=i(38639),B=i(42659),j=i(33374),z=i(50357),V=i(75240),W=i(11371),U=i(55835),q=i(31586),H=i(68708),G=i(34666),$=i(89937),J=i(75020),K=i(64526),Z=i(41844),Y=i(43487),X=i(48723),Q=i(94710),ee=i(72761);class te extends ee.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>F.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=Y.Asset.shownUnhidden(e.q).join("AssetFile","AssetFile.assetId","Asset.id").where("AssetFile.version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("AssetFile.updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("AssetFile.mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("AssetFile.uri",i+"%");return t})).orderBy("AssetFile.id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,A.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,A.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("AssetFile.id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,q.gt0)(e)?te.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,R.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(te.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=te.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=te.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:te.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,H.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith($.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,H.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,U.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,q.closeTo)(i.mtime,this.mtime,2*B.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return E.Settings.forceSync.valueOrDefault?E.Settings.forceSync.key+"=true":this.version!==u.AssetFileVersion?"AssetFileVersion: "+this.version+" != "+u.AssetFileVersion:this.whyNotMatchesFile(e)}async inSyncWithFile(e){const t=await this.whyNotInSyncWithFile(e);return this.logger().tap({msg:"inSyncWithFile()",result:null==t,meta:{whyNotInSync:t}})}async fileFields_(e){const t=e??await this.posixFile_();return null==t?void 0:await(0,h.assetFileStatFields_)(t)}isInLibrary(){return this.uri.startsWith($.PS_LIBRARY_PROTOCOL)}async isNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){const t=await this.whyNotNoop(e);return this.logger().tap({msg:"isNoop()",result:null==t,meta:{whyNotNoop:t}})}async whyNotNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){if(!0===e.forceSync)return"forceSync is true";if(!(0,q.gt0)(this.id))return"missing .id";if(!(0,q.gt0)(this.assetId))return"missing .assetId";{const e=await this.whyNotInSyncWithFile();if(null!=e)return e}if(await(0,Z.mayCopyAssetsToLibrary)()){const e=K.Library.instanceRequired_().assetFileRepository(),t=e.whyNotCopyFile(await this.posixFile_());if((0,R.blank)(t)&&null==await e.existingLibraryAssetFile(this))return"need to copy into library"}this.syncState=T.AssetFileSyncStates.noop}isVersionUpToDate(){return(0,G.gte)(this.version,u.AssetFileVersion)}async siblingCount(){return te.dbl.pluckFirstf((e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=(0,M.forceContextOrSetting)()){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,q.gt0)(this.id)&&!t.forceSync)return void(null==this.syncState&&(this.upsert(),this.syncState??(this.syncState=T.AssetFileSyncStates.noop)));const i=await this.isFileDeleted();if(!0===i)return this.syncState=T.AssetFileSyncStates.deleted,this.delete(),!0!==t.skipAssetRepair&&Q.Task.addOne("repairAsset",{assetId:this.assetId}),this;if(!1===i){const i=await this.updateFromFile_(e,t);return this.syncState??(this.syncState=null==i?T.AssetFileSyncStates.noop:T.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=T.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,H.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e,t=(0,M.forceContextOrSetting)()){const i=Date.now(),r=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&!0!==t.forceSync&&await this.matchesFile(e))return void r.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=T.AssetFileSyncStates.deleted,void r.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,R.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,H.assignAllFields)(this,(0,H.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=T.SyncFileStates.synced,r.elapsed("finished",Date.now()-i,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,H.assignFields)(this,(0,H.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...te.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,q.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,k.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,R.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,R.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,R.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+w.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),D.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,j.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,N.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===W.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,v.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=F.URI.parse(this.uri),t=(0,U.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=F.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,L.at)((0,L.at)(e,-1)?.tagPath,-1)}(0,z.eql)(e[0]?.tagPath,[J.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===$.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,L.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===J.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===$.PS_LOCAL_FILE_SCHEME){const t=F.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,H.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,N.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:ie(this.createdAt),updatedAtLocale:ie(this.updatedAt)})))}get isVideo(){return(0,x.isVideoMimeType)(this.mimetype)}}function ie(e){return(0,U.map)(e,(e=>(0,V.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=te,r=new WeakSet,s=function(){if((0,R.blank)(this.uri))return"blank uri";if((0,R.blank)(this.sha))return"blank sha";if(!(0,q.gt0)(this.width))return"missing width";if(!(0,q.gt0)(this.height))return"missing height";if(!(0,q.gt0)(this.capturedAtLocal))return"missing capturedAtLocal";if(!(0,q.gte0)(this.capturedAtPrecisionMs))return"missing capturedAtPrecisionMs";if(E.Settings.useImageHashes.valueOrDefault){const e=[];for(const t of["dctHash","diffHash","meanHash"])(0,R.blank)(this[t])&&e.push(t);if(1===e.length)return"missing image hash: "+e[0];if(e.length>1)return"missing image hashes: "+e.join(", ")}return this.isVersionUpToDate()?void 0:"outdated version"},te.$tableName="AssetFile",te.$uniqueColumnName="uri",te.$booleanFields=["shown"],te.$transientFields=["nativePath","syncState"]},48722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(76596),s=i(31586);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},37094:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},45295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},61204:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(19851),s=i(50213),n=i(97352),a=i(75020),o=i(4407),l=i(48723),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},95700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(19851),s=i(56038),n=i(28874),a=i(42659),o=i(41400),l=i(69032),u=i(61204),c=i(49796);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h());try{await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())}catch{}};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},55046:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(57975),n=i(50213),a=i(7282),o=i(65211),l=i(40958),u=i(38639),c=i(45599),d=i(31586),h=i(68708),f=i(34666),m=i(54993),p=i(57038),g=i(94448),y=i(33572),w=i(63872);class v{constructor(){this.$instanceId=(0,a.isTest)()?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new w.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if((0,a.isProd)())throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}update(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("update()",{self:this.toJSON()}),this.class().ops().updateOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=v,r=v,v.$schema="models",v.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),v.db=g.modelDb,v.$pkColumnNames=["id"]},94448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},33572:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(50213),s=i(40958),n=i(22573),a=i(38639),o=i(97790),l=i(51926),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},63872:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(48884),m=i(19851),p=i(50213),g=i(81168),y=i(48299),w=i(12943),v=i(38835),b=i(34102),S=i(28874),P=i(40958),T=i(76790),_=i(22573),M=i(50357),E=i(96249),D=i(98553),x=i(55835),k=i(31586),F=i(68708),C=i(59455),A=i(86859),I=i(33572);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,I.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new A.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,k.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,x.mapOr)(this.db(),(e=>e.isOpen),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,w.toDbValued)(t);return(0,F.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,F.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,C.toA)(e).filter(k.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,T.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,k.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,C.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+v.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+v.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,k.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,x.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+v.NonRetriableErrorFlag+v.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);if(null==s)return;return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){const t=[],i=this.allf((i=>{for(const r of e){const e=this.model.hasId(r)?this.model.pickId(r):this.$pickModelUcn(r);null!=e?(t.push([r,e]),i=i.orWhere(e)):h(this,s,"f").warn("reload(): given insufficient partial model",{fragment:r})}return i})),n=[];for(const[e,a]of t){const t=i.find((e=>(0,M.eqlSubset)(a,e)));if(null==t)h(this,s,"f").warn("reload(): failed to find result in db",{prior:e,dbArr:i});else{const i=h(this,r,"m",u).call(this,e);h(this,r,"m",l).call(this,i,t),i!==e&&h(this,r,"m",l).call(this,i,t),n.push(t)}}return n}upsert(e){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const t=this.columnNames(),i=[];for(const s of(0,f.batches)((0,C.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=new Map,n=new Set,a=(0,P.compact)(s.map((e=>this.fromJSON(e))));for(const t of a){const i=(0,D.stringify)(this.$pickModelUcn(t));e.set(i,t),this.model.hasId(t)||n.add(i),t.$beforeUpsert()}h(this,r,"m",c).call(this,a.map((e=>e.$toDbJSON(t))));const o=this.reload(a),l=new Map(o.map((e=>[(0,D.stringify)(this.$pickModelUcn(e)),e])));for(const e of a){const t=(0,D.stringify)(this.$pickModelUcn(e)),r=l.get(t)??e;n.has(t)&&r.$afterInsert(),r.$afterUpsert(),i.push(r)}}return i}delete(e){const t=(0,C.toA)(e).filter(k.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,F.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,F.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},49796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.toPct=void 0;const r=i(48161),s=i(1708),n=i(48884),a=i(50213),o=i(28874),l=i(40958),u=i(42659),c=i(45599),d=i(98553),h=i(55835),f=i(31586),m=i(68708),p=i(67478),g=i(51926),y=i(59455),w=i(54993),v=i(76386),b=i(33572),S=i(55009),P=i(72761),T=(0,c.defer)((()=>(0,a.mkLogger)("model.Progress")));function _(e){return null==e||!(0,f.isNumber)(e)||e<0||e>100?void 0:(0,f.sigFigs)(e,3)}t.toPct=_;const M=(0,g.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function E(){const e=o.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*u.dayMs}t.defaultMinCreatedAt=E;class D extends P.TimestampedModel{static vacuum(e=o.Settings.progressRetentionDays.valueOrDefault*u.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t)));for(const e of(0,n.batches)(i,o.Settings.dbBatchSelectSize.valueOrDefault))S.ProgressMeta.dbl.runf((t=>t.whereIn("progressId",e).delete())),D.dbl.runf((t=>t.whereIn("id",e).delete()))}static countCompletedDirectorySyncs(){return this.dbl.pluckFirstf((e=>e.where({state:"done"}).whereNotNull("completedAt").where("uri","like","ps%")))}static times(){return T().tap({msg:"times()",result:this.dbl.all({sql:M})})}static insertNew(e){const t=(0,h.map)(e.dek,d.stringify);return this.ops().insertOne({...(0,m.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&this.assignFromPojo(e),super.upsert()}$beforeUpsert(){super.$beforeUpsert(),null==this.id&&(this.pid??(this.pid=s.pid),this.hostname??(this.hostname=(0,r.hostname)())),"done"===this.state&&(this.completedAt??(this.completedAt=Date.now())),this.completePct=_(this.completePct),this.incompletePct=_(this.incompletePct),this.scanningPct=_(this.scanningPct)}$afterUpsert(){super.$afterUpsert(),(0,v.tellWebProgressUpdated)()}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,l.compactBlanks)((0,p.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,d.stringify)((0,l.compactBlanks)((0,y.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,m.omit)(e,"volume","uri"))}getMeta(){return S.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncomplete(e=E()){return this.logger().tap({msg:"priorIncompleteProgress()",result:D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc")))})}getLastCompletedAt(e=E()){return D.dbl.pluckFirstf((t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e)))}getLastIncompleteStartAt(){return D.dbl.pluckFirstf((e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0)))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),S.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,l.diff)(t.map((e=>e.name)),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),S.ProgressMeta.ops().upsert((0,m.entries)(e).map((([e,t])=>({progressId:this.id,name:e,value:(0,w.toS)(t)})))),(0,l.isNotEmpty)(i)&&S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).whereIn("name",i).delete()))}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),S.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,m.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},55009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},39604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(19851),s=i(50213),n=i(95696),a=i(40958),o=i(22573),l=i(86859),u=i(94448),c=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),d=(0,r.lazy)((()=>new l.DbRequest(u.modelDb,"ShaBlocklist")));function h(e){return null!=(0,u.modelDb)()&&!(0,o.blank)(e)&&c().tap({msg:"isShaBlockslisted",result:null!=d().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}function f(...e){if(null==u.modelDb.prior())return;const t=(0,a.uniq)(e).map((e=>({sha:e})));return(0,a.isEmpty)(t)?void 0:d().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,u.modelDb)())return null;const t=h(await n.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=h,t.upsertFileToShaBlockslist=async function(e){if(null==(0,u.modelDb)())return;const t=await n.PosixFile.for(e).sha();return null==t?void 0:f(t)},t.upsertToShaBlockslist=f},48723:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(56038),o=i(34102),l=i(19851),u=i(50213),c=i(36372),d=i(97352),h=i(28874),f=i(81168),m=i(42231),p=i(75020),g=i(40958),y=i(22573),w=i(42659),v=i(41400),b=i(50357),S=i(55835),P=i(31586),T=i(34666),_=i(20214),M=i(51926),E=i(59455),D=i(12168),x=i(6186),k=i(57038),F=i(21074),C=i(7656),A=i(43487),I=i(48722),O=i(45295),L=i(98784),R=i(41507),N=i(72761),B=4*w.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,v.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,M.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:A.Asset.dbl.pluckFirst(A.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset(),this.ops().clearDbCache()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{r.clear();for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.update({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,k.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,M.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,F.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:C.RecursiveAssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),this.ops().upsertOne(i)}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,k.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return A.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();return(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)})),r.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,M.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(A.Asset.dbl.all(t).map(I.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return A.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,M.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:C.RecursiveAssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?A.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(A.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(I.toAssetId))));for(const t of r)t.assetIdA.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(this.id??0),"Asset.id",i)).limit(t))).map(I.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!0,z.cmp=(e,t)=>(0,T.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=A.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(x.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e}),B);const V=(0,l.lazy)((()=>A.Asset.dbl.pluckFirstf((e=>e.count()))),w.minuteMs)},98784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(38156),s=i(3127),n=i(40958),a=i(41400),o=i(94715),l=i(55046),u=i(48723);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=new r.PushProgressObserver({op:"Rebuilding tag search index"},u.Tag.dbl.pluckFirstf((e=>e.count("*")))),t=this.dbl.db();o.Migrations.create_tag_fts(t.db),await u.Tag.ops().batched({qb:e=>e,onResults:t=>(this.$logger().throwIfAborted_(),this.insertFts(t),e.incrProgress(t.length),(0,a.delay)(1))}),e.completed()}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},41507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},94710:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Task=t.StaleTaskError=t.InvalidTaskError=t.TaskNames=t.Tasks=t.testTask=void 0;const c=i(78474),d=i(22454),h=i(23560),f=i(12089),m=i(76740),p=i(22911),g=i(99331),y=i(31562),w=i(38835),v=i(70025),b=i(8769),S=i(74128),P=i(28874),T=i(37692),_=i(40958),M=i(22573),E=i(42659),D=i(45599),x=i(98553),k=i(49769),F=i(68708),C=i(50989),A=i(59455),I=i(58723),O=i(34274),L=i(90901),R=i(61989),N=i(93755),B=i(69032),j=i(55046);t.testTask=(0,f.shim1)({name:"testTask",impl:async e=>{}}),t.Tasks={applyDeleted:I.applyDeleted,applyExcluded:I.applyExcluded,runTagMaintenance:B.runTagMaintenance,updateAssetFile:N.updateAssetFile_,repairAsset:async function(e){e.forceSync=!0,e.skipPreviews=!0,e.skipAssetTagging=!0;const t=await(0,R.updateAsset_)(e);return(0,_.isNotEmpty)(t?.assetIdsToUpdate)&&q.add(t?.assetIdsToUpdate.map((t=>({fn:"repairAsset",args:{...e,assetId:t},priority:W.repairAsset+1})))),null!=t&&!0!==t.deleted&&(0,M.blank)((0,A.toA)(t.rejected).join(""))&&(0,M.blank)(t.error)&&q.addOne("assetPostUpsertTasks",(0,F.omit)(e,"skipPreviews","skipAssetTagging")),t},assetPostUpsertTasks:L.assetPostUpsertTasks,syncFile:O.importFileToResult_,testTask:t.testTask},t.TaskNames=(0,C.strEnum)(...(0,F.keys)(t.Tasks));class z extends Error{}t.InvalidTaskError=z;class V extends Error{}t.StaleTaskError=V;const W={applyDeleted:16,applyExcluded:16,runTagMaintenance:14,updateAssetFile:13,repairAsset:12,assetPostUpsertTasks:10,syncFile:0,testTask:-1},U=["repairAsset"];class q extends j.Model{constructor(){super(...arguments),r.add(this),o.set(this,(0,D.defer)((()=>new m.Abortable)))}static countTaskNames(){const e={};for(const t of s.dbl.allf((e=>e.select("fn").count().groupBy("fn"))))e[t.fn]=t["count(*)"];return e}static orderBy(e){return e.orderBy([{column:"priority",order:"desc"},{column:"retries",order:"desc"},{column:"id",order:"asc"}])}static count(){return s.dbl.pluckFirstf((e=>e.count("id")))}static freeSlots(){return P.Settings.taskListCap.valueOrDefault-s.count()}static countByFn(e){return s.dbl.pluckFirstf((t=>t.where({fn:e}).count("id")))}static nextByFn(e,t=(e=>e)){return s.ops().allf((i=>s.orderBy(t(i.where({fn:e})))))}set args(e){this.argsJSON=(0,x.stringify)(e)}get args(){const e=(0,x.parseJSON)(this.argsJSON);return(0,F.notEmptyObj)(e)&&(e.halt=u(this,o,"f").call(this)),e}get isSerial(){return U.includes(this.fn)}toString(){return`Task#${this.fn}(${this.argsJSON})`}static addOne(e,t){return s.add([{fn:e,args:t}])[0]}static add(e,t=!1){if((0,_.isEmpty)(e))return[];const i=s.ops().upsert(e.map((e=>({fn:e.fn,argsJSON:(0,x.stringify)(e.args)})),t));return s.ee.emit("added",i),(0,h.isTaskListManager)()||(0,T.addStateEvent)("checkTasks"),i}$beforeUpsert(){this.priority??(this.priority=W[this.fn]),this.retries??(this.retries=P.Settings.maxRetries.valueOrDefault)}donePromise(){return(0,h.isTaskListManager)()?(0,k.getOrSet)(u(s,s,"f",n),this.id,(()=>new p.Deferred(this.toString(),{payload:this}))):(0,y.untilTrue)((()=>null==s.ops().findById(this.id)),{intervalMs:E.secondMs})}abort(e){this.logger().warn("aborting task",{reason:e,task:this}),u(this,o,"f").call(this).abort(e),this.delete(),(0,M.blank)(this.args.path)||(0,S.syncReport)().onProgress({path:this.args.path,from:this.fn,state:S.SyncFileStates.failed,details:e})}async _run(){if(this.retries<0)throw this.logger().warn(".run(): too many retries"+w.InternalErrorFlag,{job:this}),this.delete(),new z;if(!u(this,r,"m",l).call(this))throw this.logger().warn(".run(): someone already started this task",{job:this}),new V;try{const e=Date.now(),i=await t.Tasks[this.fn](this.args);return this.logger().throwIfAborted_(u(this,o,"f").prior()),s.taskResolvedCounts.incr(this.fn),s.ee.emit("resolved",this,i,Date.now()-e),this.delete(),u(s,s,"f",n).get(this.id)?.resolve(i),i}catch(e){if((0,g.ending)())throw this.logger().info("task failed, but we're ending. We'll leave it for next time.",{task:this}),e;throw s.taskRejectedCounts.incr(this.fn),(0,v.isRedoableError)(e)?(this.retries++,this.priority--,this.upsert()):!0===(0,v.isRetriableError)(e)&&this.retries>=0?this.logger().warn("run failed, but we can retry it later",{task:this,error:e}):(s.ee.emit("rejected",this,e),this.delete(),u(s,s,"f",n).get(this.id)?.reject(e),(0,b.onError)(this.toString()+" failed",e)),e}finally{u(s,s,"m",a).call(s)}}}t.Task=q,s=q,o=new WeakMap,r=new WeakSet,a=function(){for(const[e,t]of u(this,s,"f",n).entries())t.isSettled&&u(this,s,"f",n).delete(e)},l=function(){const e=this.retries;if(1===s.dbl.runf((t=>t.where({id:this.id,retries:e}).update({retries:e-1}))).changes)return--this.retries,!0;{const e=this.toJSON(),t=this.reload();return this.logger().warn(".#decrRetries(): someone already started this task",{before:e,reloaded:t}),!1}},q.$tableName="Task",q.$uniqueColumnName="fn,argsJSON",q.$useCache=!1,q.taskResolvedCounts=new d.CountingSet,q.taskRejectedCounts=new d.CountingSet,q.ee=new c.EventEmitter,n={value:new Map}},72761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),this.createdAt??(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},58723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyExcluded=t.applyDeleted=void 0;const r=i(50213),s=i(43487),n=(0,r.mkLogger)("ops.ApplyRemovable");async function a(e,t,i){const r=e?"Deleting":"Excluding",a=e?"deletedAt":"excludedAt";await s.Asset.dbl.batched({qb:e=>e.select("id").where("shown",0).andWhere(a,"<=",t),onResults:async t=>{for(const a of t){n.throwIfAborted_(i);try{await s.Asset.remove({assetId:a,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){n.error(r+" failed",{assetId:a,error:e})}}}})}t.applyDeleted=function(e){return a(!0,e.createdAt,e.halt)},t.applyExcluded=function(e){return a(!1,e.createdAt,e.halt)}},76386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)((()=>(0,s.mkLogger)("progress.Progress")));t.ProgressRateMs=(0,r.lazy)((()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:1.5))),t.tellWebProgressUpdated=(0,r.lazy)((async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch((e=>h().warn(".tellWebProgressUpdated: failed",{error:e})))}),(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},44694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryTermToFuzzyDate=void 0;const r=i(98725),s=(0,i(19851).lazy)((()=>new r.FuzzyDateParser({fuzzyDateParsing:!0,fuzzyYearParsing:!0})));t.queryTermToFuzzyDate=function(e){return s().parse(e)}},43786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToString=t.NormieQuerySymbols=t.SetQuerySymbols=t.isTrueTerm=t.flatTerms=t.findTerm=t.hasNsTerm=t.isQuery=t.isClause=t.isAndClause=t.isOrClause=t.isTerm=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(51926),o=i(54993);function l(e){return"object"==typeof e&&(0,s.notBlank)(e.term)&&(null==e.not||"boolean"==typeof e.not&&(null==e.ns||(0,a.isString)(e.ns)))}function u(e){return"object"==typeof e&&Array.isArray(e.queries)}function c(e){return"or"===e?.type&&u(e)}function d(e){return"and"===e?.type&&u(e)}function h(e){return d(e)||c(e)}function f(e,t){if(l(e))return t(e)?e:void 0;for(const i of e.queries){const e=f(i,t);if(null!=e)return e}}t.isTerm=l,t.isOrClause=c,t.isAndClause=d,t.isClause=h,t.isQuery=function(e){return l(e)||h(e)},t.hasNsTerm=function(e,t){return null!=f(e,(e=>e.ns===t))},t.findTerm=f,t.flatTerms=function e(t){return l(t)?[t]:(0,r.flatMap)(t.queries,e)},t.isTrueTerm=function(e){return(0,n.isTrue)(e?.not)?(0,n.isFalse)(e?.term):(0,n.isTrue)(e?.term)},t.SetQuerySymbols={not:"¬",and:"∧",or:"∨"},t.NormieQuerySymbols={not:"-",and:"AND",or:"OR"},t.queryToString=function e(i,r=t.SetQuerySymbols){if(null==i)return"";if(l(i)){let e=i.term;return null==i.term.match(/^[a-z]+$/i)&&(e='"'+e.replace(/"/g,'\\"')+'"'),`${(0,n.isTrue)(i.not)?r.not:""}${null==i.ns?"":i.ns+":"+(0,o.toS)(i.op)}${e}`}return"("+i.queries.map((t=>e(t,r))).join(` ${"or"===i.type?r.or:r.and} `)+")"}},7573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeTerm=t.isAssetTerm=t.AssetTermNs=t.AssetTermDateNs=t.AssetTermBoolNs=t.normalizeQuery=void 0;const r=i(48884),s=i(75020),n=i(40958),a=i(76790),o=i(22573),l=i(38639),u=i(50989),c=i(54993),d=i(44694),h=i(43786);function f(e){return(0,a.sortBy)((0,n.uniqBy)(e,h.queryToString),(e=>[(0,h.isTerm)(e)?0:(0,h.isOrClause)(e)?1:2,(0,h.queryToString)(e).replace(/[¬(]+/g,"")]))}t.normalizeQuery=function e(t){if((0,h.isTerm)(t))return g(t);const i=t.queries.map(e);if(0===i.length)throw new Error("empty query");if(1===i.length)return i[0];const[s,n]=(0,r.partition)(i,h.isTerm),[a,o]=(0,r.partition)(n,(e=>e.type===t.type));for(const e of a)s.push(...e.queries);const l={type:t.type,queries:f([...s,...o])};return l.queries.every((e=>(0,h.isTerm)(e)&&e.not))?e({type:"and"===t.type?"or":"and",queries:f(l.queries.map((e=>({...e,not:!1}))))}):l},t.AssetTermBoolNs=(0,u.strEnum)("deleted","excluded","liked","hidden"),t.AssetTermDateNs=(0,u.strEnum)("date","updated");const m={delete:t.AssetTermBoolNs.deleted,trash:t.AssetTermBoolNs.deleted,trashed:t.AssetTermBoolNs.deleted,exclude:t.AssetTermBoolNs.excluded,remove:t.AssetTermBoolNs.excluded,removed:t.AssetTermBoolNs.excluded,like:t.AssetTermBoolNs.liked,fav:t.AssetTermBoolNs.liked,fave:t.AssetTermBoolNs.liked,faved:t.AssetTermBoolNs.liked,favorite:t.AssetTermBoolNs.liked,favourite:t.AssetTermBoolNs.liked,hide:t.AssetTermBoolNs.hidden,archive:t.AssetTermBoolNs.hidden,archived:t.AssetTermBoolNs.hidden},p={kw:s.TagRoots.Keywords,keyword:s.TagRoots.Keywords,keywords:s.TagRoots.Keywords,dir:s.TagRoots.fs,directory:s.TagRoots.fs,folder:s.TagRoots.fs};function g(e){if((0,o.blank)(e.ns)&&null!=e.term.match(/^\d{4}[-\d]*$/)&&null!=(0,d.queryTermToFuzzyDate)(e.term))return{ns:"date",term:e.term};if("when"===(0,c.toS)(e.ns).toLowerCase())return g({...e,ns:t.AssetTermDateNs.date,term:e.term.replace(/\//g,"-")});let i=(0,o.notBlankOr)(e.ns,e.term).toLowerCase();if(i=m[i]??i,t.AssetTermBoolNs.includes(i)){let t=!(0,l.isFalse)(e.term);return!0===e.not&&(t=!t),{ns:i,term:(0,c.toS)(t)}}if(t.AssetTermNs.includes(i))return{...e,ns:i};if("before"===i||"after"===i){if(null!=e.op)throw new Error(i+": doesn't support operators");const r="after"===i&&!0!==e.not||!0===e.not;return{ns:t.AssetTermDateNs.date,op:r?">":"<",term:e.term}}return i!==e.term.toLowerCase()?{not:e.not,op:e.op,ns:p[i]??i,term:e.term}:e}t.AssetTermNs=(0,u.strEnum)(...t.AssetTermDateNs.values,...t.AssetTermBoolNs.values),t.isAssetTerm=function(e){return(0,h.isTerm)(e)&&t.AssetTermNs.includes(g(e).ns)},t.normalizeTerm=g},33693:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseQuery_=void 0;const s=r(i(31704)),n=i(19851),a=i(50213),o=i(7282),l=i(38835),u=i(31586),c=r(i(70471)),d=(0,n.lazy)((()=>(0,a.mkLogger)("query.QueryParser")));t.parseQuery_=function(e){try{const t=new s.default.Parser(s.default.Grammar.fromCompiled(c.default)).feed(e.trim()).finish();if(t.length>1&&!(0,o.isProd)()&&d().throw("parseQuery(): ambiguous grammar!",{input:e}),null==t[0])throw new Error("invalid query");return d().debug("parseQuery()",{input:e,result:t[0]}),t[0]}catch(t){const i=t.token?.col,r=`Query syntax error${(0,u.gt0)(i)?" around column "+i:""}: "${e}"`;throw d().warn("parseQuery(): bad query",{msg:r,err:t}),new Error(r+l.NonRetriableErrorFlag+l.DoNotSendErrorFlag)}}},23523:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToSql=t.queryStringToSql_=t.defaultAssetQuery=void 0;const r=i(19851),s=i(50213),n=i(66649),a=i(89724),o=i(70417),l=i(28874),u=i(42231),c=i(22573),d=i(38639),h=i(98553),f=i(54993),m=i(57038),p=i(43487),g=i(44694),y=i(43786),w=i(7573),v=i(33693),b=(0,r.lazy)((()=>(0,s.mkLogger)("query.QueryToSql")));function S(e,t,i){if((0,y.isTerm)(t))return function(e,t,i){return(0,w.isAssetTerm)(t)?function(e,t){switch(t.ns){case w.AssetTermNs.date:case w.AssetTermNs.updated:return function(e,t){const i=t.op??"=",r="date"===t.ns?"Asset.capturedAtLocal":"updated"===t.ns?"Asset.updatedAt":void 0;if(null==r)throw new Error("internal error: unexpected namespace for "+(0,h.stringify)(t));const s="Asset.updatedAt"===r?n.datedToMillis:a.maybeDatedToLocal,l=(0,g.queryTermToFuzzyDate)(t.term),u=s(l),c=l?.following()?.toDateTime(),d=s(c?.minus({second:1})),f=(0,o.max)([u,d]);if(null==l||null==u||null==f)throw new Error((0,y.queryToString)(t,y.NormieQuerySymbols)+" can't be parsed as a date");if("="===i)return e.whereBetween(r,[u,f]);if("<"===i)return e.where(r,i,u);if("<="===i)return e.where(r,i,f);if(">="===i)return e.where(r,i,u);if(">"===i)return e.where(r,i,f);throw new Error("internal error: unexpected op for "+(0,h.stringify)(t))}(e,t);case w.AssetTermNs.hidden:return e.where("Asset.hidden",T(t));case w.AssetTermNs.excluded:return M({qb:e,column:"Asset.excludedAt",whereNull:0===T(t)});case w.AssetTermNs.deleted:return M({qb:e,column:"Asset.deletedAt",whereNull:0===T(t)});case w.AssetTermNs.liked:return e.where("Asset.rating",P(t)?">=":"<",l.Settings.likeRating.valueOrDefault);default:throw new Error("not asset term:"+(0,y.queryToString)(t))}}(e,t):function(e,t,i){const r=t.term.startsWith("/"),s="="===t.op,n=function(e,t){if(null==t||"fs"!==e.ns)return e.term;const i=e.term.split("/"),r=i.findIndex(c.notBlank);if(-1===r)return e.term;const s=i[r];return i[r]=t.get(s)??s,i.join("/")}(t,i);if(r||s)return e.whereIn("Asset.id",(0,m.knex)()("AssetTag").join("Tag","Tag.id","AssetTag.tagId").select("assetId").whereLike("Tag._path",t.ns+(r?"":"%")+n.replace(/\//g,u.TagSep).replace(/\*/g,"%")+u.TagSep+(s?"":"%")));let a=(0,m.knex)()("AssetTag").join("tag_fts","tag_fts.rowid","AssetTag.tagId").select("assetId");const o="path:"+_(n.replace(/\//g," + "));if((0,c.blank)(t.ns)){if((0,d.isTrue)(t.not))throw new Error("Cannot negate without a namespace ("+(0,y.queryToString)(t)+")");a=a.where("tag_fts","MATCH",o)}else a=a.where("tag_fts","MATCH","(root:"+_(t.ns)+((0,d.isTrue)(t.not)?" NOT ":" AND ")+o+")");return e.whereIn("Asset.id",a)}(e,t,i)}(e,t,i);for(const r of t.queries)e=(0,y.isAndClause)(t)?e.andWhere((e=>S(e,r,i))):e.orWhere((e=>S(e,r,i)));return e}function P(e){const t=(0,d.isTrue)(e.term);return!0===e.not?!t:t}function T(e){return P(e)?1:0}function _(e){return e.includes("*")?e.split("*").map(_).join(" * "):`"${(0,f.toS)(e).replace(/"/g,'""')}"`}function M({qb:e,column:t,whereNull:i}){return i?e.whereNull(t):e.whereNotNull(t)}function E(){return p.Asset.ops().query().where("Asset.shown",1).join("AssetTag","AssetTag.assetId","Asset.id")}function D(e,t=E(),i){return e=(0,w.normalizeQuery)(e),(0,y.hasNsTerm)(e,w.AssetTermBoolNs.hidden)||(0,y.hasNsTerm)(e,w.AssetTermBoolNs.excluded)||(0,y.hasNsTerm)(e,w.AssetTermBoolNs.deleted)||(t=t.andWhere({"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null})),t.andWhere((t=>S(t,e,i)))}t.defaultAssetQuery=E,t.queryStringToSql_=function(e,t=E()){const i=(0,v.parseQuery_)(e);return null==i?(b().warn("assetQuery("+e+"): parsed to null"),t):D(i,t)},t.queryToSql=D},70471:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};function s(e){return e[0]}Object.defineProperty(t,"__esModule",{value:!0}),t.parseTerm=void 0;const n=r(i(80265)),a=i(40958),o=i(54993);function l(e){if(null==e[0]&&["and","or"].includes((0,o.toS)(e[1]).toLowerCase()))throw new Error("Unmatched "+e[1]);return{not:null!=e[0]?.[0]?.value,ns:e[0]?.[1]?.value,op:e[0]?.[3]?.value,term:e[1]}}function u(e){return e[0]?.value}t.parseTerm=l;const c=n.default.compile({qstr:[{match:/"(?:[^\\"]|\\.)*?"/,value:e=>e.slice(1,-1).replace(/\\"/g,'"')},{match:/'(?:[^\\']|\\.)*?'/,value:e=>e.slice(1,-1).replace(/\\'/g,"'")}],lp:"(",rp:")",not:/[-¬]/,col:":",op:/<=?|>=?|=/,or:/ +(?:or|OR|Or|∨|\|{1,2}) +/,and:/(?:and|AND|And|∧|\&{1,2}) +/,str:/[^\s:\(\)"'][^\s:\(\)]*/,ws:/ +/}),d={Lexer:c,ParserRules:[{name:"Expression$ebnf$1",symbols:[]},{name:"Expression$ebnf$1$subexpression$1",symbols:[c.has("or")?{type:"or"}:or,"Clause"]},{name:"Expression$ebnf$1",symbols:["Expression$ebnf$1","Expression$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Expression",symbols:["Clause","Expression$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[1]))]);return 1===t.length?t[0]:{type:"or",queries:t}}},{name:"Clause$ebnf$1",symbols:[]},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("and")?{type:"and"}:and],postprocess:s},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Clause$ebnf$1$subexpression$1",symbols:["__","Clause$ebnf$1$subexpression$1$ebnf$1","Factor"]},{name:"Clause$ebnf$1",symbols:["Clause$ebnf$1","Clause$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Clause",symbols:["Factor","Clause$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[2]))]);return 1===t.length?t[0]:{type:"and",queries:t}}},{name:"Factor",symbols:["Term"],postprocess:s},{name:"Factor",symbols:[c.has("lp")?{type:"lp"}:lp,"_","Expression","_",c.has("rp")?{type:"rp"}:rp],postprocess:function(e){const t=(0,a.compact)(e[2]);return 1===t.length?t[0]:t}},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("not")?{type:"not"}:not],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[c.has("op")?{type:"op"}:op],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1",symbols:["Term$ebnf$1$subexpression$1$ebnf$1",c.has("str")?{type:"str"}:str,c.has("col")?{type:"col"}:col,"Term$ebnf$1$subexpression$1$ebnf$2"]},{name:"Term$ebnf$1",symbols:["Term$ebnf$1$subexpression$1"],postprocess:s},{name:"Term$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term",symbols:["Term$ebnf$1","Value"],postprocess:l},{name:"Value",symbols:[c.has("qstr")?{type:"qstr"}:qstr],postprocess:u},{name:"Value",symbols:[c.has("str")?{type:"str"}:str],postprocess:u},{name:"_$ebnf$1",symbols:[c.has("ws")?{type:"ws"}:ws],postprocess:s},{name:"_$ebnf$1",symbols:[],postprocess:()=>null},{name:"_",symbols:["_$ebnf$1"]},{name:"__",symbols:[c.has("ws")?{type:"ws"}:ws]}],ParserStart:"Expression"};t.default=d},3996:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const a=i(19851),o=i(50213),l=i(79781),u=i(56519),c=i(56038),d=i(59189),h=i(38835),f=i(95696),m=i(48368),p=i(181),g=i(69589),y=i(28874),w=i(28544),v=i(47783),b=i(87001),S=i(40958),P=i(76790),T=i(22573),_=i(42659),M=i(55835),E=i(31586),D=i(43487),x=i(54017);t.isFileInSync=async function(e){return new F(f.PosixFile.for(e)).alreadySynced()};const k=new d.SerialLaterQueue;class F{constructor(e,t=(0,g.forceContextOrSetting)()){this.file=e,this.ctx=t,r.set(this,void 0),this.rejectedAssetIds=new Set,this.rejectedSiblingIds=new Set,this.alreadySynced=(0,c.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>n(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,c.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new x.AssetFile).updateFromFile_(this.file);return null==e?n(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,a.lazy)((async()=>{const e=await(0,v.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,a.lazy)((()=>y.Settings.useImageHashes.valueOrDefault?(0,m.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,a.lazy)((()=>(0,u.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,a.lazy)((async()=>{const e=await this.capturedAt_();return n(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,c.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,T.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return n(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await k.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return n(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new D.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,c.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,p.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtAndImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,c.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return n(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;n(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw n(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),s(this,r,(0,o.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f")}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),n(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}n(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(e=this.file){const t=await e.uri_();if(null!=t)return x.AssetFile.ops().firstf((e=>e.whereIn("uri",[...(0,b.uriEncodingVariants)(t),this.file.fileuri()])));n(this,r,"f").warn("byUri() uri is null",{file:e})}async assetByNormalizedPathUri(){const e=await this.file.normalize();return e.nativePath===this.file.nativePath?void 0:(await this.byUri(e))?.getAsset()}async assetBySha(){const e=await this.file.sha_();return D.Asset.findFirstByFile((t=>(t=t.where("AssetFile.sha",e),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds))),this.rejectedSiblingIds.size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),t)))}async assetByCapturedAtAndImageHash(){const e=await this.capturedAt_();if(null==e)return n(this,r,"f").throw("Cannot import, capturedAt is null"+h.InternalErrorFlag);if(y.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(x.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=y.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=x.AssetFile.query();return(0,E.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(_.secondMs,y.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,c.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)n(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(y.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void n(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const a=await this.dominantLabhashes();if((0,S.isNotEmpty)(a)){const t=e.localBoundaries({delta:4*s});if(null==t)n(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",a).orWhereIn("mode1",a).orWhereIn("mode2",a))));if(null!=e)return e}}const o=this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash));if(null!=o)return o;if(y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const r={};for(let e=0;e0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds)));const i=await this.firstSimilarAsset(x.AssetFile.ops().all(t));return null!=i&&n(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const s=(0,P.sortBy)(e.filter((e=>!this.rejectedSiblingIds.has(e.id)&&!this.rejectedAssetIds.has(e.assetId))),(e=>[(0,M.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of s)if(null!=e){await e.getNativePath();const i=x.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const s=(0,l.whyNotSameAsset)(t,e,i);if(null==s)return n(this,r,"f").info("Found sibling AssetFile",e),D.Asset.ops().findById(e.assetId);this.rejectedSiblingIds.add(e.id),n(this,r,"f").debug("Contemporary assetFile not similar: "+s,e?.uri)}}}t.AssetFileFinder=F,r=new WeakMap},34274:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult_=void 0;const u=i(19851),c=i(50213),d=i(73568),h=i(38835),f=i(95696),m=i(62105),p=i(74128),g=i(181),y=i(69589),w=i(28874),v=i(40958),b=i(22573),S=i(38639),P=i(59455),T=i(64526),_=i(19113),M=i(94710),E=i(3996),D=i(90901);t.importFileToResult_=async function(e){const t=T.Library.instanceRequired_();return(0,p.syncReport)().wrap_({path:e.path,from:"AssetFileImporter",fn_:()=>new x(f.PosixFile.for(e.path),t.assetFileRepository(),e).apply_()})};class x{constructor(e,t,i){r.add(this),this.file=e,this.repo=t,this.start=Date.now(),s.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else if(this.ctx.forceFilters||null==await this.prior()){const t=await(0,m.whyRejectFile)(this.file,(0,_.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,s,"f").throwIfAborted_();const i=await this.prior();if((0,v.isNotEmpty)(e)&&null!=i&&(l(this,s,"f").info("Deleting prior AssetFile",{rejected:e,prior:i}),i.delete(),this.ctx.skipAssetRepair?l(this,s,"f").info("Skipping asset repair",{assetId:i.assetId}):(l(this,s,"f").info("Scheduling asset repair",{assetId:i.assetId}),M.Task.addOne("repairAsset",{assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)}))),null!=i){const t=i.getAsset();null!=t?.deletedAt&&e.push("Asset is marked as deleted"),null!=t?.excludedAt&&e.push("Asset is marked as excluded")}if(l(this,s,"f").throwIfAborted_(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,b.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,s,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,s,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,s,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,r,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,s,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new E.AssetFileFinder(e,this.ctx),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=x,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(){l(this,s,"f").throwIfAborted_();const e=await l(this,s,"f").tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if((0,v.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,s,"f").throwIfAborted_();const t=await l(this,s,"f").tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,s,"f").throwIfAborted_();const i=await l(this,s,"f").tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return l(this,s,"f").throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return l(this,s,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,s,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,s,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;await l(this,s,"f").tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault}),l(this,s,"f").throwIfAborted_();try{o=await(0,D.assetPostUpsertTasks_)({asset:a,...this.ctx})}catch(e){e instanceof d.AbortError?l(this,s,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,s,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:r,assetFile:i,asset:a,uri:n,uris:[n,...(0,P.toA)(o?.newAssetFileUris)]}}},41844:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(50213),c=i(74128),d=i(81674),h=i(57902),f=i(4936),m=i(28874),p=i(47783),g=i(14245),y=i(67083),w=i(16170),v=i(54979),b=i(98604),S=i(40958),P=i(22573),T=i(98553),_=i(68708),M=i(89937),E=i(59455),D=i(54017),x=i(94710);t.mayCopyAssetsToLibrary=async function(){return m.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,u.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!0!==m.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,d.l)())return"no active subscription";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(m.Settings.libraryDir.valueOrDefault))return e+" already contained by "+m.Settings.libraryDir.valueOrDefault;const t=await(0,v.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,w.isMimeTypeIncluded)(t,m.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(M.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,E.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(D.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),x.Task.addOne("repairAsset",{assetId:t,forceSync:!0})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,T.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return a.addAssetFile(d),(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,p.readCapturedAt)(e),i=(0,f.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,p.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,p.readTags)(e);if(null!=i){if(m.Settings.writeGeolocationTagsToLibraryCopies.valueOrDefault){const e=(0,g.geolocationToXmp)(i);(0,_.isEmptyObj)(e)||await(0,p.writeTags_)(t,e)}return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred)}this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},90901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const r=i(50213),s=i(92434),n=i(73568),a=i(99331),o=i(39250),l=i(38835),u=i(57159),c=i(48604),d=i(66106),h=i(69589),f=i(40958),m=i(45599),p=i(23838),g=i(31586),y=i(64526),w=i(88224),v=i(43487),b=i(41844),S=i(68640),P=(0,m.defer)((()=>(0,r.mkLogger)("sync-file.AssetPostUpsertTasks"))),T=(0,m.defer)((()=>new o.LastOneInWins("Asset tasks")));async function _(e){const t=e,i=e,r=(0,g.toGt0)(t.asset?.id)??(0,g.toGt0)(i.assetId);if(null==r)throw new Error("assetPostUpsertTasks_(): unexpected null assetId"+l.InternalErrorFlag);const o=(0,h.forceContextOrSetting)(e),m=P().addContext(`.postUpsertAssetTasks_(Asset:${r})`);if(m.abortable=o.halt,o.skipPreviews&&o.skipAssetTagging)return void m.info("skipped (skipPreviews && skipAssetTagging)");const _=t.asset??v.Asset.ops().findById(r);if(null==_)return m.throw("unexpected null asset",{asset:_});try{return await T().enqueue({key:r,abortable:m.abortable,fn:()=>async function(e,t,i){const r=(0,h.forceContextOrSetting)(i),n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted_(),(0,f.isEmpty)(a)&&(await v.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,b.mayCopyAssetsToLibrary)())for(const[t,i]of(0,p.groupBy)(a,(e=>e.sha)).entries()){e.throwIfAborted_();try{for(const r of i)r.isInLibrary()&&await r.exists()&&e.debug("no-op for file SHA: already in library.",{sha:t,uri:r.uri});for(const e of i)if(await e.exists()){const t=await y.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,r);if(null!=t){o.newAssetFileUris.push(t.uri);continue}}}catch(r){e.warn("Failed to copy variation to library, but we'll try to continue",{sha:t,uris:i.map((e=>e.uri)),error:r})}}e.throwIfAborted_();const l=r.skipPreviews?void 0:await(0,S.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...r}),u=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?P().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,s.bestExistingAssetFile)(e.getAssetFiles())}(t,l);if(null==u)return e.throw("null primaryOrShownAssetFile_()",{asset:t});const m=await u.posixFile_();if(!0!==r.skipPreviews&&t.isVideo()){if(null==m)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});o.transcoded=null!=await(0,d.transcode_)(m,c.Previews.instance().ap(n).mp4(),{force:r.forceRebuildPreviews,halt:r.halt})}return e.throwIfAborted_(),t.markShownAndUpsert_(u),r.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,w.tagAndUpsertAsset_)(t),o}(m,_,{...e,...o})})}catch(e){if(e instanceof n.AbortError)return void m.warn("aborted, next caller will clean up my mess",{error:e});const t=[e];if(!(0,a.ending)()){m.error("failed, marking asset unshown",{error:e});try{_.markUnshownAndUpsert()}catch(e){m.error("failed to mark asset unshown",{upsertError:e}),t.push(e)}}throw new u.WrappedError("Failed to post-process assset "+_.id,{causes:t})}}t.assetPostUpsertTasks=function(e){try{return _(e)}catch(e){if(e instanceof n.AbortError)return void P().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=_},61989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset_=t.updateAsset=void 0;const r=i(48884),s=i(50213),n=i(45393),a=i(79184),o=i(79781),l=i(92434),u=i(56519),c=i(70417),d=i(69589),h=i(28874),f=i(40958),m=i(22573),p=i(38639),g=i(50357),y=i(43487),w=i(54017),v=i(3996),b=i(90901);async function S(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,r=(0,s.mkLogger)(`sync-file.UpdateAsset(${i})`);r.abortable=t.halt;const S=y.Asset.ops().findById(i);if(null==S)return r.throw("no such asset");const T=S.getAssetFiles({refresh:!0});if((0,f.isEmpty)(T))return r.warn("No asset files: deleting."),S.delete(),{asset:S,rejected:"Empty asset (no AssetFiles)"};const _=S.$clone(),M=S.getShown()?.$clone();for(const e of T)r.throwIfAborted_(),await e.upsertIfNeeded_(void 0,t);T.some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&S.clear(),await P(r,T);const E=(0,l.sortAssetFiles)(T),D=E?.[0];if((0,f.isEmpty)(E)||null==D)return r.warn("No existing files. Skipping for now."),S.markUnshownAndUpsert(),{asset:S,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!D.isVersionUpToDate())return r.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:D}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${D.id}, could not be updated. Un-showing Asset:${i}`};const x=await D.capturedAt();if(null==x)return r.warn("Best file failed to extract a captured-at",{bestAcceptedAF:D}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${D.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const k=new Set,[F,C]=await(0,u.partitionAsync)(E,(e=>(0,o.isSimilarAssetFile)(e,D)));if(r.throwIfAborted_(),(0,f.isNotEmpty)(C)){const e=await(0,a.aggregateAssetFiles)(C);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});k.add(e.id);for(const i of t)e.addAssetFile(i);w.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),r.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function A(e){return(0,f.uniq)(F.map((t=>t[e])))}const I=await Promise.all(F.map((e=>e.capturedAt()))),O=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,L=I.map((e=>e?.localBoundaries({delta:O}))),R=(0,c.min)(L.map((e=>e?.start)))??x.localBoundaries({delta:O})?.start,N=(0,c.max)(L.map((e=>e?.end)))??x.localBoundaries({delta:O})?.end,B=w.AssetFile.ops().all(w.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${D.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",A("sha")),null==R||null==N?r.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:R,endBoundary:N}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[R,N]),e.orWhereIn("AssetFile.meanHash",A("meanHash")).orWhereIn("AssetFile.diffHash",A("diffHash")).orWhereIn("AssetFile.dctHash",A("dctHash"))))));if(r.throwIfAborted_(),h.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const e=await D.posixFile();if(null==e)r.info("bestAcceptedAF has no posixFile, cannot expand query for fuzzy dates",{bestAcceptedAF:D});else{const i=new v.AssetFileFinder(e,t);for(const e of[...F,...B])i.rejectedAssetIds.add(e.assetId),i.rejectedAssetIds.add(e.id);let s=h.Settings.maxContemporaryAdoptionAssets.valueOrDefault;for(;--s>0;){r.throwIfAborted_();const e=await i.assetByCapturedAtAndImageHash();if(null==e){r.info("allowFuzzyDateImageHashMatches(): no additional assets found to adopt");break}if(r.info("allowFuzzyDateImageHashMatches(): found asset with similar image",{a:e}),null!=e){i.rejectedAssetIds.add(e.id);for(const t of e.getAssetFiles())r.info("found asset file by fuzzy date and image hash",{uri:t.uri,assetId:e.id}),B.push(t),i.rejectedAssetIds.add(t.id)}}}}r.info("asset file candidates for adoption: ",B.map((e=>e.posixPathFromGrandparent)));const j=[];for(const e of B){r.throwIfAborted_();try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,D)&&(r.info("adopting similar asset file",{af:e}),k.add(e.assetId),e.shown=!1,S.addAssetFile(e),e.upsert(),j.push(e))}catch(t){r.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}}r.info("fetched expansion",{retainAFs:F.map((e=>e.id)),rejectAFs:C.map((e=>e.id)),externalAssetFiles:B.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:j.map((e=>e.posixPathFromGrandparent))}),await P(r,[...F,...j]),t.skipPreviews&&t.skipAssetTagging?(r.info("skipping previews and tagging",t),S.upsert()):await(0,b.assetPostUpsertTasks_)({...t,asset:S});const z=!(0,g.eql)(_,S),V=!(0,g.eql)(M,S.getShown()),W=!(z||V||t.forceRebuildPreviews||t.forceSync);return r.tap({msg:"updateAsset() result",level:"info",result:{asset:S,assetIdsToUpdate:Array.from(k),assetFiles:S.assetFiles,skipped:W},meta:{ctx:t,assetChanged:z,primaryAssetFileChanged:V}})}async function P(e,t){const[i,s]=(0,r.partition)(t,(e=>e.isVersionUpToDate()));for(const t of s){e.throwIfAborted_();const r=i.find((e=>e.sha===t.sha));if(null!=r){e.info("backfilling",{sibling:r,dest:t});const i=await t.updateFromShaSibling_(r);null!=i&&i.upsert()}}}t.updateAsset=async function(e){try{const t=await S(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}},t.updateAsset_=S},93755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t.updateAssetFile_=t.updateAssetFile=void 0;const r=i(50213),s=i(92434),n=i(98314),a=i(74128),o=i(69589),l=i(87001),u=i(40958),c=i(22573),d=i(68708),h=i(43487),f=i(54017),m=i(94710);async function p(e){const t=Date.now(),i=e,s=e,n=s.af?.id??i.assetFileId,u=(0,r.mkLogger)(`updateAssetFile(${n})`),d=s.af??f.AssetFile.ops().findById(n);if(null==d)return u.throw("db record not found",{assetFileId:n});const h=await d.posixFile_(),p=(0,o.forceContextOrSetting)(e),w={id:n,assetFileId:n,path:h?.nativePath,uri:d?.uri};if(null==h){const e=["cannot resolve URI"];return(0,c.blank)(d.mountpoint)||e.push("is "+d.mountpoint+" mounted?"),(0,a.syncReport)().onProgress({path:d.uri,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:e.join(": "),state:a.SyncFileStates.skipped}),{...w,error:"file for URI not found"}}const v=await(h?.isDeletedUri(d.uri));if(null==v)return u.info("no-op: file URI points to an unmounted volume",w),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:((0,c.toNotBlank)(d.mountpoint)??"volume")+" is not currently mounted",state:a.SyncFileStates.skipped}),{...w,skipped:!0};const b=e.whyReject??await d.whyRejected();if(v||!(0,c.blank)(b)){const e={...w,rejected:b,deleted:v};return u.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:v?"file no longer exists":"rejected: "+b,state:a.SyncFileStates.deleted}),d.delete(),!0!==p.skipAssetRepair&&m.Task.addOne("repairAsset",{assetId:d.assetId}),e}const S=await h.uri_();if(!await(0,l.uriIsEquivalent)(S,d.uri)){const e=await g(d,S,p);if(null!=e)return{...w,...e}}return!p.forceSync&&await d.matchesFile()?(u.info("no-op: file already matches db record",w),d.touch(),{...w,skipped:!0}):{...w,...await y(d,p)}}async function g(e,t,i){const n=(0,r.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,u.uniq)([...(0,l.uriEncodingVariants)(e.uri),...(0,l.uriEncodingVariants)(t)]);n.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const o=f.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,u.isNotEmpty)(o)){n.warn("Found other AssetFiles with equivalent URIs.",{afIds:o.map((e=>e.id))});const t=[e,...o],r=(0,s.sortAssetFiles)(t);if((0,u.isEmpty)(r))return n.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,d.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const l=t.map((e=>e.id));for(const e of r)if(await e.exists()){f.AssetFile.dbl.runf((t=>t.whereIn("id",l.filter((t=>t!==e.id))).delete()));const r=y(e,i);return h.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,u.uniq)(t.map((e=>e.assetId)))))),r}}n.info("no-op, no duplicate URIs.")}async function y(e,t){const i=Date.now();return null!=await e.upsertIfNeeded_(void 0,t)&&h.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:await e.getNativePath(),elapsedMs:Date.now()-i,from:"updateAssetFileIfNeeded()",state:e.syncState??a.SyncFileStates.unknown}),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await p(e)}catch(t){return{id:e.assetFileId,...e,error:(0,n.errorToS)(t)}}},t.updateAssetFile_=p,t.handleAssetFileUriChange=g,t.updateAssetFileIfNeeded=y},68640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const r=i(99331),s=i(38835),n=i(48604),a=i(50213),o=i(69589),l=i(87001),u=i(40958),c=i(45599),d=i(50357),h=i(31586),f=i(68708),m=i(59455),p=i(43487),g=(0,c.defer)((()=>(0,a.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,m.toA)(e.assetFiles).find((e=>(0,h.gt0)(e.assetId)))?.assetId,i=(0,o.forceContextOrSetting)(e),a=g().addContext(".Asset:"+t);if(i.skipPreviews)return void a.warn("skipPreviews is true: no-op");if(!(0,h.gt0)(t))return a.throw("invalid assetId",{assetId:t});const c=e.asset??p.Asset.ops().findById(t);if(null==c)return a.throw("Asset:"+t+" not found");a.throwIfAborted_(i.halt);try{const e=await c.getExistingAssetFiles();if((0,u.isEmpty)(e))return void a.warn("no existing assetFiles",{asset:c});const r=n.Previews.instance().ap(t),o=await r.readInfo();a.throwIfAborted_(i.halt);const h=await(0,n.buildAssetPreviews_)({...i,assetId:t,assetFiles:e}),m=e.find((e=>e.id===h?.assetFileId))??e.find((e=>(0,l.uriIsEquivalent)(h?.uri,e.uri)));a.info("buildAssetPreviews_()",{result:h,primaryAssetFile:m});const p=await(m?.posixFile_());if(null==m||null==p||!0!==await(p?.exists()))return a.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:h,assetFiles:e.map((e=>(0,f.pick)(e,"id","uri"))),primaryAssetFile:m,primaryPosixFile:p});const g=(0,d.eql)(o,h),y=null==h||g;return{...h,noop:y}}catch(e){throw(0,r.ending)()||(a.warn("Failed to update previews. Un-showing asset "+t,{error:e}),c.markUnshownAndUpsert()),e}}},7656:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.DirectAssetCountForTagQuery=t.RecursiveAssetCountForTagQuery=t.nonLeafTagIds=void 0;const r=i(50213),s=i(56038),n=i(95704),a=i(38156),o=i(42659),l=i(45599),u=i(41400),c=i(31586),d=i(51926),h=(0,l.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function f(e){return e.prepare((0,d.compressWhitespace)("SELECT"," t1.id,"," count(t2.id) AS cnt","FROM"," Tag t1"," JOIN Tag t2 ON t1.id = t2.parentId","GROUP BY"," 1","HAVING"," cnt > 0")).pluck().all()}async function m(e,i=[]){const r=e.prepare(t.RecursiveAssetCountForTagQuery).pluck(),o=e.prepare(t.DirectAssetCountForTagQuery).pluck(),l=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId"),c=new Set(f(e)),d=new a.PushProgressObserver({op:"Rebuilding tag asset counts"},e.prepare("SELECT count(*) FROM Tag").pluck().get());await(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e){const e=!c.has(t);(0,s.timeSync)("db.rebuildTagAssetCounts("+(e?"leaf":"cte")+")",(()=>{const s=(e?o:r).get({tagId:t});l.run({tagId:t,assetCount:s,updatedAt:Date.now()}),d.incrProgress(),h().debug("_rebuildTagAssetCounts()",{isLeaf:e,whereClauses:i,tagId:t,assetCount:s})})),t%10==0&&(h().throwIfAborted_(),await(0,u.delay)(1))}}}),d.completed()}t.nonLeafTagIds=f,t.RecursiveAssetCountForTagQuery=(0,d.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.DirectAssetCountForTagQuery=(0,d.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," AssetTag"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," AssetTag.tagId = :tagId"," AND Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL;"),t.rebuildTagAssetCounts=async function(e,t=o.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>m(e,["assetCount IS NULL"]))),(0,c.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rm(e)))}},69032:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(1728),c=i(56038),d=i(34102),h=i(49076),f=i(69589),m=i(28874),p=i(42231),g=i(85087),y=i(98770),w=i(59107),v=i(63870),b=i(7014),S=i(22573),P=i(42659),T=i(41400),_=i(75240),M=i(31586),E=i(34666),D=i(51926),x=i(75020),k=i(54017),F=i(48723),C=i(98784),A=i(7656),I=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>C.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return I().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=((0,o.isTest)()?5:30)*P.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=I().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),F.Tag.validate_(),s.throwIfAborted_(i?.halt),await L(),i.recountAllTags&&(s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)(),s.info("rebuilding tag asset counts..."),await(0,A.rebuildTagAssetCounts)(F.Tag.dbl.db().db,0))}catch(e){I().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,M.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),I().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const L=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{I().info("updating tag mountpoints...");const e=F.Tag.findByPath([x.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await N(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function R(){t.tagFtsRebuild.unset(),L.unset()}async function N(e){if(null==e||2!==e.depth||!e._path.startsWith(x.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===x.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),F.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,v.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),F.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,T.later)((()=>{(0,d.ee)().on("clearCache",R),m.Settings.libraryDir.watchLater(R)})),t.fixFileRootTag=N,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):k.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,v.volumeMetadataTtlMs)()}),(0,T.later)((()=>{w.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},16436:e=>{"use strict";e.exports=require("@sentry/node")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},87550:e=>{"use strict";e.exports=require("better-sqlite3")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},66150:e=>{"use strict";e.exports=require("fast-xml-parser")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},31832:e=>{"use strict";e.exports=require("knex")},51168:e=>{"use strict";e.exports=require("luxon")},93973:e=>{"use strict";e.exports=require("ml-kmeans")},80265:e=>{"use strict";e.exports=require("moo")},31704:e=>{"use strict";e.exports=require("nearley")},4927:e=>{"use strict";e.exports=require("papaparse")},83058:e=>{"use strict";e.exports=require("picomatch")},57272:e=>{"use strict";e.exports=require("plist")},85949:e=>{"use strict";e.exports=require("process")},57160:e=>{"use strict";e.exports=require("punycode.js")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},49378:e=>{"use strict";e.exports=require("trash")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},29907:e=>{"use strict";e.exports=require("cluster")},76982:e=>{"use strict";e.exports=require("crypto")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=53493);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/logcat.js b/bin/logcat.js index cfe7b8d..f69ef75 100755 --- a/bin/logcat.js +++ b/bin/logcat.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={37975:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),n=i(22573),s=i(38639);function o(){return(0,s.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,n.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),n=i(7282),s=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),n=i(36783),s=i(76790),o=i(22573),a=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const n=new Set(t.map(i));return e.filter((e=>n.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function E(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,i){return x(e,t,i).index}function x(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let r=0;re.slice(i,i+t)))}async function T(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let n=0;for(const s of e)(t(s,n++)?i:r).push(s);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=E,t.least=function(e){return E(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=x(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=C,t.collectBatched=function(e,t,i){const n=[];for(const s of C((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(i(s)));return n},t.collectBatchedAsync=async function(e,t,i){const n=[];for(const s of C((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(await i(s)));return n},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await T(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+n;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=i(77988),l=o(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),S=i(99331),b=i(95937),P=i(98314),_=i(38835),E=i(70025),M=i(8769),x=i(43334),C=i(95402),T=i(28874),D=i(63870);class k extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,r,"m",n).call(this)),i,"worker"===e?(0,D.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const o=t;o.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,C.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,i,r)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&C.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,E.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=k,r=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(x.isWin?3:1)*c.minuteMs,maxTasksPerProcess:T.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:T.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:T.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,D.commandTimeoutMs)(),taskTimeoutMillis:T.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,i){var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,r,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,r,"m",a).call(this,0,(e=>{var t,i;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(i=u(this,s,"f"),--i),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const i=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of n)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,r.toS)(e)},t.bufferStartsWith=o},9092:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(40958),a=i(23838),l=s(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,n=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(r=e,n=o)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),n=i(31586),s=i(68708),o=i(54993),a=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,n]of this.m.entries()){const s=e(r);t.fill(s,i,i+n),i+=n}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),n=i(72993),s=i(45969),o=i(43334);t.EditionType=(0,r.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),n=i(55835),s=i(68708);var o=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.omit)(e,...i),(0,s.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,n.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),n=i(19851),s=i(95696);t.examples=(0,n.lazy)((()=>s.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),n=i(65843),s=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,n.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),n=i(40958),s=i(55835),o=i(31586),a=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,i){var r,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(i=l(this,n,"f"),++i),"f"),c.promise):(u(this,r,(o=l(this,r,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(a=l(this,r,"f"),++a),"f"),c}get(e){var t,i;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(r=l(this,a,"f"),++r),"f")})),r.promise}},r=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,r).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,a=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(a,r.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,n.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),n=i(98553);var s=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,n.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,r.readFile)(e)).toString())}},19851:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(57975),a=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,r,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(42659),a=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?E():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,n.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function E(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=E,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),n=i(1708),s=i(45599),o=i(68708),a=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,s.defer)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:n.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,o.pick)(n.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:n.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),n=i(32105),s=i(14593);t.rootLoggers=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},56639:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),n=i(55835),s=i(59455),o=i(48884);function a(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,r.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,n.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),n=i(54557);t.memoize=function(e,t){let i=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,r.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,r.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},7282:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=r(i(1708)),s=i(38639),o=i(54993),a=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(55835),a=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=r&&r>0&&null!=n&&n>0?i(r,n):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(f.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function p(e){return(0,a.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const n=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),n=i(42659),s=i(96249),o=i(55835),a=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,n]of(0,l.entries)(e)){const e=t(r,n);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const n of t)r[n]=i(n,e[n]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let n=0;for(const s of(0,l.keys)(e))if(r[s]=t(s,e[s]),n++,(0,a.gt)(n,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,s.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),n=i(73024),s=i(48161),o=i(19851),a=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,o.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return k();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function _(){return"ubuntu"===(0,t.osDistributionLinux)()}function E(){return"fedora"===(0,t.osDistributionLinux)()}function M(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,n.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=_,t.hasApt=function(){return P()||_()},t.isFedora=E,t.isAlpine=M;const x={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},C={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function T(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),n=t[i];return(0,c.isString)(n)?n:n?.[r]}const D=(0,o.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function k(e=D()){try{return(0,a.mapNotBlankOr)(function(e=D()){return T(e,x)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":T(e,C);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=k,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=D();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(_())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(E())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(M())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},12801:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=r(i(48161)),s=i(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),n=i(56409),s=i(31586),o=i(22911),a=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...r){f=!0,m=Date.now()+(0,s.max_)(t,i);const n=d=new o.Deferred(c);(0,s.gt0)(i)&&n.setTimeout(i);try{n.resolve(await e(...r))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return n.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return p.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),n=i(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(n,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(s(t))}const n=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,r||(r=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,n.toS)(t));return new RegExp(i,t??(r?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=r(i(48161)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),S=i(24399),b=i(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let E=!0;const M=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),E)try{return n.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;E=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=r(i(1708)),s=i(19851),o=i(40958),a=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function n(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=n(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=n(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),n=i(57150),s=i(7282),o=i(23560),a=i(17181);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,a.setupLogger)(),(0,n.logStartup)())}},28850:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const a=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends a.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),n.set(this,void 0),s(this,r,e,"f")}_call(){return(0,l.time)(o(this,r,"f")+(null==o(this,n,"f")?"(local)":"(remote)"),null==o(this,n,"f")?this.impl():o(this,n,"f").call(this))}setShim(e){s(this,n,e,"f")}hasShim(){return null!=o(this,n,"f")}clearShim(){s(this,n,void 0,"f")}}r=new WeakMap,n=new WeakMap},12089:function(e,t,i){var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,o){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",o).call(this,e),(()=>u(this,r,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,r=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=i(76790),o=i(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return n(this,r,"f")[Symbol.iterator]()}get length(){return n(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=n(this,r,"f").length-1;for(;t<=i;){const s=t+Math.floor((i-t)/2),o=this.valueOf(n(this,r,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:i=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...n(this,r,"f")];const o=t=>t<0||t>n(this,r,"f").length-1?null:(i??this.diff)(n(this,r,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return n(this,r,"f").shift()}at(e){return(0,o.at)(n(this,r,"f"),e)}toA(){return[...n(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,r,"f").length-1){const e=[...n(this,r,"f")];return n(this,r,"f").length=0,e}return n(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,r,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),n=i(82328),s=i(84542),o=i(95705),a=i(28874);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),n=i(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(r.stdout)}},71567:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=r(i(1708)),s=i(22573),o=i(98553),a=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);r.write(n+"\n"),(0,a.isWorkerService)()&&null!=i&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(55835),a=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const n=t.indexOf(i,r);return-1===n?0:1+e(t,i,n+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,a.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(r.slice(-n.length),n,i)?r.slice(0,-n.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),n=r.length-(t+i);return n<=0?r:r.slice(0,t).trim()+" …(+"+n+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),n=t.indexOf(r);if(n>=0)return{index:n,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function E(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=E;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(E(e))&&(e=e.slice(1,-1).trim())),e};const x=/^['‘’].*['‘’]$/,C=/^["“”„«»〃].*["“”„«»〃]$/;function T(e,t){const i=D(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,i.push(e.substring(s,n.index)),r.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),x.test(e)||C.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),n=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=T,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,n.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,s.blank)(r))for(const e of r.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>r.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function n(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=r(i(77598)),s=i(73913),o=i(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,r=224){return i.encodeBuffer(a(e,r)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(31586),a=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,n="";for(let s=0;s=r&&(r=i.get(s,o),n=(0,l.substr)(e,s-r+1,r)));return n}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),n=t.normalize();return e!==r||t!==n?y(r,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),n=[];return i.forEach((i=>{const s=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,o.times)(s,(()=>n.push(i)))})),n}function b(e,t,i){const n=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,n))-i((0,l.strslice)(t,n))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,r]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,r,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const E=/[^\da-z]+/gi;function M(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(E,"").toLowerCase()));return b(i,r,(e=>c.RadixAlphaNum.decode(e)))}function x(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const n=(0,o.mapNumericOr)(e.charCodeAt(r),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(r),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=M,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=x,t.paddedPositionalDiff=function(e,t,i=8){return x((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},84885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),n=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,n.sortedKeys)(e))}},75387:function(e,t,i){var r,n,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",n.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const n=t();return null!=n&&this.set(e,n),n}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,n,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,n,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,r,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,r,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,r,"m",n).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,r,"m",n).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,r,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,r,"m",s).call(this),[...this.delegate.keys()]}[(r=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,r,"m",n).call(this,e,t)}},84699:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},94174:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=r(i(48161)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),n=i(55835),s=i(31586),o=i(97790),a=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,r,"f")&&clearTimeout(s(this,r,"f")),o(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,n=new WeakMap},22911:function(e,t,i){var r,n,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),S=i(45599),b=i(26905),P=i(55835),_=i(31586),E=i(68708),M=i(20214),x=i(57153),C=i(85556),T=i(50213),D=i(70025),k=i(95937),O="TIMEOUT",F=(0,S.defer)((()=>(0,T.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,_.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const n=i[r];if(n.isSettled){if(n.name===O)return void F().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield n.value}}if(i.every((e=>e.name===O)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,x.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=n,n,(y=p(i,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,T.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,E.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new C.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===x.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==x.PromiseStates.pending}get isResolved(){return p(this,a,"f")===x.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===x.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,a,x.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,x.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,n=I,m=function(e){if(p(this,a,"f")===x.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},27395:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),n=i(40958),s=i(42659),o=i(23838),a=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,a.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,n.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,n.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",o).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,o){this.endTimeoutMs=o,r.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){o(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,n=new WeakMap},99331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,r.isTest)()?e:e||n}},45608:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=r(i(1708)),s=i(22573),o=i(45599),a=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},5916:function(e,t,i){var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new S(e,t,i,r)};class S extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,r,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,a,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(i=c(this,s,"f"),++i),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},1728:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),n=i(80049);t.memoizeAsync=function(e,t){let i=0;const s=new n.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,r.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},22781:function(e,t,i){var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),n.set(this,!1),s.set(this,!1)}_call(){return o(this,n,"f")?(a(this,s,!0,"f"),!0===this.undefinedIfBusy?void 0:o(this,r,"f")):(a(this,n,!0,"f"),a(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{a(this,n,!1,"f"),!0===this.runLaterIfBusy&&o(this,s,"f")&&(a(this,s,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return o(this,n,"f")}prior(){return o(this,r,"f")}async force(){return await o(this,r,"f"),this._call()}}r=new WeakMap,n=new WeakMap,s=new WeakMap},37461:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),n=i(76790),s=i(38639),o=i(42659),a=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var S=i(20214);async function b(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:n}){const s=[];for(const o of(0,r.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(i(o),n):i(o));null!=e&&s.push([e,o])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,r.compact)(await e);if((0,r.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(i,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(i,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,i){const r=[];for(const n of(0,p.batches)((0,f.toA)(await e),t)){const e=await b(n);r.push(...await b(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,n=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(n??r)}catch{}if(null!=n)throw n;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const n=await t;return null!=n?i(r,n):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const n=await t(r);return null==n?i():n},t.thenMap2Or=async function(e,t,i,r){const n=await e;if(null==n)return r();const s=await t;if(null==s)return r();const o=await i(n,s);return null==o?r():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await E({name:e,arr:t,f:i});return(0,n.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(42659),a=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),S=i(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-r;return i?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function E(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),r=t();return E(e,Date.now()-i),r},t.pushTime=E,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>_(e,t)),i)}},42638:function(e,t,i){var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),S=i(82647),b=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:n}){const s=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const n=new P.Deferred(e,{payload:i,serialId:r});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},4867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),n=i(34546),s=i(41400),o=i(31586),a=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let a=!0;return Promise.race((0,r.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),n=i(42659),s=i(41400),o=i(32639),a=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=r(i(1708)),s=i(45599),o=i(41400),a=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),S=i(88158),b=i(45969),P=i(43334),_=i(28874),E=i(3790);function M(e){return x().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const x=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const C=["HOME","LANG","USER"],T=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],D=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?C:T),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function k(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,_.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,a.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(n.default.env,(e=>M(e)||!(0,E.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=k,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:F({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function F({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...D(),...i?(0,g.childProcLocale)():{},...k(r),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,E.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return n}t.childEnv=F},84777:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=r(i(31421)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),S=i(22911),b=i(4867),P=i(73614),_=i(70025),E=i(57159),M=i(36868),x=i(66184),C=i(45643),T=i(95402),D=i(9727),k=(0,o.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function F(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,T.killPid)(i).catch((e=>{k().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,C.waitForPidExit)(i,t))return k().debug("endProcess(): exitted",O(e)),!0;{T.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");k().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,T.killPid)(i,!0).catch((e=>{k().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,C.waitForPidExit)(i,5e3)}function I(e,i,r,n=0){const o=new Date,a=[];return(0,v.niceable)(i,r)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&F(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,T.addPid)({pid:e.pid,cmd:i,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,r){const s=(0,D.spawnOptions)(r);return(0,x.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(n.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const r=i.quiet??!1,n=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new S.Deferred(f);o.on("error",(e=>g.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>g.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>g.push(e))),o.stderr?.on("data",(e=>p.push(e))),o.stderr?.on("end",(()=>P.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),k().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const x=p.join("");(0,l.notBlank)(x)&&g.push(new Error(x)),!r&&(0,a.isNotEmpty)(g)&&k().warn(f+" resulted in errors:",g);const C=i.isIgnorableError??_.isIgnorableError,T=g.filter((e=>!0!==C(e)));if(T.length>0)throw 1===T.length?T[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:T});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:x}}catch(e){throw k().error("stdoutResult_() failed",e),await(0,T.killPid)(o.pid,!0),e}}t.endProcess=F,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const s=(0,D.spawnOptions)(r);return k().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(n.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const r=await A(e,t,i);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},3790:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),n=i(41400),s=i(19851),o=i(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},34330:function(e,t,i){var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),S=i(25764),b=i(99331),P=i(42638),_=i(38835),E=i(8769),M=i(57159),x=i(66003),C=i(50213),T=i(45643),D=i(28874),k=i(84777);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,k.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,C.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),n.set(this,!1),this.onError=(e,t,i)=>{const s=new M.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,n,"f")||o||(this.lastError=s,(0,E.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,r,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:D.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,n,"f")}async end(){return c(this,n,!0,"f"),u(this,r,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,n,"f")}),!u(this,n,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",s).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=O,n=new WeakMap,r=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,n,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",o).call(this,e)},o=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,T.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,k.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",s).call(this),!this._stopped&&!u(this,n,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,E.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,n,"f")}),this._stopped||u(this,n,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,x.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,E.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,n,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(53916)),a=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,a.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),n=i.sibling(r);if(n.isSelfOrDescendantOf((0,l.examples)()))return o.join("$examples",n.posixPathFrom((0,l.examples)()));const s=(0,d.originalsDir)();if(n.isSelfOrDescendantOf(s))return o.join("$library",n.posixPathFrom(s));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?o.join("$library",n.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const s=i(6858),o=i(1708),a=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return n(this,r,"f").push(...e),this}async parse(e=o.argv,t){let i=(0,m.addHelpFooter)(new s.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of n(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":a.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,o.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of n(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),n=i(31586),s=i(51926),o=i(17344),a=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,n.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),n=i(38639),s=i(17181),o=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,n.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),o.Settings.logColor.envValue=e,(0,s.setupLogFormatter)()}))}}},94361:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),n=i(40958),s=i(55835),o=i(31586),a=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,o.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},76596:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),n=i(19851),s=i(22573),o=i(42659),a=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),n=i(31586),s=i(54557),o=i(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),n=i(40958),s=i(22573),o=i(42659),a=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},84248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},15056:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),n=i(7311);function s(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(n.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(76760)),a=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),S=i(29882),b=i(45969),P=i(43334),_=i(28874),E=i(41692),M=i(32774),x=i(80612),C=i(32551),T=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+T(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+T()),preexistingDir:i});return e}}function k(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+T(),preexistingDir:M.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,C.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,C.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,C.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,x.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,x.firstDir)({dirs:k(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,E.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(F)}));function F(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},46292:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),n=i(45969),s=i(41692),o=i(32774),a=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),n=i(45969),s=i(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=r(i(76760)),s=i(40958),o=i(72993),a=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),n=i(96706),s=i(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),n=i(40958),s=i(22573),o=i(66430);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),n=i(76760),s=i(1708),o=i(19851),a=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),n=i(49776),s=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,n.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),n=i(54993),s=i(29882),o=i(28874);function a(e){return(0,r.toNotBlank)((0,n.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),n=i(55835),s=i(37805),o=i(15056),a=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e),!1)}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function E(e){return y(_(e))}async function M(e){return y((0,n.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await S(t),await P(t),await E(t),await M(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=E,t.setupLibraryDbDir_=M},46296:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=r(i(76760)),s=i(19851),o=i(40958),a=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(44198),a=i(43334),l=i(24399),u=i(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),n=i(7282),s=i(29325),o=i(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,r.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),n=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=r(i(73024)),s=i(76760),o=r(i(1708)),a=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),S=i(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),i={...o.default.env};for(const r of e)try{const e=(0,d.debom)(n.default.readFileSync((0,g.resolve)(r))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(s))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),n=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,r.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},96706:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=r(i(1708)),s=i(19851),o=i(22573),a=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,a.isTrue)(g(e))}},98314:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),n=i(19851),s=i(40958),o=i(22573),a=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),r=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),r-o.length,n)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),n=i(26905),s=i(55835),o=i(54993),a=i(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,n.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),n=i(76790),s=i(50989),o=i(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),n=i(38639),s=i(26905),o=i(54993),a=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),n=i(31586),s=i(68708),o=i(7282),a=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===i.fatal,c=!0===i.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),n=i(22573),s=i(38639),o=i(26905),a=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,n.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,n.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(49769),a=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,r,"f").get(e);return null!=o&&(o.resolve(t),s(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,n=new WeakMap},34102:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),n=i(19851),s=i(15197);t.ee=(0,n.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=r(i(73024)),s=r(i(1708)),o=i(19851),a=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,n.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=r(i(76760)),s=i(19851),o=i(81168),a=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,o.equalsIgnoreCase)(e.basename,i.base))return n.default.join(r,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),n=i(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,i){var r,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),v=f(i(1708)),w=i(46466),S=f(i(57975)),b=f(i(38522)),P=i(19851),_=i(40958),E=i(5233),M=i(22573),x=i(42659),C=i(50357),T=i(96249),D=i(98553),k=i(55835),O=i(31586),F=i(68708),I=i(97790),L=i(39926),A=i(51926),N=i(59455),R=i(54993),j=i(48884),B=i(22911),V=i(99331),z=i(56519),W=i(56038),U=i(31562),q=i(76850),H=i(70025),G=i(34102),J=i(80875),$=i(50213),K=i(70417),Y=i(43334),Z=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),ne=i(89968),se=i(20197),oe=i(88561),ae=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),Se=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,r=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,M.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const n=(0,fe.resolve)(i),s=new Pe(n,t);return be().set(i,s),be().set(n,s),s}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",s).call(this)??await d(e=this.clearThisAndParent(),r,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,N.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,n,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,C.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,T.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,x.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>=(0,x.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>(0,x.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*x.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,J.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,J.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,q.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,F.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,E.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,V.ending)()?1:3,timeoutMs:0,retryDelay:x.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,r,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,r,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,A.newlineRe)(),(r=>{const n=e.exec(r);null!=n&&(t.maybeResolve(n),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,O.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),_e)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,n)=>{try{const s=await e.f(r,(0,k.denull)(n));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*x.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},84542:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),n=i(96249),s=i(51926),o=i(54993),a=i(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),n=i(19851),s=i(50213),o=i(37805),a=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=r(i(76760)),s=r(i(1708)),o=i(19851),a=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44652)),l=o(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),S=i(16287),b=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class E{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new E(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},n=await a.stat(t);return new E(i,new P(r,n))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return E.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new E(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>E.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new E(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=E},20197:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=r(i(76760)),s=i(39926),o=i(29882),a=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(r.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},88561:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(40958),a=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,r,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),n=i(22573),s=i(45599),o=i(96249),a=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),n=i(17217),s=i(16287),o=i(68284);async function a(e){return(0,r.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},73787:function(e,t,i){var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,n.set(this,[]),s.set(this,void 0),o.set(this,void 0),l(this,o,(0,f.fileStatsSync)(e),"f"),l(this,s,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",a).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,n,"f").push(e)}close(){u(this,s,"f").close()}}t.FileWatcher=m,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,o,"f"),t)){l(this,o,t,"f");for(const t of u(this,n,"f"))t(e,this.nativePath)}}},73209:function(e,t,i){var r,n,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w,S=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const _=i(58587),E=P(i(44652)),M=i(87997),x=i(40958),C=i(17586),T=i(42659),D=i(50357),k=i(75240),O=i(55835),F=i(31586),I=i(30976),L=i(13538),A=i(54993),N=i(7282),R=i(68852),j=i(23560),B=i(25764),V=i(38836),z=i(99331),W=i(22781),U=i(38835),q=i(55222),H=i(63870),G=i(69734),J=i(17217),$=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends V.EndableWrapper{static newUid(e=process.pid){return b(this,n,Math.max(Date.now(),S(this,n,"f",s)+1),"f",s),(0,x.compactBlanks)([q.TokenRadix.encode(S(this,n,"f",s)),j.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return n.pidFromBasename((0,J.basename)(e))}static pidFromBasename(e){return(0,F.toInt)($.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return S(this,n,"f",a).find((t=>t.opts.file===e.file))??new n(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>S(this,r,"m",w).call(this)),e.endableRank??B.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=n,n,(i=S(t,n,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(S(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(n.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await S(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+S(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),S(n,n,"f",a).push(this)}get acquired(){return S(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await S(this,r,"m",f).call(this,e)??S(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,C.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==S(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,N.isTest)()?10:T.secondMs);b(this,c,setInterval((()=>S(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=S(this,c,"f")&&(clearInterval(S(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(S(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),b(this,u,!1,"f"),(0,O.map)(S(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?S(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>S(this,r,"m",v).call(this)),(0,F.toGt0)(this.staleMs)??T.secondMs),"f"),S(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(S(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,L.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,n=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>S(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await S(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await S(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+T.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,N.isTest)())return this.release(),!1;n.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=n.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,_.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),S(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await S(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await S(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,x.filterInPlace)(S(n,n,"f",a),(e=>S(e,l,"f")!==S(this,l,"f")))},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),n=i(51926),s=i(54993),o=i(17217);function a(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,n.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,n.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&a((0,o.basename)(e))}},4001:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),n=i(55835),s=i(31586),o=i(51926),a=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,s.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const n=(0,u.parsePosixPath)(i),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,n.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(g.exec(t),(e=>t=e[1].trim())),t}},14977:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=r(i(44652)),s=r(i(73024)),o=i(46466),a=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=r(i(77598)),s=r(i(73024)),o=i(46466),a=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=S().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),S().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const r=n.default.createHash(i);return await(0,o.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),n=i(42659),s=i(55835),o=i(31586),a=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*n.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*n.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),n=i(54993),s=i(7282),o=i(43334),a=i(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),n=i(51926),s=i(54993);class o extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=r.pop();this._prior=o??"";let a=!1;for(const e of r)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=r(i(76760)),s=i(17217),o=i(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},85772:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const o=s(i(76760)),a=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),S=i(88561),b=i(65238),P=i(16287),_=(0,a.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),E="NoMedia",M=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(o.default.sep),"/"]).join("")+"])\\.?"+E+"$","im"),x=Object.freeze(["."+E,E]),C=Object.freeze((0,u.flatten)(x.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function T(e){return null!=M.exec(e)}t.isNoMediaName=T;const D=(0,a.lazy)((()=>new S.FileCache({name:"fs.noMediaDirsCache"})));async function k(e,t){if(null==e)return null;const i=v.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return T(i.base)||await(0,w.isCachedirTagFile)(i)?D().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):k(i.parent());{const e=await D().getOrSetAsync(i.nativePath,(()=>O(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:k(i.parent())}}async function O(e){if(T(e.base))return D().set(e.parent().nativePath,e.nativePath),_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,b.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([F(e.nativePath,i),(0,b.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,w.isCachedirTagDirectory)(e)?_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function F(e,t){for(const i of g.isCaseSensitiveFs?C:x){if(!0===t?.aborted)return null;const r=o.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return _().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(T(r.basename))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,o.join)(e,r.basename))});if(r.basename===w.CACHEDIR_TAG){const t=(0,o.join)(e,r.basename);if(await(0,w.isCachedirTagFile)(t))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await k(e,t)},t.whyNoMedia=k,t.whyNoMediaDir=O,t._dirHasNoMediaChild=F},29882:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=r(i(44652)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),S=i(17217),b=i(16287),P=i(66430),_=i(5545);function E(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=E,t.containsHiddenPathname=function(e){return k(e).some(E)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!E(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return x((0,v.posix2native)(e))},t.extname=function(e){return x(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function x(e){const t=M.exec(e)?.groups,i=t?.ext2??"",r=s.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function C(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function T(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),i=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const r=e(t),n=e(i);return null!=r&&null!=n&&(y.isLinux?r===n:(0,p.equalsIgnoreCase)(r,n))}function k(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&k(e).length===(y.isWin?1:0)}function F({p:e,maxLength:t}){const i=(0,S.toNativePath_)(e);if(i.length<=t)return i;const r=k(e),n=[],s=[r.pop()];for(;r.length>0;)if(n.length=t){r.unshift(n.pop());break}}else if(s.unshift(r.pop()),L([...n,...s]).length>=t){r.push(s.shift());break}return r.length>0&&n.push("…"),L([...n,...s])}function I(e){return e.startsWith("\\\\")}function L(e){return(0,h.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=x,t.parentBasename=C,t.grandParentBasename=function(e){return C(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=T,t.eqlBasename=function(e,t){return D(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(S.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,S.toNativePath_)(e),r=(0,S.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,v.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=F,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const n=[];for(const r of e.slice(0,i))n.push(F({p:r,maxLength:t}));return n.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=x(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=L,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:L(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>T({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=r(i(76760)),s=i(19851),o=i(40958),a=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),S=i(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function E(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(i,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...E()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,o.uniq)((0,o.compactBlanks)([...M(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=n.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){var r,n,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),S=i(22573),b=i(42659),P=i(26905),_=i(75240),E=i(55835),M=i(31586),x=i(68708),C=i(13538),T=i(89937),D=i(12168),k=i(54993),O=i(48884),F=i(50213),I=i(45255),L=i(81168),A=i(56519),N=i(56038),R=i(31562),j=i(84777),B=i(9595),V=i(38835),z=i(70025),W=i(57902),U=i(55222),q=i(43334),H=i(33847),G=i(24399),J=i(28874),$=i(79915),K=i(45200),Y=i(34238),Z=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),ne=i(73209),se=i(48313),oe=i(29882),ae=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,F.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,$.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,ae.toNativePath_)(e),r=new fe(i,t);return(0,L.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,oe.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,oe.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,E.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,E.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,k.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===T.PS_LIBRARY_SCHEME?1:t.scheme===T.PS_LOCAL_FILE_SCHEME?2:t.scheme===T.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,$.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,$.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,E.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,x.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:n,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:o,minSizeBytes:i,timeoutMs:n,dirty:l})}return a&&r?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*n,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,M.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:n,dirty:s=!1}){return await this.parent().mkdirp_(),(0,ne.withLock_)({file:this,skipFsLock:r,timeoutMs:n,dirty:s},(async()=>{const r=this.wip();try{await r.unlink("trace");const s=await(0,C.thenOrTimeoutError)(e(r),n);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==J.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",n).call(this,t)}catch(e){if(!0===(0,z.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();J.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,M.clamp)(I.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,E.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,oe.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,oe.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,n=async function(e){let t,i=e;const r=e.wip();try{const n=await this.stat_();if(null==n)return this.pflog().throw("Can't copy missing files"+V.NonRetriableErrorFlag);if(n.size>0){if(J.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+V.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),n.size>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},n.size,(()=>r.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,M.approximates)(n.size,await r.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:n.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:n.birthtimeMs,mtimeMs:n.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,n.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${n.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,E.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),n=r?.size;return null==r||null==n?this.pflog().throw("Can't copy missing files"):(n>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},n,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+V.DoNotSendErrorFlag,{error:t})}finally{(0,E.map)(t,(e=>e.end()))}}},78133:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=r(i(76760)),s=i(22573),o=i(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const i=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",r=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=r(i(76760)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(n.default.join((0,p.execDir)(),"resources"),n.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,p.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=n.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),n=i(19851),s=i(31586),o=i(50213),a=i(57902),l=i(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),n=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const n=i??(await(0,r.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await(0,r.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,r.close)}}},69428:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},55690:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),n=i(84542);t.readLines_=async function(e){return(0,n.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class n extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=r(i(51455)),s=i(76760),o=i(19851),a=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),S=i(88561),b=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function _(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const E=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||E.prior()?.delete(e)}async function x(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await E().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=C(e),n=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===f.Timeout&&(0,g.onTimeout)({soft:!1}),n!==f.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),E.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!E().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=E().get(e)},t.childDirectories_=async function(e){return(await x(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?x(e):C(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=x,t.readdirCached=function(e){return E().get(e)},t.readdirUncached_=C},53265:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=i(73024),s=r(i(76760)),o=i(40958),a=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=s.default.resolve(t,...e);if((0,n.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},50274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),n=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=r(i(73024)),s=r(i(76760)),o=i(22573),a=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],n=t[i],s=(0,u.diff)(b(r),b(n));if(null==s||s>1)return"unmatched "+i+": "+r+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=r(i(73024)),s=i(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const i=o(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=o(e);return t.emptyIsNew?null==i:a(i)},t.isNonEmptyFileSync=function(e,t=0){const i=o(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),n=i(56409);t.onDataChunked=function(e,t,i){const r=new s(t,i,!0);return r.read(e),r.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=r(i(57075)),s=i(41400),o=i(55835),a=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends n.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=r(i(73024)),s=i(76760),o=i(22573),a=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},27794:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=r(i(44652)),s=i(19851),o=i(22573),a=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},5545:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=r(i(76760)),s=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??n.default.sep)}},70257:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),n=i(45255),s=i(17217);t.WipTimeoutMs=n.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const o=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(o,"")},t.isWip=function(e){return o.test((0,s.basename)(e)??"")}},58722:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),n=i(22911);class s extends r.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},73428:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=r(i(44652)),s=r(i(76760)),o=i(51926),a=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=r(i(73024)),s=i(76760),o=i(46466),a=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const r=[],s=[n.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>r.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},33866:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},52086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},13940:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),n=i(19851),s=i(42659),o=i(59455),a=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),S=(0,n.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,n.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,n.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const n=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const s=n.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+r);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:o}),o}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const n=await P(e,t,i);return await n.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),n}catch(r){return S().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48584:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},49794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),n=i(19851),s=i(40958),o=i(22573),a=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),n=i(23560),s=i(66184),o=i(72210);class a{log(e,t,i,r){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,r.lazy)((()=>new a))},14593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),n=i(22573),s=i(26905),o=i(55835),a=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),n=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof n.LogWriter))}},28981:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),n=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new n.PlaintextLogFormatter))},31256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(41400),a=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,o.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(77030),o=i(19851),a=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),S=(0,o.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,a.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const o=this.socket;null==o?n(this,r,"f").call(this):o.write(this.logFormatter.format(e,t,i,s)+b)}catch(r){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),n=i(42659),s=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},4904:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),n=i(31586),s=i(51926),o=i(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),n=i(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,n.set(this,[]),s.set(this,(0,l.lazy)((()=>{a(this,n,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:a(this,n,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>a(this,s,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=a(this,r,"m",o).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=a(this,r,"m",o).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap,s=new WeakMap,r=new WeakSet,o=function(e){if(null==e||0===a(this,n,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return a(this,n,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),n=i(50989),s=i(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),n=i(68708),s=i(20214),o=i(51926),a=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,o.isString)(i)||Buffer.isBuffer(i))return(0,o.ellipsize)(i.toString(),256,32);if((0,a.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const a=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(i),(0,n.keys)(a));return(0,r.isNotEmpty)(c)&&(a["…"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return i}},89241:function(e,t,i){var r,n,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),h=i(38522),f=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),v=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),n.set(this,!1),s.set(this,!1),o.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,o,!0,"f")})),this.stream.on("data",c(this,r,"m",a).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,n,!0,"f")})),this.stream.on("end",(()=>{u(this,n,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,o,"f"),ended:c(this,n,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,o,"f")}get ended(){return c(this,n,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e){if(null===e)u(this,n,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},24068:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),n=i(76760),s=i(1708),o=i(87997),a=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),S=i(38836),b=i(99331),P=i(42638),_=i(76596),E=i(98314),M=i(89968),x=i(29882),C=i(28874),T=i(28981),D=i(20839),k=i(21727),O=i(66184),F=i(57902),I=i(72210),L=i(98192);function A(e){const t=(0,T.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class N extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,C.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,x.mkdirp_)(e),this.root=await M.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),D.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(F.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,n.join)(e,i))}))}catch(t){return void(0,O.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,E.errorToS)(t))))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,_.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,k.datedLogDir)(this.root.nativePath);try{await(0,x.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,E.errorToS)(e))))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await M.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,L.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,E.errorToS)(e))))}}))}}t.LogTail=N,N.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new N))},72210:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),n=i(82328),s=i(28981),o=i(20839),a=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),S=i(23560),b=i(81168),P=i(78406),_=i(25764),E=i(20197),M=i(14977),x=i(36868),C=i(28874),T=i(32105),D=i(20839),k=i(21727),O=i(66184),F=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*D.DefaultLogFlushMs),rank:_.EndableRanks.logger,unref:!0,onEnd:()=>c(this,n,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:T.ConsoleLogger.instance(),flushEveryMs:D.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const n={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(n.meta=(0,F.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,n=new WeakMap,r=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,i);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,r,"m",o).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,E.ensureNewNativePath_)({nativePath:(0,f.join)((0,k.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",a).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,x.endStream)(e.stream),C.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,M.gzip_)(e.nativePath))}catch(e){c(this,r,"m",o).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),n=i(40958),s=i(55835),o=i(68708),a=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),n=i(84542),s=i(4001),o=i(13047),a=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),r=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,n.splitLines)(a)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),n=i(76790),s=i(68708),o=i(89788),a=i(57902);t.SentLogLevels=(0,r.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),n=i(41400),s=i(55835),o=i(37975),a=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),S=i(24068),b=i(43705),P=i(51879);function _(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),E();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new b.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,s.map)((0,y.logBroadcaster)(),(e=>i.push(e))),a.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&S.LogTail.instance()}function E(){const e=h.Settings.logColor.valueOrDefault;(0,o.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=_,t.setupLogFormatter=E,(0,n.later)((()=>{h.Settings.logStdout.watchLater(_),h.Settings.logDir.watchLater(_),h.Settings.tailLogs.watchLater(_),h.Settings.logColor.watchLater(E),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},75631:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Recent=void 0;const n=r(i(1708)),s=i(57075),o=i(40958),a=i(76790),l=i(42659),u=i(41400),c=i(96249),d=i(55835),h=i(31586),f=i(34666),m=i(5670),p=i(45608),g=i(56519),y=i(69554),v=i(38790),w=i(70488),S=i(83278),b=i(84542),P=i(89968),_=i(14977),E=i(33456),M=i(28981),x=i(4904),C=i(89241),T=i(98192),D=i(97352),k=i(28874),O=i(2858);let F;function I(e){n.default.stdout.write(e+b.Newline)}async function L(e){const t=S.BaseFile.for(e);if(await t.isFile())return[t.nativePath];if(await t.isDirectory()){const e=await t.descendants((e=>e.ext.startsWith(".log")));return e?.map((e=>e.nativePath))}}t.Recent={beforeParse:e=>e.option("--recent [duration]",'Automatically cat recent logs. The optional "duration" argument can either be a number, which will be interpreted in minutes, or an ISO 8601 duration string, like "1d" for 1 day, or "20m" for 20 minutes. Defaults to 1 day.'),afterParse:e=>{null!=e.recent&&(!0===e.recent?F=l.dayMs:(0,D.mapGt0)(e.recent,(e=>F=e*l.minuteMs))??(0,w.decodeDuration)(e.recent))}},async function(){const e=await new y.CLI(m.ServiceNames.logcat,"[FILE_OR_DIR...]","FILE_OR_DIR may be either a logfile or a directory that will be scanned for .log, .log.gz, and .log.bz files.").add(t.Recent,v.ColorArgs).parse();n.default.on("SIGINT",(()=>(0,p.exit)({reason:"SIGINT",status:0}))),n.default.on("SIGTERM",(()=>(0,p.exit)({reason:"SIGTERM",status:0})));const i=(0,o.uniq)((0,c.flatten)(await(0,g.mapAsync)({name:"parseArgs",arr:e.args,f:L})));if((0,h.gt0)(F)){const e=(0,_.matcherForExtOrCompressedExt)(".log");await(0,O.readSystemSettings)();const t=Date.now()-F;await S.BaseFile.for(k.Settings.logDir.valueOrDefault).visitDescendants((async r=>{const n=await r.maxStatMs();e(r.ext)&&await r.isFile()&&(0,f.gt)(n,t)&&i.push(r.nativePath)}))}const r=(0,M.DefaultLogFormatter)();if((0,o.isEmpty)(i))return(0,o.isNotEmpty)(e.args)&&(console.error(r.format("error","logcat","No valid logfiles were provided.")),e.help()),I(r.format("info","logcat","No log files provided: reading from stdin.")),I(r.format("warn","logcat","The output will not be sorted chronologically.")),void await s.promises.pipeline(n.default.stdin,new E.LineReader,new s.Transform({transform(e,t,i){(0,d.map)((0,T.chunkToLogEntry)(e),(e=>I(r.formatLogEntry({from:"",...e})))),i()}}));const l=await(0,g.thenCompact)(i.map((async e=>{const t=await P.DirectoryEntry.for(e);return null!=t&&(0,h.gt0)(t.size())?new C.LogReader(t,console.error):void 0})));function w(){let e;(0,o.filterInPlace)(l,(e=>!e.complete()));for(const t of l){if(!t.ready())return;const i=t.peek();null!=i?.ts&&(null==e||i.tse.f.nativePath))));l.length>0;)try{const e=w();if(null!=e)for(const t of e)I(r.formatLogEntry(t));else await(0,u.delay)(10,!1)}catch(e){console.error("caught error",e)}n.default.stdout.write(b.Newline,(()=>(0,p.exit)({reason:"",status:0})))}()},82647:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(57975),a=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,r,"m",n).call(this,-1)}get p29(){return s(this,r,"m",n).call(this,-.5)}get p38(){return s(this,r,"m",n).call(this,-.25)}get p69(){return s(this,r,"m",n).call(this,.5)}get p84(){return s(this,r,"m",n).call(this,1)}get p98(){return s(this,r,"m",n).call(this,2)}get p99(){return s(this,r,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),n=i(55835),s=i(31586),o=i(30976),a=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,n.map2)(e,t,((e,t)=>(0,r.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):r[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let n=0;n(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},55222:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),n=i(22573),s=i(55835),o=i(32639),a=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),n=this.normalizeToken(t);return r.length>=i&&r===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},17921:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),n=i(65713);function s(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,n.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,r,"f")/(s(this,r,"f")+1)+e/(s(this,r,"f")+1),"f"),o(this,r,(t=s(this,r,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,u.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),n=v(t,(e=>(e-i)**2));return 0===n?0:r/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},49076:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const n=r(i(48161)),s=i(19851),o=i(22573),a=i(41400),l=i(81168),u=i(28874);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??n.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??n.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},96128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),n=i(19851),s=i(22573),o=i(42659),a=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),S=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==S.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=b.exec(e)}function _(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=_,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=_(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void E().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const E=(0,n.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=_(e)?r.promises.reverse(e):r.promises.resolve4(e),5*o.secondMs);if(t===c.Timeout)return E().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(E().warn("No name found for "+e),e):i}catch(t){return E().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),n=i(42659),s=i(31586),o=i(97790),a=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*n.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs})},45969:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),n=i(38639),s=i(19851),o=i(59958),a=i(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),n=i(19851),s=i(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},43334:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=r(i(48161)),s=r(i(1708)),o=i(22573),a=i(38639),l=i(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=r(i(73024)),s=i(19851),o=i(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),n=i(59455),s=i(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),S=i(54993),b=i(54557),P=i(19851),_=i(50213),E=i(88158),M=i(409),x=i(78406),C=i(25764),T=i(99331),D=i(56519),k=i(46292),O=i(8769),F=i(83278),I=i(32144),L=i(29882),A=i(43334),N=i(24399),R=i(58261),j=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),B=10*p.secondMs;function V(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,L.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??A.isWin,r=await this.pidfiles(),n=await this.pids(r??[]);if((0,f.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,R.pidInfos)(n);if(null!=a){for(const n of r){const r=await n.readJson();if(null==r){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:r,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!V(r,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:r,pidEntry:u}),await n.unlink("debug"),s.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:r}),o.push(W(l,i,!1)),s.push({...r,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(i&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const i=a(this,r,"m",s).call(this,e.pid),n=(0,v.opt)((0,E.Try)((()=>(0,L.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await i.writeJson_(l),j().debug("addPid() wrote "+i,l),i}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,r,"m",s).call(this,e);return(0,D.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new x.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:C.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=U,n=new WeakMap,o=new WeakMap,r=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,k.configDir)(),(e=>new U(F.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=i(31421),s=i(48161),o=r(i(1708)),a=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),S=i(56519),b=i(84777),P=i(8103),_=i(45879),E=i(43334),M=i(24399),x=i(45643),C=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function T(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){if(E.isLinux)return async function(e){const t=[];for(const i of e)t.push(z(await(0,_.readFileMaybe)("/proc/"+i+"/stat")));return C().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,x.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,E.isWin?I:R)).filter((e=>T(e)&&t.includes(e.pid)));return C().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=T,t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,x.existingPids)(e),(t=>{const i=[o.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=D;const k="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return N(e);const t=[k,"-Id",F(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const L={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function N(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,L),r=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===o.default.pid))||r.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),r}async function R(e){return t=(await(0,b.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...L,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=N;const j=(0,g.lazy)((()=>{try{if(E.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){C().warn("clk_tck failed",{error:e})}return 100})),B=(0,g.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),V=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function z(e){const t=V.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(n)?{pid:i,cmd:r,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),n=i(22573),s=i(31586),o=i(29882),a=i(97352);t.progressEvtToS=function(e){const t=(0,n.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,n.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},41944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),n=i(42659),s=i(31586),o=i(12089),a=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new a.TTLMap(15*n.secondMs))),t.recentDone=(0,r.lazy)((()=>new a.TTLMap(2*n.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),n=i(31586),s=i(409),o=i(78406),a=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends o.EndableInterval{constructor(e,t,i,n=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:n,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=n,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,n.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,n.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},24399:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),n=i(19851),s=i(22573),o=i(42659),a=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),S=i(31562),b=i(84777),P=i(34102),_=i(43334),E=i(28874),M=i(63870),x="{ready}",C=" | ConvertTo-Json -Compress";function T(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=T,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",E.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${x}"}`,...(0,s.mapNotBlankOr)(E.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:x,fail:"Error",exitCommand:"exit",maxProcs:E.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),E.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(E.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,C),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,n)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,n)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,C),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+T(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,n.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),n=i(38639),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),n=i(31586),s=i(97790),o=i(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(97790),o=i(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(r.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),n=i(22573),s=i(45599),o=i(50213),a=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,n.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),n=i(91655),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},4175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),n=i(22573),s=i(38639),o=i(42659),a=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){_(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&E()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,n.blank)(m.Settings.assetPathnameFormat.value)&&(0,n.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*o.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const S=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],b={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function _(e){for(const t of S)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:b;for(const[e,i]of(0,a.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function E(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=_,t.disableExternalNetworkRequests=E},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),n=i(53265),s=i(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class n extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),n=i(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=i(19851),a=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),S=i(44198),b=i(96706),P=i(34102),_=i(28283),E=i(81075),M=i(98778),x=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,r,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?s(this,r,"m",n).call(this,e??t)+": "+i:null==this.fromEnv(e)?s(this,r,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return E.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,S.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&b.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,S.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&b.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],x.WrapComments);function i(e,i){(0,a.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],x.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+r],x.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:x.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:x.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),n=i(51168),s=i(76760),o=i(19851),a=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),S=i(7282),b=i(12801),P=i(4328),_=i(70488),E=i(84248),M=i(5531),x=i(99315),C=i(34365),T=i(34580),D=i(96706),k=i(50274),O=i(33866),F=i(52086),I=i(48584),L=i(45969),A=i(43334),N=i(24540),R=i(70379),j=i(71300),B=i(33209),V=i(48987),z=i(68268),W=i(61208),U=i(99023),q=i(30577),H=i(1485),G=i(19861),J=i(55111),$=i(30933),K=i(22859),Y=i(71988),Z=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),ne=i(57039),se=i(9945),oe=i(74589),ae=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new oe.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>H.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:H.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>H.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,L.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:J.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:E.AutoVacuumModes,defaultValue:E.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:C.SynchronousModes,defaultValue:C.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:x.RepairModes,defaultValue:x.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,L.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:q.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,T.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,N.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,$.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:k.SidecarExts,defaultValue:k.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,$.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:F.CropStrategies.attention,strEnum:F.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>V.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:R.DateTagFormats.ym,strEnum:R.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,L.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function be(e){const i=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,L.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,D.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),n=i(31586),s=i(7282),o=i(49776),a=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(22573),a=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),S=i(81168),b=i(83556),P=i(87290),_=i(98314),E=i(34102),M=i(83278),x=i(95696),C=i(60865),T=i(4175),D=i(83179),k=i(81075),O=i(28874),F=i(41692),I=i(84438),L=i(32707),A=i(6707),N=i(98778),R=i(55018),j=i(10357),B=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function V(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function z(e=(0,L.systemSettingsFile)()){if(null!=e)return X(M.BaseFile.for(e))}async function W(){try{return(0,o.toNotBlank)((await(0,A.readTomlFile_)((0,L.systemSettingsFile)()))?.[O.Settings.libraryDir.name])}catch{return}}function U(e){return(0,A.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function q(){return U((0,L.systemSettingsFile)())}function H(e){return U(V(e))}function G(){t.libraryHasSettings.refresh()}function J(e){const t=V(e);return B().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:O.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function $(e,i){if(null==e)return void B().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),n=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,N.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let n="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,E.ee)().emitDebounced("settingsChanged")}(n,i),B().info("writeToml(): wrote settings",{dest:n,file:e,nonDefaults:(0,D.settingsToObj)(i),wip:r}),r){const t=await(0,A.readTomlFile_)(n),i=await(0,A.readTomlFile_)(e);(0,u.eql)(t,i)?(B().info("Equivalent contents",{dest:n,file:e,a:t,b:i}),await n.unlink()):(B().info("Archiving prior, different contents",{dest:n,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await n.unwip_())}}async function K(e=(0,L.systemSettingsFile)()){const t=x.PosixFile.forMaybe(e);return null!=t&&await $(t,(0,O.persistedSystemSettings)()),t}function Y(e){return X(V(e))}async function Z(e){await(0,P.setupLibraryDataDir_)((0,o.firstNotBlank)(e,O.Settings.libraryDir.value));const i=V(e);return B().info("writeLibrarySettings()",{file:i}),null!=i&&(await $(i,(0,O.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=B().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,n.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function Q(e){const t=B().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,A.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const s=[],o=(0,n.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,O.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,O.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;s.push(e)}})));return t.info("loaded",{settings:(0,D.settingsToObj)(o),warnings:(0,n.toNotEmpty)(s)}),await(0,T.handleDeprecatedSettings)(),(0,T.handleMetaSettings)(o),{settings:o,warnings:s}}t.librarySettingsFile=V,t.readSettings=(0,r.lazy)((async()=>{await z(),(0,t.libraryHasSettings)()&&await Y()}),a.minuteMs),t.readSystemSettings=z,t.envOrSavedLibraryDir=async function(){return O.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=q,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await q()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await H()&&await Z()},t.libraryHasSettings=(0,r.lazy)((()=>J())),t.libraryHasSettings.unset=()=>{B().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,E.ee)().on("clearCache",G),(0,E.ee)().on("settingsChanged",G),O.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=J,t.versionForSettings=(0,r.lazy)((()=>(0,C.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return $(x.PosixFile.for(e),(0,O.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=Z,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([O.Settings.noNetwork,O.Settings.httpPort,O.Settings.license,O.Settings.logStdout,O.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(O.Settings))ee().has(e.key)||e.unset();(0,E.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,j.WrapComments))))}t.clearLibraryDirSetting=async function(){await z(),O.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(x.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(x.PosixFile.forMaybe(V())?.unlink("trace")),(0,E.ee)().emit("clearCache"),F.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${(0,C.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...k.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...k.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,o={...e.addToJSON()};(0,n.mapNotEmpty)(e.altKeys,(e=>o.aliases=(0,h.orList)(e)));const a=(0,p.entries)(o).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,R.valueToS)(t)}`));(0,n.isNotEmpty)(a)&&a.push(""),i.push(...ie((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...a,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),n=i(40958),s=i(22573),o=i(98553),a=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function h(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class n extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),n=i(98553),s=i(55835),o=i(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,n=e.strEnum,(0,r.compact)((0,o.splitStringArray)(i)?.map((e=>n.getCI(e))));var i,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),n=i(81168),s=i(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),n=i(55835),s=i(46292),o=i(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,r.join)(e,o.SettingsToml)))}},80496:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),n=i(44652),s=i(22573),o=i(76850),a=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),n=i(96249),s=i(98553),o=i(68708),a=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[n]:(0,a.wrap)(n.split("\n"),i)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},65162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),n=i(81168);t.bname=function(e,t=!0){let i=(0,n.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,n.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},70379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},88840:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),n=i(40958),s=i(96249),o=i(23838),a=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,a.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},68268:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},61208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},79915:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),n=i(40958),s=i(22573),o=i(81168),a=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isJsonExt)(i.ext),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,n.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,n.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return a&&function(e,i){const r=(0,o.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function n(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=n(e.slice(r.length)),l=n(i.slice(r.length));return a&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},45200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(96249),a=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,n.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,n.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),n=i(57975),s=i(90595),o=i(22573),a=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,n,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=n??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return M(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:n,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===n?n=this.query:null===n&&(n=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&r===this.path&&n===this.query&&s===this.fragment?this:new b(t,i,r,n,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const r=i[2]||g,n=D(i[4]||g),s=(i[5]||g).split("/").map(D).join("/"),o="psfile"===r&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=D(i[9]||g);return new b(r,n,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(M(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return x(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=M(this,!1)),this._fsPath}toString(e=!1){return e?x(this,!0):(null==this._formatted&&(this._formatted=x(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,r=-1;for(let n=0;n=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),void 0!==i&&(i+=e.charAt(n));else{void 0===i&&(i=e.substr(0,n));const t=P[s];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),i+=t):-1===r&&(r=n)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function E(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function x(e,t){const i=t?E:_;let r="";const{scheme:n,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(n&&(r+=n,r+=":"),(l||"file"===n)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>r+="?"+e)),a&&(r+="#",r+=t?a:_(a,!1)),r}function C(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+C(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=M;const T=/(?:%[\dA-Z][\dA-Z])+/gi;function D(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(T)?e.replace(T,(e=>C(e))):e}t.percentDecode=D,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),n=i(40958),s=i(50357),o=i(89937),a=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,n.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),n=i(22573),s=i(51926),o=i(89937),a=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,n.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,n.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,n.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,s=(0,n.notBlank)(t)&&!t.includes(i);if(s&&!(0,n.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,n.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),n=i(22573),s=i(51926),o=i(89937),a=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,n.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,n.blank)(t))return;const i=(0,r.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(76760)),a=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,a.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const n=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...n);return await(0,h.isReadableDirectory)(t)?o.join(t,...n):void 0}},85087:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),n=i(42659),s=i(9103),o=i(37628);t.volsha=(0,s.memoize)((e=>(0,r.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:n.minuteMs})},60865:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),n=i(30577);t.channel=function(){return(0,n.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),n=i(22573),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof r.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const s=o(e);return null!=s&&(0,r.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),n=i(9595),s=i(29882),o=i(43334),a=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,n.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},1485:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),n=i(22573),s=i(59455),o=i(50213),a=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),n=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||r||n);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:n}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,n.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,n.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const n=m(e.Used)??0,s=m(e.Available)??0;if(0!==n||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?n+s:r,used:n,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:n,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,n.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(22573),a=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),S=i(24541),b=i(60224),P=i(63870),_=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const E=/([a-z]+)(?::\\)?/i;function M(e){return e?.match(E)?.[1]?.toUpperCase()}function x(e){return(0,l.map)(M(e),(e=>e+":\\"))}function C(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(M(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function T(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function D(e){return`Get-Volume ${(0,f.toS)(M(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=x,t.getPsDriveCommand=C,t.getVolumeCommand=D,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(D())};const k=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function F(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=x(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,n.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(k.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var s}async function I(){const e=(0,n.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(x)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(C(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,n.compact)((0,a.flatten)(t).map(T)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,n.compact)((0,a.flatten)(r).map(F)),l=(0,n.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,n.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=F,t.volumeInfoWin=I},68884:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(42659),a=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),S=i(16287),b=i(45969),P=i(43334),_=i(69108),E=i(98770),M=i(44224),x=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,x.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const C=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?C().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,M.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):C().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,n.isEmpty)(e)?[]:(C().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,x.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void C().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await T(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,x.mountpointsTtlMs)()}))),(0,a.later)((()=>(0,E.setupVolumeTTL)(t.gioVolumes)));const T=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,x.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void C().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},98770:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),n=i(5233),s=i(41400),o=i(56038),a=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,n.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),S=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const s=(0,c.sortIgnoreCase)((0,n.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const n=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...n,...s},u=r?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:n,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),_=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),r=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),n=i(19851),s=i(40958),o=i(22573),a=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,n.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),n=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of n)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(42659),a=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),S=i(8769),b=i(34102),P=i(17217),_=i(16287),E=i(43334),M=i(28874),x=i(8540),C=i(68884),T=i(44224),D=i(24541),k=i(69375),O=i(63870),F=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,O.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function A(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{M.Settings.libraryDir.watchLater(I),M.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&M.Settings.scanAllDrives.valueOrDefault?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,O.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux){const i=(0,T.maybeWatchProcMounts)();await(0,C.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,O.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await R()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,O.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),o.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=M.Settings.mountpoints.values;if((0,n.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?D.mountpointsWin:T.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,n.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,O.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,k.isExcludedMountpoint)(e)||M.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,a.later)((()=>{(0,b.ee)().on("clearCache",(()=>{C.gioVolumes.unset(),I()})),M.Settings.mountpointsTtlMs.watch(L)}),(0,c.isTest)()?1:o.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>A(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:C.GioCommand,args:C.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(C.gioVolumes.unset(),A()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const R=(0,r.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,O.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>A(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),n=i(40958),s=i(42659),o=i(48884),a=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),S=i(68884),b=i(59107),P=i(69375),_=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await C()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,S.isGioSupported)())try{await(0,c.thenMap)((0,S.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){_().warn("Failed to fetch gio volumes",e)}return e};const E="/proc/mounts";function M(e){return!v.Settings.excludedFilesystemTypes.has(e)}function x(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function C(e=E,t=M,i=x){if(y.isLinux)try{const r=await(0,f.readLines_)(e),s=(0,n.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),a=await(0,c.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,r])=>{const n=t(e),s=await i(r);return _().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:n&&s,meta:{fs:e,mp:r,fsOK:n,mpOK:s}})}});return _().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void _().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=C,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(E)?new h.FileWatcher(E,{recursive:!1,persistent:!1},(()=>{_().info("detected change in "+E),(0,d.setUnrefTimeout)((()=>b.mountpoints.refresh()),s.secondMs)})):void 0))},24541:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),n=i(42659),s=i(13538),o=i(50213),a=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*n.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),n=i(22573),s=i(50213),o=i(9103),a=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),n=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,r.blank)(e))return;const i=n.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},60224:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),n=i(22573),s=i(42659),o=i(55835),a=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await M()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,n.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,n.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(n.notBlank).getOrElse((()=>"/"))}))))).get()}async function E(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,u.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=E;const M=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?E():(0,r.compact)(e.filter((e=>(0,n.notBlank)(e.LocalName))).map((e=>(0,o.map)(_(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),n=i(12168),s=i(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/r.secondMs},86848:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(38639),a=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),S=i(28874),b=i(59107),P=i(63870),_=i(68995),E=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,n.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function x(e){return(0,o.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function C(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function T(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=C(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function D(e){if(S.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of S.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),r=await T(i).catch((e=>E().info("Failed to read "+i,{error:e})));if(null!=r)return E().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,_.volumeUuidSubpath)());if("/"===e.mountpoint)return E().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(S.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return E().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(S.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,_.writeVolumeUuid)(e);if(!(0,s.blank)(t))return E().tap({msg:"readVolumeUUID(): wrote new "+(0,_.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return E().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),b.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(x(e))return;if((0,o.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>D(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>E().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=x,t.toVolumeUUID=C,t.readUuidFile_=T,t.readVolumeUUID=D},7014:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const n=r(i(48161)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),S=i(50213),b=i(7282),P=i(23560),_=i(28850),E=i(45255),M=i(81168),x=i(56519),C=i(4867),T=i(49776),D=i(9595),k=i(77740),O=i(44198),F=i(96706),I=i(8769),L=i(57159),A=(i(34102),i(21144)),N=i(73209),R=i(29882),j=i(95696),B=i(17217),V=i(16287),z=i(49076),W=i(96128),U=i(45969),q=i(43334),H=i(28874),G=i(85087),J=i(50424),$=i(48165),K=i(98770),Y=i(27461),Z=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,o.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=n.default.platform(),se=new Map,oe=new Map,ae=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,se),le((0,G.volsha)(e.uuid),e,ae),e}function ce(){return(0,a.compact)([j.PosixFile.forMaybe((0,T.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,D.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),se.clear(),ae.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,M.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),n=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,z.cleanHostname)()},updatedAt:r,os:ne}))),s=new Map;for(const e of n)for(const t of(0,a.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))s.set(t,e);const o=ce();for(const e of o)await(0,N.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:n.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),n=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:n,priorIsMissingMountpoints:s}),n||s?void 0:e}async function me(e,i){const r=(0,m.map)(e,B.toNativePath_);if((0,u.blank)(r))return;const n=await(0,A.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,R.bestMountpointForDir)(n,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:n,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:n}})}async function pe(e,t,i){const r=i.filter((e=>(0,M.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(r))return;const n=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,M.equalsIgnoreCase)(e,t.remoteHost)));if(null!=n)return n;const s=await(0,W.friendlyname)(e);return(0,x.asyncFind)(r,(async e=>(0,M.equalsIgnoreCase)(s,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,P.isSyncService)()||(0,b.isTest)())),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await de()),t=(0,v.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,a.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,C.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,C.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,a.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if((0,b.isTest)()){const e=(0,p.toInt)((0,O.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,k.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,C.thenOrTimeoutError)({p:q.isWin?(0,$.dfWin)():(0,J.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,C.thenOrTimeoutError)({p:q.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,Z.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,o.lazy)((()=>q.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,M.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,R.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return ae.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(50213),a=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const n=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(n))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},65713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),n=i(19851),s=i(23838),o=i(81168),a=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,n.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,n.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,n.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=n)return n}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),n=i(96249),s=i(23838),o=i(59455),a=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,n.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},30933:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=r(i(48161)),s=i(19851),o=i(42659),a=i(31586),l=i(50213),u=i(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=r(i(48161)),s=i(19851),o=i(31586),a=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},15674:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),n=i(42659),s=i(41400),o=i(31586),a=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,r.lazy)((()=>{const e=(0,o.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*a.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=w();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,o.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),n=i(87997),s=i(19851),o=i(42659),a=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new r.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,n.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),n=i(22573),s=i(50357),o=i(98553),a=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,a.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const n=[];if(et;s-=i)n.push(r(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),n=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const n of t){const t=i(n);r.includes(t)||(e.push(n),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const n=new Set(i.map(r));return e.filter((e=>!n.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),n=i(36783),s=i(41801),o=i(98553),a=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,a.getOrSet)(i,(0,o.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},5233:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),n=i(31586),s=i(13538),o=i(41583);t.retryOnReject_=async function(e,t){const i=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},22573:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),n=i(42279),s=i(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),n=i(22573),s=i(30301),o=i(55835),a=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),n=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,n,r)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,n.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/r.ms);e-=s*r.ms,s>0&&(r.ms>=t.dayMs?i:n).push(s+r.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),n=i(73872);function s(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function o(e,t,i,r){if(null==i||y(e)||y(t))return;let n=i.get(e);null!=n?n.set(t,r):(n=new WeakMap,n.set(t,r),i.set(e,n))}function a(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const n=l(e,t);return null!==n?n:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return o(e,t,u,i),i;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],n=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(r.sort(),n.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let n=-1;for(;++n{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const n=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return n.prior=()=>t,n.hasPrior=()=>r,n}},41400:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),n=i(35556),s=i(31586),o=i(68708);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=n.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return n.isBrowser||t<=r.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},50357:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),n=i(68708),s=i(34666),o=i(32639);function a(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const i of(0,n.keys)(e))if(!a(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(31586),a=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,s.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},96249:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),n=i(42659),s=i(55835),o=i(31586),a=i(12168),l=[{ms:n.yearMs,s:"year",p:"years"},{ms:n.yearMs/12,s:"month",p:"months"},{ms:n.weekMs,s:"week",p:"weeks"},{ms:n.dayMs,s:"day",p:"days"},{ms:n.hourMs,s:"hour",p:"hours"},{ms:n.minuteMs,s:"minute",p:"minutes"},{ms:n.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,n){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(n,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function n(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},73722:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const n=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,n){if((0,isFunction_1.isFunction)(r))return;let s,o,a,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),n=i(50357),s=i(31586),o=i(65812);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const s=await e,a=await i;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),n=i(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return a(o(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),n=i(76790),s=i(50357),o=i(98553),a=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,s.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),n=null==i?[]:e(t,i);(0,r.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,n]of this.store.entries()){const s=(0,r.findIndexes)(n,(t=>!e(i,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,n.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),n=i(22573),s=i(42279),o=i(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>a(t)&&a(i)&&e(t,i);function f(e,i,n){return!(null==n||!a(n))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,n)&&(0,t.gte)(i,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function E(e,t,i){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return a(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)a(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,i){return b(e,(e=>b(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return a(e)?t(e):i},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!a(i))return;t+=i}return t}},68708:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(32639),a=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,n.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const n={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))n[e]=S(...i.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,n]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==n&&!0!==i?.assignNullish||(e[r]=n));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,s.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function n(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:S(i,t)}for(const r of i){const[i,o]=(0,c.splitFirst)(r,"."),a=b(t,i);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&n(r,e(t[r],...i));return r},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const n=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(n)?void 0:{key:n[0].key,value:(0,r.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(i,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,o.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>r(this.a,e,t,i)))))))}}function n(e){return e instanceof r||e===t.None}function s(e){return n(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=n,t.opt=s},39926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),n=i(54993),s={};function o(e,t){if(t<1)return"";if(!(0,r.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),n=i(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,s=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==s&&"symbol"!==s)){const r=(0,n.toS)(e),s=(0,n.toS)(i),o=r.localeCompare(s);return r[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==s?a.indexOf(r)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const n of(0,r.toA)(await e))if(null!=n){const e=await n;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),n=i(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return null==i||0===i.length?s(e,t):a(e,t,1,i)[0]}function a(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(r??[]);if(t===e&&0===n&&0===o.size&&1===i)return[e];const a=n-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of a(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},5670:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),n=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),r=o(t);return null==i||null==r?void 0:i>r?1:i{const i=o(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),n=i(17586),s=i(22573),o=i(96249),a=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,a.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),n=(0,c.toS)(t);return r.length===n.length&&(r===n||r.toLowerCase()===n.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const r=i?.maxLineLen??80,n=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),n).trim()).length<=r)return[t];const s=S(t," ",r);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),i)];{const r=t.indexOf(" ",n.length+1);return r>0&&r{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),n=i(68708),s=i(42279),o=i(83104),a=i(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,i(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,i(t))}catch(e){n&&(n=!1,r(e))}finally{clearTimeout(s)}}))}async function c(e,t,i=!0){const n=await u(e,t,i);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?o.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{r(await i())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),r(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(n)+")");return c(e,n,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,s.tot)(i);const n=await u(e,t,r);return n===o.Timeout?(0,s.tot)(i):n}},42279:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),n=i(22573),s=i(54993);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,n.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,n.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),n=i(30301),s=i(31586),o=i(46891),a=i(50989),l=i(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,s.isNumber)(r)&&(i+=r/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),n=Math.pow(10,3*r),o=d[r];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),n=Math.pow(2,10*r),o=h[r];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},65812:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),n=i(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),n=i(23541),s=i(59455),o=i(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,r.compact)((0,s.toA)(e).map(a))}},54993:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,r.stringify)(e)}}t.toStr=s},90858:e=>{e.exports=require("@iarna/toml")},58587:e=>{e.exports=require("batch-cluster")},6858:e=>{e.exports=require("commander")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},57272:e=>{e.exports=require("plist")},90595:e=>{e.exports=require("punycode")},38064:e=>{e.exports=require("semver")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},40610:e=>{e.exports=require("node:dns")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},77030:e=>{e.exports=require("node:net")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},53916:e=>{e.exports=require("node:path/posix")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")},16928:e=>{e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__={},exports;exports=__webpack_exports__,Object.defineProperty(exports,"__esModule",{value:!0}),__webpack_require__(75631),module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={37975:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),n=i(22573),s=i(38639);function o(){return(0,s.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,n.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),n=i(7282),s=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),n=i(36783),s=i(76790),o=i(22573),a=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const n=new Set(t.map(i));return e.filter((e=>n.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function E(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,i){return x(e,t,i).index}function x(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let r=0;re.slice(i,i+t)))}async function T(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let n=0;for(const s of e)(t(s,n++)?i:r).push(s);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=E,t.least=function(e){return E(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=x(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=C,t.collectBatched=function(e,t,i){const n=[];for(const s of C((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(i(s)));return n},t.collectBatchedAsync=async function(e,t,i){const n=[];for(const s of C((0,r.compact)((0,f.toA)(e)),t))n.push(...(0,r.compact)(await i(s)));return n},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await T(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+n;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=i(77988),l=o(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),S=i(99331),b=i(95937),P=i(98314),_=i(38835),E=i(70025),M=i(8769),x=i(43334),C=i(95402),T=i(28874),D=i(63870);class k extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,r,"m",n).call(this)),i,"worker"===e?(0,D.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const o=t;o.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,C.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,i,r)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&C.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,E.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=k,r=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(x.isWin?3:1)*c.minuteMs,maxTasksPerProcess:T.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:T.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:T.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,D.commandTimeoutMs)(),taskTimeoutMillis:T.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,i){var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,r,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,r,"m",a).call(this,0,(e=>{var t,i;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(i=u(this,s,"f"),--i),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const i=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of n)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,r.toS)(e)},t.bufferStartsWith=o},9092:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(40958),a=i(23838),l=s(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,n=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(r=e,n=o)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),n=i(31586),s=i(68708),o=i(54993),a=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,n]of this.m.entries()){const s=e(r);t.fill(s,i,i+n),i+=n}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),n=i(72993),s=i(45969),o=i(43334);t.EditionType=(0,r.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),n=i(55835),s=i(68708);var o=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.omit)(e,...i),(0,s.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,n.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),n=i(19851),s=i(95696);t.examples=(0,n.lazy)((()=>s.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),n=i(65843),s=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,n.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),n=i(40958),s=i(55835),o=i(31586),a=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,i){var r,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(i=l(this,n,"f"),++i),"f"),c.promise):(u(this,r,(o=l(this,r,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(a=l(this,r,"f"),++a),"f"),c}get(e){var t,i;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(r=l(this,a,"f"),++r),"f")})),r.promise}},r=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,r).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,a=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(a,r.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,n.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),n=i(98553);var s=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,n.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,r.readFile)(e)).toString())}},19851:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(57975),a=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,r,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(42659),a=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?E():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,n.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function E(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=E,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),n=i(1708),s=i(45599),o=i(68708),a=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,s.defer)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:n.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,o.pick)(n.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:n.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),n=i(32105),s=i(14593);t.rootLoggers=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},56639:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),n=i(55835),s=i(59455),o=i(48884);function a(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,r.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,n.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),n=i(54557);t.memoize=function(e,t){let i=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,r.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,r.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},7282:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=r(i(1708)),s=i(38639),o=i(54993),a=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(55835),a=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=r&&r>0&&null!=n&&n>0?i(r,n):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(f.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function p(e){return(0,a.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const n=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),n=i(42659),s=i(96249),o=i(55835),a=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,n]of(0,l.entries)(e)){const e=t(r,n);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const n of t)r[n]=i(n,e[n]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let n=0;for(const s of(0,l.keys)(e))if(r[s]=t(s,e[s]),n++,(0,a.gt)(n,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,s.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),n=i(73024),s=i(48161),o=i(19851),a=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,o.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return k();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function _(){return"ubuntu"===(0,t.osDistributionLinux)()}function E(){return"fedora"===(0,t.osDistributionLinux)()}function M(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,n.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=_,t.hasApt=function(){return P()||_()},t.isFedora=E,t.isAlpine=M;const x={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},C={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function T(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),n=t[i];return(0,c.isString)(n)?n:n?.[r]}const D=(0,o.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function k(e=D()){try{return(0,a.mapNotBlankOr)(function(e=D()){return T(e,x)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":T(e,C);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=k,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=D();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(_())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(E())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(M())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},12801:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=r(i(48161)),s=i(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),n=i(56409),s=i(31586),o=i(22911),a=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...r){f=!0,m=Date.now()+(0,s.max_)(t,i);const n=d=new o.Deferred(c);(0,s.gt0)(i)&&n.setTimeout(i);try{n.resolve(await e(...r))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return n.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return p.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),n=i(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(n,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(s(t))}const n=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,r||(r=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,n.toS)(t));return new RegExp(i,t??(r?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=r(i(48161)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),S=i(24399),b=i(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let E=!0;const M=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),E)try{return n.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;E=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=r(i(1708)),s=i(19851),o=i(40958),a=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function n(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=n(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=n(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),n=i(57150),s=i(7282),o=i(23560),a=i(17181);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,a.setupLogger)(),(0,n.logStartup)())}},28850:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const a=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends a.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),n.set(this,void 0),s(this,r,e,"f")}_call(){return(0,l.time)(o(this,r,"f")+(null==o(this,n,"f")?"(local)":"(remote)"),null==o(this,n,"f")?this.impl():o(this,n,"f").call(this))}setShim(e){s(this,n,e,"f")}hasShim(){return null!=o(this,n,"f")}clearShim(){s(this,n,void 0,"f")}}r=new WeakMap,n=new WeakMap},12089:function(e,t,i){var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,o){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",o).call(this,e),(()=>u(this,r,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,r=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=i(76790),o=i(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return n(this,r,"f")[Symbol.iterator]()}get length(){return n(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=n(this,r,"f").length-1;for(;t<=i;){const s=t+Math.floor((i-t)/2),o=this.valueOf(n(this,r,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:i=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...n(this,r,"f")];const o=t=>t<0||t>n(this,r,"f").length-1?null:(i??this.diff)(n(this,r,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return n(this,r,"f").shift()}at(e){return(0,o.at)(n(this,r,"f"),e)}toA(){return[...n(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,r,"f").length-1){const e=[...n(this,r,"f")];return n(this,r,"f").length=0,e}return n(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,r,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),n=i(82328),s=i(84542),o=i(95705),a=i(28874);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),n=i(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(r.stdout)}},71567:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=r(i(1708)),s=i(22573),o=i(98553),a=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);r.write(n+"\n"),(0,a.isWorkerService)()&&null!=i&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(55835),a=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const n=t.indexOf(i,r);return-1===n?0:1+e(t,i,n+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,a.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(r.slice(-n.length),n,i)?r.slice(0,-n.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),n=r.length-(t+i);return n<=0?r:r.slice(0,t).trim()+" …(+"+n+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),n=t.indexOf(r);if(n>=0)return{index:n,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function E(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=E;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(E(e))&&(e=e.slice(1,-1).trim())),e};const x=/^['‘’].*['‘’]$/,C=/^["“”„«»〃].*["“”„«»〃]$/;function T(e,t){const i=D(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,i.push(e.substring(s,n.index)),r.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),x.test(e)||C.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),n=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=T,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,n.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,s.blank)(r))for(const e of r.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>r.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function n(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=r(i(77598)),s=i(73913),o=i(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,r=224){return i.encodeBuffer(a(e,r)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(31586),a=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,n="";for(let s=0;s=r&&(r=i.get(s,o),n=(0,l.substr)(e,s-r+1,r)));return n}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),n=t.normalize();return e!==r||t!==n?y(r,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),n=[];return i.forEach((i=>{const s=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,o.times)(s,(()=>n.push(i)))})),n}function b(e,t,i){const n=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,n))-i((0,l.strslice)(t,n))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,r]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,r,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const E=/[^\da-z]+/gi;function M(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(E,"").toLowerCase()));return b(i,r,(e=>c.RadixAlphaNum.decode(e)))}function x(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const n=(0,o.mapNumericOr)(e.charCodeAt(r),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(r),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=M,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=x,t.paddedPositionalDiff=function(e,t,i=8){return x((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},84885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),n=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,n.sortedKeys)(e))}},75387:function(e,t,i){var r,n,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",n.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){h(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),h(this,a,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const n=t();return null!=n&&this.set(e,n),n}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,n,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,n,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,r,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,r,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,r,"m",n).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,r,"m",n).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,r,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,r,"m",s).call(this),[...this.delegate.keys()]}[(r=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,r,"m",n).call(this,e,t)}},84699:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},94174:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=r(i(48161)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),n=i(55835),s=i(31586),o=i(97790),a=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(i))return;const[o,a,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,r,"f")&&clearTimeout(s(this,r,"f")),o(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,n=new WeakMap},22911:function(e,t,i){var r,n,s,o,a,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),S=i(45599),b=i(26905),P=i(55835),_=i(31586),E=i(68708),M=i(20214),x=i(57153),C=i(85556),T=i(50213),D=i(70025),k=i(95937),O="TIMEOUT",F=(0,S.defer)((()=>(0,T.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,_.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const n=i[r];if(n.isSettled){if(n.name===O)return void F().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield n.value}}if(i.every((e=>e.name===O)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,x.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=n,n,(y=p(i,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,T.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,E.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new C.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===x.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==x.PromiseStates.pending}get isResolved(){return p(this,a,"f")===x.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===x.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,a,x.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,x.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,n=I,m=function(e){if(p(this,a,"f")===x.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},27395:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),n=i(40958),s=i(42659),o=i(23838),a=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,a.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,n.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,n.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",o).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,o){this.endTimeoutMs=o,r.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){o(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,n=new WeakMap},99331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,r.isTest)()?e:e||n}},45608:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=r(i(1708)),s=i(22573),o=i(45599),a=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},5916:function(e,t,i){var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new S(e,t,i,r)};class S extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,r,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,a,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(i=c(this,s,"f"),++i),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},1728:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),n=i(80049);t.memoizeAsync=function(e,t){let i=0;const s=new n.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,r.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},22781:function(e,t,i){var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),n.set(this,!1),s.set(this,!1)}_call(){return o(this,n,"f")?(a(this,s,!0,"f"),!0===this.undefinedIfBusy?void 0:o(this,r,"f")):(a(this,n,!0,"f"),a(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{a(this,n,!1,"f"),!0===this.runLaterIfBusy&&o(this,s,"f")&&(a(this,s,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return o(this,n,"f")}prior(){return o(this,r,"f")}async force(){return await o(this,r,"f"),this._call()}}r=new WeakMap,n=new WeakMap,s=new WeakMap},37461:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),n=i(76790),s=i(38639),o=i(42659),a=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var S=i(20214);async function b(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:n}){const s=[];for(const o of(0,r.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(i(o),n):i(o));null!=e&&s.push([e,o])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,r.compact)(await e);if((0,r.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(i,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(i,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,i){const r=[];for(const n of(0,p.batches)((0,f.toA)(await e),t)){const e=await b(n);r.push(...await b(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await E({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,n=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(n??r)}catch{}if(null!=n)throw n;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const n=await t;return null!=n?i(r,n):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const n=await t(r);return null==n?i():n},t.thenMap2Or=async function(e,t,i,r){const n=await e;if(null==n)return r();const s=await t;if(null==s)return r();const o=await i(n,s);return null==o?r():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await E({name:e,arr:t,f:i});return(0,n.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(42659),a=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),S=i(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-r;return i?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function E(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),r=t();return E(e,Date.now()-i),r},t.pushTime=E,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>_(e,t)),i)}},42638:function(e,t,i){var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),S=i(82647),b=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:n}){const s=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const n=new P.Deferred(e,{payload:i,serialId:r});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},4867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),n=i(34546),s=i(41400),o=i(31586),a=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let a=!0;return Promise.race((0,r.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),n=i(42659),s=i(41400),o=i(32639),a=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=r(i(1708)),s=i(45599),o=i(41400),a=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),S=i(88158),b=i(45969),P=i(43334),_=i(28874),E=i(3790);function M(e){return x().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const x=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const C=["HOME","LANG","USER"],T=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],D=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?C:T),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function k(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,_.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,a.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(n.default.env,(e=>M(e)||!(0,E.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=k,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:F({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function F({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...D(),...i?(0,g.childProcLocale)():{},...k(r),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,E.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return n}t.childEnv=F},84777:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=r(i(31421)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),S=i(22911),b=i(4867),P=i(73614),_=i(70025),E=i(57159),M=i(36868),x=i(66184),C=i(45643),T=i(95402),D=i(9727),k=(0,o.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function F(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,T.killPid)(i).catch((e=>{k().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,C.waitForPidExit)(i,t))return k().debug("endProcess(): exitted",O(e)),!0;{T.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");k().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,T.killPid)(i,!0).catch((e=>{k().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,C.waitForPidExit)(i,5e3)}function I(e,i,r,n=0){const o=new Date,a=[];return(0,v.niceable)(i,r)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&F(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,T.addPid)({pid:e.pid,cmd:i,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,r){const s=(0,D.spawnOptions)(r);return(0,x.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(n.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const r=i.quiet??!1,n=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new S.Deferred(f);o.on("error",(e=>g.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>g.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>g.push(e))),o.stderr?.on("data",(e=>p.push(e))),o.stderr?.on("end",(()=>P.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),k().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const x=p.join("");(0,l.notBlank)(x)&&g.push(new Error(x)),!r&&(0,a.isNotEmpty)(g)&&k().warn(f+" resulted in errors:",g);const C=i.isIgnorableError??_.isIgnorableError,T=g.filter((e=>!0!==C(e)));if(T.length>0)throw 1===T.length?T[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:T});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:x}}catch(e){throw k().error("stdoutResult_() failed",e),await(0,T.killPid)(o.pid,!0),e}}t.endProcess=F,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const s=(0,D.spawnOptions)(r);return k().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(n.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const r=await A(e,t,i);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},3790:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),n=i(41400),s=i(19851),o=i(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},34330:function(e,t,i){var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),S=i(25764),b=i(99331),P=i(42638),_=i(38835),E=i(8769),M=i(57159),x=i(66003),C=i(50213),T=i(45643),D=i(28874),k=i(84777);t.mkBasicWatchedChild=function(e){return new O({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,k.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,C.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),n.set(this,!1),this.onError=(e,t,i)=>{const s=new M.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,n,"f")||o||(this.lastError=s,(0,E.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,r,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:D.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,n,"f")}async end(){return c(this,n,!0,"f"),u(this,r,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,n,"f")}),!u(this,n,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",s).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:D.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=O,n=new WeakMap,r=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,n,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",o).call(this,e)},o=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,T.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,k.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",s).call(this),!this._stopped&&!u(this,n,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,E.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,n,"f")}),this._stopped||u(this,n,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,x.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,E.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,n,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(53916)),a=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,a.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),n=i.sibling(r);if(n.isSelfOrDescendantOf((0,l.examples)()))return o.join("$examples",n.posixPathFrom((0,l.examples)()));const s=(0,d.originalsDir)();if(n.isSelfOrDescendantOf(s))return o.join("$library",n.posixPathFrom(s));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?o.join("$library",n.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const s=i(6858),o=i(1708),a=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return n(this,r,"f").push(...e),this}async parse(e=o.argv,t){let i=(0,m.addHelpFooter)(new s.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of n(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":a.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,o.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of n(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),n=i(31586),s=i(51926),o=i(17344),a=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,n.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),n=i(38639),s=i(17181),o=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,n.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),o.Settings.logColor.envValue=e,(0,s.setupLogFormatter)()}))}}},94361:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),n=i(40958),s=i(55835),o=i(31586),a=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,o.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},76596:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),n=i(19851),s=i(22573),o=i(42659),a=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),n=i(31586),s=i(54557),o=i(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),n=i(40958),s=i(22573),o=i(42659),a=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},84248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},15056:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),n=i(7311);function s(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(n.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(76760)),a=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),S=i(29882),b=i(45969),P=i(43334),_=i(28874),E=i(41692),M=i(32774),x=i(80612),C=i(32551),T=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+T(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+T()),preexistingDir:i});return e}}function k(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+T(),preexistingDir:M.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,C.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,C.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,C.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...D()),i}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,x.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,x.firstDir)({dirs:k(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,E.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(F)}));function F(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},46292:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),n=i(45969),s=i(41692),o=i(32774),a=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),n=i(45969),s=i(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=r(i(76760)),s=i(40958),o=i(72993),a=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),n=i(96706),s=i(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),n=i(40958),s=i(22573),o=i(66430);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),n=i(76760),s=i(1708),o=i(19851),a=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),n=i(49776),s=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,n.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),n=i(54993),s=i(29882),o=i(28874);function a(e){return(0,r.toNotBlank)((0,n.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),n=i(55835),s=i(37805),o=i(15056),a=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e),!1)}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function E(e){return y(_(e))}async function M(e){return y((0,n.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await S(t),await P(t),await E(t),await M(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=E,t.setupLibraryDbDir_=M},46296:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=r(i(76760)),s=i(19851),o=i(40958),a=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(44198),a=i(43334),l=i(24399),u=i(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),n=i(7282),s=i(29325),o=i(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,r.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),n=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=r(i(73024)),s=i(76760),o=r(i(1708)),a=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),S=i(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),i={...o.default.env};for(const r of e)try{const e=(0,d.debom)(n.default.readFileSync((0,g.resolve)(r))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(s))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),n=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,r.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},96706:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=r(i(1708)),s=i(19851),o=i(22573),a=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,a.isTrue)(g(e))}},98314:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),n=i(19851),s=i(40958),o=i(22573),a=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),r=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),r-o.length,n)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),n=i(26905),s=i(55835),o=i(54993),a=i(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,n.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),n=i(76790),s=i(50989),o=i(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),n=i(38639),s=i(26905),o=i(54993),a=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),n=i(31586),s=i(68708),o=i(7282),a=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===i.fatal,c=!0===i.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),n=i(22573),s=i(38639),o=i(26905),a=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,n.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,n.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(49769),a=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,r,"f").get(e);return null!=o&&(o.resolve(t),s(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,n=new WeakMap},34102:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),n=i(19851),s=i(15197);t.ee=(0,n.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=r(i(73024)),s=r(i(1708)),o=i(19851),a=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,n.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=r(i(76760)),s=i(19851),o=i(81168),a=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,o.equalsIgnoreCase)(e.basename,i.base))return n.default.join(r,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),n=i(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,i){var r,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),v=f(i(1708)),w=i(46466),S=f(i(57975)),b=f(i(38522)),P=i(19851),_=i(40958),E=i(5233),M=i(22573),x=i(42659),C=i(50357),T=i(96249),D=i(98553),k=i(55835),O=i(31586),F=i(68708),I=i(97790),L=i(39926),A=i(51926),N=i(59455),R=i(54993),j=i(48884),B=i(22911),V=i(99331),z=i(56519),W=i(56038),U=i(31562),q=i(76850),H=i(70025),G=i(34102),J=i(80875),$=i(50213),K=i(70417),Y=i(43334),Z=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),ne=i(89968),se=i(20197),oe=i(88561),ae=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),Se=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,r=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,M.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const n=(0,fe.resolve)(i),s=new Pe(n,t);return be().set(i,s),be().set(n,s),s}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",s).call(this)??await d(e=this.clearThisAndParent(),r,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,N.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,n,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,C.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,R.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,T.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,x.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>=(0,x.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>(0,x.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*x.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,J.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,J.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,q.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,F.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,E.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,V.ending)()?1:3,timeoutMs:0,retryDelay:x.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,r,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,r,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,A.newlineRe)(),(r=>{const n=e.exec(r);null!=n&&(t.maybeResolve(n),i.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,O.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),_e)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,n)=>{try{const s=await e.f(r,(0,k.denull)(n));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*x.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},84542:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),n=i(96249),s=i(51926),o=i(54993),a=i(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),n=i(19851),s=i(50213),o=i(37805),a=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=r(i(76760)),s=r(i(1708)),o=i(19851),a=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44652)),l=o(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),S=i(16287),b=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class E{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new E(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},n=await a.stat(t);return new E(i,new P(r,n))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return E.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new E(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>E.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new E(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=E},20197:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=r(i(76760)),s=i(39926),o=i(29882),a=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(r.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},88561:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(40958),a=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,r,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),n=i(22573),s=i(45599),o=i(96249),a=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),n=i(17217),s=i(16287),o=i(68284);async function a(e){return(0,r.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},73787:function(e,t,i){var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,n.set(this,[]),s.set(this,void 0),o.set(this,void 0),l(this,o,(0,f.fileStatsSync)(e),"f"),l(this,s,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",a).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,n,"f").push(e)}close(){u(this,s,"f").close()}}t.FileWatcher=m,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,o,"f"),t)){l(this,o,t,"f");for(const t of u(this,n,"f"))t(e,this.nativePath)}}},73209:function(e,t,i){var r,n,s,o,a,l,u,c,d,h,f,m,p,g,y,v,w,S=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const _=i(58587),E=P(i(44652)),M=i(87997),x=i(40958),C=i(17586),T=i(42659),D=i(50357),k=i(75240),O=i(55835),F=i(31586),I=i(30976),L=i(13538),A=i(54993),N=i(7282),R=i(68852),j=i(23560),B=i(25764),V=i(38836),z=i(99331),W=i(22781),U=i(38835),q=i(55222),H=i(63870),G=i(69734),J=i(17217),$=new RegExp("-(?\\d+)"+(0,R.escapeRegExp)(G.PsLockExt)+"$");class K extends V.EndableWrapper{static newUid(e=process.pid){return b(this,n,Math.max(Date.now(),S(this,n,"f",s)+1),"f",s),(0,x.compactBlanks)([q.TokenRadix.encode(S(this,n,"f",s)),j.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return n.pidFromBasename((0,J.basename)(e))}static pidFromBasename(e){return(0,F.toInt)($.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return S(this,n,"f",a).find((t=>t.opts.file===e.file))??new n(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>S(this,r,"m",w).call(this)),e.endableRank??B.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=n,n,(i=S(t,n,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(S(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(n.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await S(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+S(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),S(n,n,"f",a).push(this)}get acquired(){return S(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await S(this,r,"m",f).call(this,e)??S(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,C.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,D.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==S(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,N.isTest)()?10:T.secondMs);b(this,c,setInterval((()=>S(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=S(this,c,"f")&&(clearInterval(S(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(S(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),b(this,u,!1,"f"),(0,O.map)(S(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,z.ending)()||this.ended?S(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>S(this,r,"m",v).call(this)),(0,F.toGt0)(this.staleMs)??T.secondMs),"f"),S(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(S(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,L.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,n=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>S(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await S(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await S(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+T.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,N.isTest)())return this.release(),!1;n.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=n.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,_.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),S(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await S(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await S(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,x.filterInPlace)(S(n,n,"f",a),(e=>S(e,l,"f")!==S(this,l,"f")))},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),n=i(51926),s=i(54993),o=i(17217);function a(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,n.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,n.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&a((0,o.basename)(e))}},4001:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),n=i(55835),s=i(31586),o=i(51926),a=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,s.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const n=(0,u.parsePosixPath)(i),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,n.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(g.exec(t),(e=>t=e[1].trim())),t}},14977:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=r(i(44652)),s=r(i(73024)),o=i(46466),a=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=r(i(77598)),s=r(i(73024)),o=i(46466),a=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=S().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),S().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const r=n.default.createHash(i);return await(0,o.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),n=i(42659),s=i(55835),o=i(31586),a=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*n.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*n.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),n=i(54993),s=i(7282),o=i(43334),a=i(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),n=i(51926),s=i(54993);class o extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=r.pop();this._prior=o??"";let a=!1;for(const e of r)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=r(i(76760)),s=i(17217),o=i(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},85772:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const o=s(i(76760)),a=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),S=i(88561),b=i(65238),P=i(16287),_=(0,a.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),E="NoMedia",M=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(o.default.sep),"/"]).join("")+"])\\.?"+E+"$","im"),x=Object.freeze(["."+E,E]),C=Object.freeze((0,u.flatten)(x.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function T(e){return null!=M.exec(e)}t.isNoMediaName=T;const D=(0,a.lazy)((()=>new S.FileCache({name:"fs.noMediaDirsCache"})));async function k(e,t){if(null==e)return null;const i=v.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return T(i.base)||await(0,w.isCachedirTagFile)(i)?D().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):k(i.parent());{const e=await D().getOrSetAsync(i.nativePath,(()=>O(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:k(i.parent())}}async function O(e){if(T(e.base))return D().set(e.parent().nativePath,e.nativePath),_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,b.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([F(e.nativePath,i),(0,b.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,w.isCachedirTagDirectory)(e)?_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function F(e,t){for(const i of g.isCaseSensitiveFs?C:x){if(!0===t?.aborted)return null;const r=o.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return _().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(T(r.basename))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,o.join)(e,r.basename))});if(r.basename===w.CACHEDIR_TAG){const t=(0,o.join)(e,r.basename);if(await(0,w.isCachedirTagFile)(t))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await k(e,t)},t.whyNoMedia=k,t.whyNoMediaDir=O,t._dirHasNoMediaChild=F},29882:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=r(i(44652)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),S=i(17217),b=i(16287),P=i(66430),_=i(5545);function E(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=E,t.containsHiddenPathname=function(e){return k(e).some(E)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!E(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return x((0,v.posix2native)(e))},t.extname=function(e){return x(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function x(e){const t=M.exec(e)?.groups,i=t?.ext2??"",r=s.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function C(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function T(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),i=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function D(e,t,i){if(null==t||null==i)return!1;const r=e(t),n=e(i);return null!=r&&null!=n&&(y.isLinux?r===n:(0,p.equalsIgnoreCase)(r,n))}function k(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&k(e).length===(y.isWin?1:0)}function F({p:e,maxLength:t}){const i=(0,S.toNativePath_)(e);if(i.length<=t)return i;const r=k(e),n=[],s=[r.pop()];for(;r.length>0;)if(n.length=t){r.unshift(n.pop());break}}else if(s.unshift(r.pop()),L([...n,...s]).length>=t){r.push(s.shift());break}return r.length>0&&n.push("…"),L([...n,...s])}function I(e){return e.startsWith("\\\\")}function L(e){return(0,h.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=x,t.parentBasename=C,t.grandParentBasename=function(e){return C(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=T,t.eqlBasename=function(e,t){return D(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(S.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,S.toNativePath_)(e),r=(0,S.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,v.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=F,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const n=[];for(const r of e.slice(0,i))n.push(F({p:r,maxLength:t}));return n.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=x(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=L,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:L(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>T({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=r(i(76760)),s=i(19851),o=i(40958),a=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),S=i(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function E(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(i,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...E()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,o.uniq)((0,o.compactBlanks)([...M(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=n.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){var r,n,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),S=i(22573),b=i(42659),P=i(26905),_=i(75240),E=i(55835),M=i(31586),x=i(68708),C=i(13538),T=i(89937),D=i(12168),k=i(54993),O=i(48884),F=i(50213),I=i(45255),L=i(81168),A=i(56519),N=i(56038),R=i(31562),j=i(84777),B=i(9595),V=i(38835),z=i(70025),W=i(57902),U=i(55222),q=i(43334),H=i(33847),G=i(24399),J=i(28874),$=i(79915),K=i(45200),Y=i(34238),Z=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),ne=i(73209),se=i(48313),oe=i(29882),ae=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,F.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,$.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,ae.toNativePath_)(e),r=new fe(i,t);return(0,L.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,oe.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,oe.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,E.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,E.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,k.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===T.PS_LIBRARY_SCHEME?1:t.scheme===T.PS_LOCAL_FILE_SCHEME?2:t.scheme===T.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,$.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,$.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,E.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,x.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:n,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:o,minSizeBytes:i,timeoutMs:n,dirty:l})}return a&&r?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*n,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,M.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:n,dirty:s=!1}){return await this.parent().mkdirp_(),(0,ne.withLock_)({file:this,skipFsLock:r,timeoutMs:n,dirty:s},(async()=>{const r=this.wip();try{await r.unlink("trace");const s=await(0,C.thenOrTimeoutError)(e(r),n);if(s===t.NoOp)return s;if(await(0,R.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,N.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==J.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",n).call(this,t)}catch(e){if(!0===(0,z.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();J.Settings.verifyFileCopies.valueOrDefault&&(await(0,R.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,M.clamp)(I.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,E.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,oe.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,oe.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Z.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,n=async function(e){let t,i=e;const r=e.wip();try{const n=await this.stat_();if(null==n)return this.pflog().throw("Can't copy missing files"+V.NonRetriableErrorFlag);if(n.size>0){if(J.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+V.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),n.size>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},n.size,(()=>r.size({refresh:!0})))),!await(0,R.untilTrue)((async()=>(0,M.approximates)(n.size,await r.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:n.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:n.birthtimeMs,mtimeMs:n.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,n.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${n.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,E.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),n=r?.size;return null==r||null==n?this.pflog().throw("Can't copy missing files"):(n>5*D.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},n,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+V.DoNotSendErrorFlag,{error:t})}finally{(0,E.map)(t,(e=>e.end()))}}},78133:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=r(i(76760)),s=i(22573),o=i(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const i=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",r=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=r(i(76760)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(n.default.join((0,p.execDir)(),"resources"),n.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,p.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=n.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),n=i(19851),s=i(31586),o=i(50213),a=i(57902),l=i(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),n=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const n=i??(await(0,r.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await(0,r.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,r.close)}}},69428:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},55690:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),n=i(84542);t.readLines_=async function(e){return(0,n.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class n extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=r(i(51455)),s=i(76760),o=i(19851),a=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),S=i(88561),b=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function _(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const E=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||E.prior()?.delete(e)}async function x(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await E().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=C(e),n=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===f.Timeout&&(0,g.onTimeout)({soft:!1}),n!==f.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),E.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!E().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=E().get(e)},t.childDirectories_=async function(e){return(await x(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?x(e):C(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=x,t.readdirCached=function(e){return E().get(e)},t.readdirUncached_=C},53265:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=i(73024),s=r(i(76760)),o=i(40958),a=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=s.default.resolve(t,...e);if((0,n.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},50274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),n=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=r(i(73024)),s=r(i(76760)),o=i(22573),a=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],n=t[i],s=(0,u.diff)(b(r),b(n));if(null==s||s>1)return"unmatched "+i+": "+r+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=r(i(73024)),s=i(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const i=o(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=o(e);return t.emptyIsNew?null==i:a(i)},t.isNonEmptyFileSync=function(e,t=0){const i=o(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),n=i(56409);t.onDataChunked=function(e,t,i){const r=new s(t,i,!0);return r.read(e),r.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=r(i(57075)),s=i(41400),o=i(55835),a=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends n.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=r(i(73024)),s=i(76760),o=i(22573),a=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},27794:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=r(i(44652)),s=i(19851),o=i(22573),a=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},5545:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=r(i(76760)),s=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??n.default.sep)}},70257:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),n=i(45255),s=i(17217);t.WipTimeoutMs=n.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const o=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(o,"")},t.isWip=function(e){return o.test((0,s.basename)(e)??"")}},58722:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),n=i(22911);class s extends r.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},73428:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=r(i(44652)),s=r(i(76760)),o=i(51926),a=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=r(i(73024)),s=i(76760),o=i(46466),a=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const r=[],s=[n.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>r.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},33866:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},52086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},13940:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),n=i(19851),s=i(42659),o=i(59455),a=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),S=(0,n.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,n.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,n.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const n=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const s=n.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+r);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:o}),o}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const n=await P(e,t,i);return await n.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),n}catch(r){return S().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48584:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},49794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),n=i(19851),s=i(40958),o=i(22573),a=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),n=i(23560),s=i(66184),o=i(72210);class a{log(e,t,i,r){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,r.lazy)((()=>new a))},14593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),n=i(22573),s=i(26905),o=i(55835),a=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),n=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof n.LogWriter))}},28981:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),n=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new n.PlaintextLogFormatter))},31256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(41400),a=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,o.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(77030),o=i(19851),a=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),S=(0,o.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,a.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const o=this.socket;null==o?n(this,r,"f").call(this):o.write(this.logFormatter.format(e,t,i,s)+b)}catch(r){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),n=i(42659),s=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},4904:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),n=i(31586),s=i(51926),o=i(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),n=i(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,n.set(this,[]),s.set(this,(0,l.lazy)((()=>{a(this,n,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:a(this,n,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>a(this,s,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=a(this,r,"m",o).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=a(this,r,"m",o).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap,s=new WeakMap,r=new WeakSet,o=function(e){if(null==e||0===a(this,n,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return a(this,n,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),n=i(50989),s=i(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),n=i(68708),s=i(20214),o=i(51926),a=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,o.isString)(i)||Buffer.isBuffer(i))return(0,o.ellipsize)(i.toString(),256,32);if((0,a.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const a=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(i),(0,n.keys)(a));return(0,r.isNotEmpty)(c)&&(a["…"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return i}},89241:function(e,t,i){var r,n,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),h=i(38522),f=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),v=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),n.set(this,!1),s.set(this,!1),o.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,o,!0,"f")})),this.stream.on("data",c(this,r,"m",a).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,n,!0,"f")})),this.stream.on("end",(()=>{u(this,n,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,o,"f"),ended:c(this,n,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,o,"f")}get ended(){return c(this,n,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e){if(null===e)u(this,n,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},24068:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),n=i(76760),s=i(1708),o=i(87997),a=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),S=i(38836),b=i(99331),P=i(42638),_=i(76596),E=i(98314),M=i(89968),x=i(29882),C=i(28874),T=i(28981),D=i(20839),k=i(21727),O=i(66184),F=i(57902),I=i(72210),L=i(98192);function A(e){const t=(0,T.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class N extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,C.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,x.mkdirp_)(e),this.root=await M.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),D.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(F.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,n.join)(e,i))}))}catch(t){return void(0,O.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,E.errorToS)(t))))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,_.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,k.datedLogDir)(this.root.nativePath);try{await(0,x.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,E.errorToS)(e))))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await M.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,L.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,E.errorToS)(e))))}}))}}t.LogTail=N,N.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new N))},72210:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),n=i(82328),s=i(28981),o=i(20839),a=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),S=i(23560),b=i(81168),P=i(78406),_=i(25764),E=i(20197),M=i(14977),x=i(36868),C=i(28874),T=i(32105),D=i(20839),k=i(21727),O=i(66184),F=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*D.DefaultLogFlushMs),rank:_.EndableRanks.logger,unref:!0,onEnd:()=>c(this,n,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:T.ConsoleLogger.instance(),flushEveryMs:D.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const n={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(n.meta=(0,F.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,n=new WeakMap,r=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,i);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,r,"m",o).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,E.ensureNewNativePath_)({nativePath:(0,f.join)((0,k.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",a).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,x.endStream)(e.stream),C.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,M.gzip_)(e.nativePath))}catch(e){c(this,r,"m",o).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),n=i(40958),s=i(55835),o=i(68708),a=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),n=i(84542),s=i(4001),o=i(13047),a=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),r=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,n.splitLines)(a)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),n=i(76790),s=i(68708),o=i(89788),a=i(57902);t.SentLogLevels=(0,r.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),n=i(41400),s=i(55835),o=i(37975),a=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),S=i(24068),b=i(43705),P=i(51879);function _(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),E();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new b.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,s.map)((0,y.logBroadcaster)(),(e=>i.push(e))),a.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&S.LogTail.instance()}function E(){const e=h.Settings.logColor.valueOrDefault;(0,o.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=_,t.setupLogFormatter=E,(0,n.later)((()=>{h.Settings.logStdout.watchLater(_),h.Settings.logDir.watchLater(_),h.Settings.tailLogs.watchLater(_),h.Settings.logColor.watchLater(E),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},75631:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Recent=void 0;const n=r(i(1708)),s=i(57075),o=i(40958),a=i(76790),l=i(42659),u=i(41400),c=i(96249),d=i(55835),h=i(31586),f=i(34666),m=i(5670),p=i(45608),g=i(56519),y=i(69554),v=i(38790),w=i(70488),S=i(83278),b=i(84542),P=i(89968),_=i(14977),E=i(33456),M=i(28981),x=i(4904),C=i(89241),T=i(98192),D=i(97352),k=i(28874),O=i(2858);let F;function I(e){n.default.stdout.write(e+b.Newline)}async function L(e){const t=S.BaseFile.for(e);if(await t.isFile())return[t.nativePath];if(await t.isDirectory()){const e=await t.descendants((e=>e.ext.startsWith(".log")));return e?.map((e=>e.nativePath))}}t.Recent={beforeParse:e=>e.option("--recent [duration]",'Automatically cat recent logs. The optional "duration" argument can either be a number, which will be interpreted in minutes, or an ISO 8601 duration string, like "1d" for 1 day, or "20m" for 20 minutes. Defaults to 1 day.'),afterParse:e=>{null!=e.recent&&(!0===e.recent?F=l.dayMs:(0,D.mapGt0)(e.recent,(e=>F=e*l.minuteMs))??(0,w.decodeDuration)(e.recent))}},async function(){const e=await new y.CLI(m.ServiceNames.logcat,"[FILE_OR_DIR...]","FILE_OR_DIR may be either a logfile or a directory that will be scanned for .log, .log.gz, and .log.bz files.").add(t.Recent,v.ColorArgs).parse();n.default.on("SIGINT",(()=>(0,p.exit)({reason:"SIGINT",status:0}))),n.default.on("SIGTERM",(()=>(0,p.exit)({reason:"SIGTERM",status:0})));const i=(0,o.uniq)((0,c.flatten)(await(0,g.mapAsync)({name:"parseArgs",arr:e.args,f:L})));if((0,h.gt0)(F)){const e=(0,_.matcherForExtOrCompressedExt)(".log");await(0,O.readSystemSettings)();const t=Date.now()-F;await S.BaseFile.for(k.Settings.logDir.valueOrDefault).visitDescendants((async r=>{const n=await r.maxStatMs();e(r.ext)&&await r.isFile()&&(0,f.gt)(n,t)&&i.push(r.nativePath)}))}const r=(0,M.DefaultLogFormatter)();if((0,o.isEmpty)(i))return(0,o.isNotEmpty)(e.args)&&(console.error(r.format("error","logcat","No valid logfiles were provided.")),e.help()),I(r.format("info","logcat","No log files provided: reading from stdin.")),I(r.format("warn","logcat","The output will not be sorted chronologically.")),void await s.promises.pipeline(n.default.stdin,new E.LineReader,new s.Transform({transform(e,t,i){(0,d.map)((0,T.chunkToLogEntry)(e),(e=>I(r.formatLogEntry({from:"",...e})))),i()}}));const l=await(0,g.thenCompact)(i.map((async e=>{const t=await P.DirectoryEntry.for(e);return null!=t&&(0,h.gt0)(t.size())?new C.LogReader(t,console.error):void 0})));function w(){let e;(0,o.filterInPlace)(l,(e=>!e.complete()));for(const t of l){if(!t.ready())return;const i=t.peek();null!=i?.ts&&(null==e||i.tse.f.nativePath))));l.length>0;)try{const e=w();if(null!=e)for(const t of e)I(r.formatLogEntry(t));else await(0,u.delay)(10,!1)}catch(e){console.error("caught error",e)}n.default.stdout.write(b.Newline,(()=>(0,p.exit)({reason:"",status:0})))}()},82647:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(57975),a=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,r,"m",n).call(this,-1)}get p29(){return s(this,r,"m",n).call(this,-.5)}get p38(){return s(this,r,"m",n).call(this,-.25)}get p69(){return s(this,r,"m",n).call(this,.5)}get p84(){return s(this,r,"m",n).call(this,1)}get p98(){return s(this,r,"m",n).call(this,2)}get p99(){return s(this,r,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),n=i(55835),s=i(31586),o=i(30976),a=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,n.map2)(e,t,((e,t)=>(0,r.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):r[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let n=0;n(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},55222:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),n=i(22573),s=i(55835),o=i(32639),a=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),n=this.normalizeToken(t);return r.length>=i&&r===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},17921:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),n=i(65713);function s(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,n.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,r,"f")/(s(this,r,"f")+1)+e/(s(this,r,"f")+1),"f"),o(this,r,(t=s(this,r,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,u.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),n=v(t,(e=>(e-i)**2));return 0===n?0:r/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},49076:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const n=r(i(48161)),s=i(19851),o=i(22573),a=i(41400),l=i(81168),u=i(28874);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??n.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??n.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},96128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),n=i(19851),s=i(22573),o=i(42659),a=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),S=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==S.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=b.exec(e)}function _(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=_,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=_(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void E().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const E=(0,n.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=_(e)?r.promises.reverse(e):r.promises.resolve4(e),5*o.secondMs);if(t===c.Timeout)return E().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(E().warn("No name found for "+e),e):i}catch(t){return E().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),n=i(42659),s=i(31586),o=i(97790),a=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*n.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs})},45969:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),n=i(38639),s=i(19851),o=i(59958),a=i(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),n=i(19851),s=i(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},43334:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=r(i(48161)),s=r(i(1708)),o=i(22573),a=i(38639),l=i(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=r(i(73024)),s=i(19851),o=i(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),n=i(59455),s=i(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),S=i(54993),b=i(54557),P=i(19851),_=i(50213),E=i(88158),M=i(409),x=i(78406),C=i(25764),T=i(99331),D=i(56519),k=i(46292),O=i(8769),F=i(83278),I=i(32144),L=i(29882),A=i(43334),N=i(24399),R=i(58261),j=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),B=10*p.secondMs;function V(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,L.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??A.isWin,r=await this.pidfiles(),n=await this.pids(r??[]);if((0,f.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,R.pidInfos)(n);if(null!=a){for(const n of r){const r=await n.readJson();if(null==r){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:r,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!V(r,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:r,pidEntry:u}),await n.unlink("debug"),s.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:r}),o.push(W(l,i,!1)),s.push({...r,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(i&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const i=a(this,r,"m",s).call(this,e.pid),n=(0,v.opt)((0,E.Try)((()=>(0,L.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await i.writeJson_(l),j().debug("addPid() wrote "+i,l),i}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,r,"m",s).call(this,e);return(0,D.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new x.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:C.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=U,n=new WeakMap,o=new WeakMap,r=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,k.configDir)(),(e=>new U(F.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=i(31421),s=i(48161),o=r(i(1708)),a=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),S=i(56519),b=i(84777),P=i(8103),_=i(45879),E=i(43334),M=i(24399),x=i(45643),C=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function T(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){if(E.isLinux)return async function(e){const t=[];for(const i of e)t.push(z(await(0,_.readFileMaybe)("/proc/"+i+"/stat")));return C().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,x.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,E.isWin?I:R)).filter((e=>T(e)&&t.includes(e.pid)));return C().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=T,t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,x.existingPids)(e),(t=>{const i=[o.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=D;const k="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return N(e);const t=[k,"-Id",F(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const L={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function N(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,L),r=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===o.default.pid))||r.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),r}async function R(e){return t=(await(0,b.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...L,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=N;const j=(0,g.lazy)((()=>{try{if(E.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){C().warn("clk_tck failed",{error:e})}return 100})),B=(0,g.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),V=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function z(e){const t=V.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(n)?{pid:i,cmd:r,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),n=i(22573),s=i(31586),o=i(29882),a=i(97352);t.progressEvtToS=function(e){const t=(0,n.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,n.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},41944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),n=i(42659),s=i(31586),o=i(12089),a=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new a.TTLMap(15*n.secondMs))),t.recentDone=(0,r.lazy)((()=>new a.TTLMap(2*n.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),n=i(31586),s=i(409),o=i(78406),a=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends o.EndableInterval{constructor(e,t,i,n=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:n,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=n,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,n.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,n.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},24399:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),n=i(19851),s=i(22573),o=i(42659),a=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),S=i(31562),b=i(84777),P=i(34102),_=i(43334),E=i(28874),M=i(63870),x="{ready}",C=" | ConvertTo-Json -Compress";function T(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=T,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",E.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${x}"}`,...(0,s.mapNotBlankOr)(E.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:x,fail:"Error",exitCommand:"exit",maxProcs:E.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),E.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(E.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,C),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,n)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,n)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,C),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+T(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,n.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),n=i(38639),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),n=i(31586),s=i(97790),o=i(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(97790),o=i(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(r.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),n=i(22573),s=i(45599),o=i(50213),a=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,n.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),n=i(91655),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},4175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),n=i(22573),s=i(38639),o=i(42659),a=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){_(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&E()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,n.blank)(m.Settings.assetPathnameFormat.value)&&(0,n.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*o.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const S=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],b={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function _(e){for(const t of S)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:b;for(const[e,i]of(0,a.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function E(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=_,t.disableExternalNetworkRequests=E},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),n=i(53265),s=i(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class n extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),n=i(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=i(19851),a=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),S=i(44198),b=i(96706),P=i(34102),_=i(28283),E=i(81075),M=i(98778),x=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,r,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?s(this,r,"m",n).call(this,e??t)+": "+i:null==this.fromEnv(e)?s(this,r,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return E.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,S.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&b.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,S.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&b.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],x.WrapComments);function i(e,i){(0,a.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],x.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+r],x.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:x.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:x.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),n=i(51168),s=i(76760),o=i(19851),a=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),S=i(7282),b=i(12801),P=i(4328),_=i(70488),E=i(84248),M=i(5531),x=i(99315),C=i(34365),T=i(34580),D=i(96706),k=i(50274),O=i(33866),F=i(52086),I=i(48584),L=i(45969),A=i(43334),N=i(24540),R=i(70379),j=i(71300),B=i(33209),V=i(48987),z=i(68268),W=i(61208),U=i(99023),q=i(30577),H=i(1485),G=i(19861),J=i(55111),$=i(30933),K=i(22859),Y=i(71988),Z=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),ne=i(57039),se=i(9945),oe=i(74589),ae=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new oe.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>H.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:H.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>H.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,L.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:J.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:E.AutoVacuumModes,defaultValue:E.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:C.SynchronousModes,defaultValue:C.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:x.RepairModes,defaultValue:x.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,L.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:q.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,T.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,N.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,$.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:k.SidecarExts,defaultValue:k.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,$.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:F.CropStrategies.attention,strEnum:F.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>V.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:R.DateTagFormats.ym,strEnum:R.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,L.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function be(e){const i=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,L.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,D.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),n=i(31586),s=i(7282),o=i(49776),a=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(22573),a=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),S=i(81168),b=i(83556),P=i(87290),_=i(98314),E=i(34102),M=i(83278),x=i(95696),C=i(60865),T=i(4175),D=i(83179),k=i(81075),O=i(28874),F=i(41692),I=i(84438),L=i(32707),A=i(6707),N=i(98778),R=i(55018),j=i(10357),B=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function V(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function z(e=(0,L.systemSettingsFile)()){if(null!=e)return X(M.BaseFile.for(e))}async function W(){try{return(0,o.toNotBlank)((await(0,A.readTomlFile_)((0,L.systemSettingsFile)()))?.[O.Settings.libraryDir.name])}catch{return}}function U(e){return(0,A.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function q(){return U((0,L.systemSettingsFile)())}function H(e){return U(V(e))}function G(){t.libraryHasSettings.refresh()}function J(e){const t=V(e);return B().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:O.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function $(e,i){if(null==e)return void B().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),n=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,N.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let n="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,E.ee)().emitDebounced("settingsChanged")}(n,i),B().info("writeToml(): wrote settings",{dest:n,file:e,nonDefaults:(0,D.settingsToObj)(i),wip:r}),r){const t=await(0,A.readTomlFile_)(n),i=await(0,A.readTomlFile_)(e);(0,u.eql)(t,i)?(B().info("Equivalent contents",{dest:n,file:e,a:t,b:i}),await n.unlink()):(B().info("Archiving prior, different contents",{dest:n,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await n.unwip_())}}async function K(e=(0,L.systemSettingsFile)()){const t=x.PosixFile.forMaybe(e);return null!=t&&await $(t,(0,O.persistedSystemSettings)()),t}function Y(e){return X(V(e))}async function Z(e){await(0,P.setupLibraryDataDir_)((0,o.firstNotBlank)(e,O.Settings.libraryDir.value));const i=V(e);return B().info("writeLibrarySettings()",{file:i}),null!=i&&(await $(i,(0,O.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=B().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,n.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function Q(e){const t=B().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,A.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const s=[],o=(0,n.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,O.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,O.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;s.push(e)}})));return t.info("loaded",{settings:(0,D.settingsToObj)(o),warnings:(0,n.toNotEmpty)(s)}),await(0,T.handleDeprecatedSettings)(),(0,T.handleMetaSettings)(o),{settings:o,warnings:s}}t.librarySettingsFile=V,t.readSettings=(0,r.lazy)((async()=>{await z(),(0,t.libraryHasSettings)()&&await Y()}),a.minuteMs),t.readSystemSettings=z,t.envOrSavedLibraryDir=async function(){return O.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=q,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await q()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await H()&&await Z()},t.libraryHasSettings=(0,r.lazy)((()=>J())),t.libraryHasSettings.unset=()=>{B().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,E.ee)().on("clearCache",G),(0,E.ee)().on("settingsChanged",G),O.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=J,t.versionForSettings=(0,r.lazy)((()=>(0,C.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return $(x.PosixFile.for(e),(0,O.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=Z,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([O.Settings.noNetwork,O.Settings.httpPort,O.Settings.license,O.Settings.logStdout,O.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(O.Settings))ee().has(e.key)||e.unset();(0,E.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,j.WrapComments))))}t.clearLibraryDirSetting=async function(){await z(),O.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(x.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(x.PosixFile.forMaybe(V())?.unlink("trace")),(0,E.ee)().emit("clearCache"),F.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${C.versionMajorMinor}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...k.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...k.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,o={...e.addToJSON()};(0,n.mapNotEmpty)(e.altKeys,(e=>o.aliases=(0,h.orList)(e)));const a=(0,p.entries)(o).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,R.valueToS)(t)}`));(0,n.isNotEmpty)(a)&&a.push(""),i.push(...ie((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...a,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),n=i(40958),s=i(22573),o=i(98553),a=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function h(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class n extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),n=i(98553),s=i(55835),o=i(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,n=e.strEnum,(0,r.compact)((0,o.splitStringArray)(i)?.map((e=>n.getCI(e))));var i,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),n=i(81168),s=i(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),n=i(55835),s=i(46292),o=i(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,r.join)(e,o.SettingsToml)))}},80496:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),n=i(44652),s=i(22573),o=i(76850),a=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),n=i(96249),s=i(98553),o=i(68708),a=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[n]:(0,a.wrap)(n.split("\n"),i)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},65162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),n=i(81168);t.bname=function(e,t=!0){let i=(0,n.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,n.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},70379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},88840:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),n=i(40958),s=i(96249),o=i(23838),a=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,a.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},68268:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},61208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},79915:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),n=i(40958),s=i(22573),o=i(81168),a=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isJsonExt)(i.ext),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,n.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,n.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return a&&function(e,i){const r=(0,o.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function n(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=n(e.slice(r.length)),l=n(i.slice(r.length));return a&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},45200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(96249),a=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,n.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,n.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),n=i(57975),s=i(57160),o=i(22573),a=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,n,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=n??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return M(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:n,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===n?n=this.query:null===n&&(n=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&r===this.path&&n===this.query&&s===this.fragment?this:new b(t,i,r,n,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const r=i[2]||g,n=D(i[4]||g),s=(i[5]||g).split("/").map(D).join("/"),o="psfile"===r&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=D(i[9]||g);return new b(r,n,o,a,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(M(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return x(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=M(this,!1)),this._fsPath}toString(e=!1){return e?x(this,!0):(null==this._formatted&&(this._formatted=x(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,r=-1;for(let n=0;n=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),void 0!==i&&(i+=e.charAt(n));else{void 0===i&&(i=e.substr(0,n));const t=P[s];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),i+=t):-1===r&&(r=n)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function E(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function x(e,t){const i=t?E:_;let r="";const{scheme:n,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(n&&(r+=n,r+=":"),(l||"file"===n)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>r+="?"+e)),a&&(r+="#",r+=t?a:_(a,!1)),r}function C(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+C(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=M;const T=/(?:%[\dA-Z][\dA-Z])+/gi;function D(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(T)?e.replace(T,(e=>C(e))):e}t.percentDecode=D,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),n=i(40958),s=i(50357),o=i(89937),a=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,n.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),n=i(22573),s=i(51926),o=i(89937),a=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,n.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,n.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,n.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,s=(0,n.notBlank)(t)&&!t.includes(i);if(s&&!(0,n.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?f(a.mountpoint,e.path):s&&(0,n.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),n=i(22573),s=i(51926),o=i(89937),a=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,n.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,n.blank)(t))return;const i=(0,r.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(76760)),a=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,a.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const n=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...n);return await(0,h.isReadableDirectory)(t)?o.join(t,...n):void 0}},85087:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),n=i(42659),s=i(9103),o=i(37628);t.volsha=(0,s.memoize)((e=>(0,r.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:n.minuteMs})},60865:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),n=i(30577);t.channel=function(){return(0,n.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),n=i(22573),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof r.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const s=o(e);return null!=s&&(0,r.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),n=i(9595),s=i(29882),o=i(43334),a=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,n.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},1485:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),n=i(22573),s=i(59455),o=i(50213),a=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),n=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||r||n);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:n}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,n.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,n.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const n=m(e.Used)??0,s=m(e.Available)??0;if(0!==n||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?n+s:r,used:n,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:n,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,n.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(22573),a=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),S=i(24541),b=i(60224),P=i(63870),_=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const E=/([a-z]+)(?::\\)?/i;function M(e){return e?.match(E)?.[1]?.toUpperCase()}function x(e){return(0,l.map)(M(e),(e=>e+":\\"))}function C(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(M(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function T(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function D(e){return`Get-Volume ${(0,f.toS)(M(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=x,t.getPsDriveCommand=C,t.getVolumeCommand=D,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(D())};const k=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function F(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=x(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,n.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(k.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var s}async function I(){const e=(0,n.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(x)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(C(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,n.compact)((0,a.flatten)(t).map(T)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(D(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,n.compact)((0,a.flatten)(r).map(F)),l=(0,n.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,n.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=F,t.volumeInfoWin=I},68884:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(42659),a=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),S=i(16287),b=i(45969),P=i(43334),_=i(69108),E=i(98770),M=i(44224),x=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,x.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const C=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?C().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,M.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):C().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,n.isEmpty)(e)?[]:(C().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,x.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void C().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await T(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,x.mountpointsTtlMs)()}))),(0,a.later)((()=>(0,E.setupVolumeTTL)(t.gioVolumes)));const T=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,x.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void C().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},98770:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),n=i(5233),s=i(41400),o=i(56038),a=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,n.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),S=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const s=(0,c.sortIgnoreCase)((0,n.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const n=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...n,...s},u=r?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:n,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),_=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),r=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),n=i(19851),s=i(40958),o=i(22573),a=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,n.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),n=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of n)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(42659),a=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),S=i(8769),b=i(34102),P=i(17217),_=i(16287),E=i(43334),M=i(28874),x=i(8540),C=i(68884),T=i(44224),D=i(24541),k=i(69375),O=i(63870),F=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,O.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function A(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{M.Settings.libraryDir.watchLater(I),M.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&M.Settings.scanAllDrives.valueOrDefault?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(E.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,O.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),E.isLinux){const i=(0,T.maybeWatchProcMounts)();await(0,C.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,O.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await R()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,O.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),o.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const N=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=M.Settings.mountpoints.values;if((0,n.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",E.isWin?D.mountpointsWin:T.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,n.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,O.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,k.isExcludedMountpoint)(e)||M.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return N.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),N()}})),t.isPosixMountpoint=async function(e){if(E.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return E.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,a.later)((()=>{(0,b.ee)().on("clearCache",(()=>{C.gioVolumes.unset(),I()})),M.Settings.mountpointsTtlMs.watch(L)}),(0,c.isTest)()?1:o.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>A(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:C.GioCommand,args:C.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(C.gioVolumes.unset(),A()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const R=(0,r.lazy)((async()=>{if(!E.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,O.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>A(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),n=i(40958),s=i(42659),o=i(48884),a=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),S=i(68884),b=i(59107),P=i(69375),_=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await C()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,S.isGioSupported)())try{await(0,c.thenMap)((0,S.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){_().warn("Failed to fetch gio volumes",e)}return e};const E="/proc/mounts";function M(e){return!v.Settings.excludedFilesystemTypes.has(e)}function x(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function C(e=E,t=M,i=x){if(y.isLinux)try{const r=await(0,f.readLines_)(e),s=(0,n.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),a=await(0,c.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,r])=>{const n=t(e),s=await i(r);return _().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:n&&s,meta:{fs:e,mp:r,fsOK:n,mpOK:s}})}});return _().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void _().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=C,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(E)?new h.FileWatcher(E,{recursive:!1,persistent:!1},(()=>{_().info("detected change in "+E),(0,d.setUnrefTimeout)((()=>b.mountpoints.refresh()),s.secondMs)})):void 0))},24541:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),n=i(42659),s=i(13538),o=i(50213),a=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),a.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*n.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),n=i(22573),s=i(50213),o=i(9103),a=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),n=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,r.blank)(e))return;const i=n.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},60224:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),n=i(22573),s=i(42659),o=i(55835),a=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await M()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,n.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,n.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(n.notBlank).getOrElse((()=>"/"))}))))).get()}async function E(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,u.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=E;const M=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?E():(0,r.compact)(e.filter((e=>(0,n.notBlank)(e.LocalName))).map((e=>(0,o.map)(_(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),n=i(12168),s=i(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/r.secondMs},86848:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(38639),a=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),S=i(28874),b=i(59107),P=i(63870),_=i(68995),E=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,n.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function x(e){return(0,o.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function C(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function T(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=C(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function D(e){if(S.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of S.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),r=await T(i).catch((e=>E().info("Failed to read "+i,{error:e})));if(null!=r)return E().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,_.volumeUuidSubpath)());if("/"===e.mountpoint)return E().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(S.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return E().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(S.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,_.writeVolumeUuid)(e);if(!(0,s.blank)(t))return E().tap({msg:"readVolumeUUID(): wrote new "+(0,_.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return E().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),b.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(x(e))return;if((0,o.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>D(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>E().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=x,t.toVolumeUUID=C,t.readUuidFile_=T,t.readVolumeUUID=D},7014:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const n=r(i(48161)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),S=i(50213),b=i(7282),P=i(23560),_=i(28850),E=i(45255),M=i(81168),x=i(56519),C=i(4867),T=i(49776),D=i(9595),k=i(77740),O=i(44198),F=i(96706),I=i(8769),L=i(57159),A=(i(34102),i(21144)),N=i(73209),R=i(29882),j=i(95696),B=i(17217),V=i(16287),z=i(49076),W=i(96128),U=i(45969),q=i(43334),H=i(28874),G=i(85087),J=i(50424),$=i(48165),K=i(98770),Y=i(27461),Z=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,o.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=n.default.platform(),se=new Map,oe=new Map,ae=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,se),le((0,G.volsha)(e.uuid),e,ae),e}function ce(){return(0,a.compact)([j.PosixFile.forMaybe((0,T.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,D.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),se.clear(),ae.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,M.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),n=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,z.cleanHostname)()},updatedAt:r,os:ne}))),s=new Map;for(const e of n)for(const t of(0,a.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))s.set(t,e);const o=ce();for(const e of o)await(0,N.withLock_)({file:e,timeoutMs:E.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:n.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),n=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:n,priorIsMissingMountpoints:s}),n||s?void 0:e}async function me(e,i){const r=(0,m.map)(e,B.toNativePath_);if((0,u.blank)(r))return;const n=await(0,A.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,R.bestMountpointForDir)(n,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:n,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:n}})}async function pe(e,t,i){const r=i.filter((e=>(0,M.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(r))return;const n=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,M.equalsIgnoreCase)(e,t.remoteHost)));if(null!=n)return n;const s=await(0,W.friendlyname)(e);return(0,x.asyncFind)(r,(async e=>(0,M.equalsIgnoreCase)(s,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,P.isSyncService)()||(0,b.isTest)())),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await de()),t=(0,v.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,a.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,C.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,C.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,a.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if((0,b.isTest)()){const e=(0,p.toInt)((0,O.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,k.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,C.thenOrTimeoutError)({p:q.isWin?(0,$.dfWin)():(0,J.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,V.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,C.thenOrTimeoutError)({p:q.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,Z.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,o.lazy)((()=>q.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,M.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,R.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return ae.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(50213),a=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const n=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(n))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},65713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),n=i(19851),s=i(23838),o=i(81168),a=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,n.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,n.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,n.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=n)return n}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),n=i(96249),s=i(23838),o=i(59455),a=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,n.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},30933:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=r(i(48161)),s=i(19851),o=i(42659),a=i(31586),l=i(50213),u=i(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=r(i(48161)),s=i(19851),o=i(31586),a=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},15674:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),n=i(42659),s=i(41400),o=i(31586),a=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,r.lazy)((()=>{const e=(0,o.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*a.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=w();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,o.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),n=i(87997),s=i(19851),o=i(42659),a=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new r.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,n.setInterval)(g,o.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),n=i(22573),s=i(50357),o=i(98553),a=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,a.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const n=[];if(et;s-=i)n.push(r(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),n=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const n of t){const t=i(n);r.includes(t)||(e.push(n),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const n=new Set(i.map(r));return e.filter((e=>!n.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),n=i(36783),s=i(41801),o=i(98553),a=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,a.getOrSet)(i,(0,o.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},5233:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),n=i(31586),s=i(13538),o=i(41583);t.retryOnReject_=async function(e,t){const i=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},22573:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),n=i(42279),s=i(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),n=i(22573),s=i(30301),o=i(55835),a=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),n=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,n,r)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,n.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/r.ms);e-=s*r.ms,s>0&&(r.ms>=t.dayMs?i:n).push(s+r.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),n=i(73872);function s(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function o(e,t,i,r){if(null==i||y(e)||y(t))return;let n=i.get(e);null!=n?n.set(t,r):(n=new WeakMap,n.set(t,r),i.set(e,n))}function a(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const n=l(e,t);return null!==n?n:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return o(e,t,u,i),i;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],n=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(r.sort(),n.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let n=-1;for(;++n{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const n=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return n.prior=()=>t,n.hasPrior=()=>r,n}},41400:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),n=i(35556),s=i(31586),o=i(68708);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=n.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return n.isBrowser||t<=r.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},50357:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),n=i(68708),s=i(34666),o=i(32639);function a(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const i of(0,n.keys)(e))if(!a(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(31586),a=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,s.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},96249:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),n=i(42659),s=i(55835),o=i(31586),a=i(12168),l=[{ms:n.yearMs,s:"year",p:"years"},{ms:n.yearMs/12,s:"month",p:"months"},{ms:n.weekMs,s:"week",p:"weeks"},{ms:n.dayMs,s:"day",p:"days"},{ms:n.hourMs,s:"hour",p:"hours"},{ms:n.minuteMs,s:"minute",p:"minutes"},{ms:n.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,n){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(n,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function n(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},73722:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const n=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,n){if((0,isFunction_1.isFunction)(r))return;let s,o,a,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),n=i(50357),s=i(31586),o=i(65812);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const s=await e,a=await i;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),n=i(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return a(o(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),n=i(76790),s=i(50357),o=i(98553),a=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,s.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),n=null==i?[]:e(t,i);(0,r.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,n]of this.store.entries()){const s=(0,r.findIndexes)(n,(t=>!e(i,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,n.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),n=i(22573),s=i(42279),o=i(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>a(t)&&a(i)&&e(t,i);function f(e,i,n){return!(null==n||!a(n))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,n)&&(0,t.gte)(i,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function E(e,t,i){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return a(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)a(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,i){return b(e,(e=>b(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return a(e)?t(e):i},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return E(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!a(i))return;t+=i}return t}},68708:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(32639),a=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,n.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const n={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))n[e]=S(...i.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,n]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==n&&!0!==i?.assignNullish||(e[r]=n));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,s.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function n(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:S(i,t)}for(const r of i){const[i,o]=(0,c.splitFirst)(r,"."),a=b(t,i);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&n(r,e(t[r],...i));return r},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const n=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(n)?void 0:{key:n[0].key,value:(0,r.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(i,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,o.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>r(this.a,e,t,i)))))))}}function n(e){return e instanceof r||e===t.None}function s(e){return n(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=n,t.opt=s},39926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),n=i(54993),s={};function o(e,t){if(t<1)return"";if(!(0,r.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),n=i(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,s=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==s&&"symbol"!==s)){const r=(0,n.toS)(e),s=(0,n.toS)(i),o=r.localeCompare(s);return r[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==s?a.indexOf(r)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const n of(0,r.toA)(await e))if(null!=n){const e=await n;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),n=i(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return null==i||0===i.length?s(e,t):a(e,t,1,i)[0]}function a(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(r??[]);if(t===e&&0===n&&0===o.size&&1===i)return[e];const a=n-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of a(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},5670:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),n=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),r=o(t);return null==i||null==r?void 0:i>r?1:i{const i=o(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),n=i(17586),s=i(22573),o=i(96249),a=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,a.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),n=(0,c.toS)(t);return r.length===n.length&&(r===n||r.toLowerCase()===n.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const r=i?.maxLineLen??80,n=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),n).trim()).length<=r)return[t];const s=S(t," ",r);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),i)];{const r=t.indexOf(" ",n.length+1);return r>0&&r{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),n=i(68708),s=i(42279),o=i(83104),a=i(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,i(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,i(t))}catch(e){n&&(n=!1,r(e))}finally{clearTimeout(s)}}))}async function c(e,t,i=!0){const n=await u(e,t,i);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?o.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{r(await i())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),r(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(n)+")");return c(e,n,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,s.tot)(i);const n=await u(e,t,r);return n===o.Timeout?(0,s.tot)(i):n}},42279:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),n=i(22573),s=i(54993);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,n.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,n.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),n=i(30301),s=i(31586),o=i(46891),a=i(50989),l=i(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,s.isNumber)(r)&&(i+=r/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),n=Math.pow(10,3*r),o=d[r];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),n=Math.pow(2,10*r),o=h[r];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},65812:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),n=i(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),n=i(23541),s=i(59455),o=i(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,r.compact)((0,s.toA)(e).map(a))}},54993:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,r.stringify)(e)}}t.toStr=s},90858:e=>{e.exports=require("@iarna/toml")},58587:e=>{e.exports=require("batch-cluster")},6858:e=>{e.exports=require("commander")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},57272:e=>{e.exports=require("plist")},57160:e=>{e.exports=require("punycode.js")},38064:e=>{e.exports=require("semver")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},40610:e=>{e.exports=require("node:dns")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},77030:e=>{e.exports=require("node:net")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},53916:e=>{e.exports=require("node:path/posix")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")},16928:e=>{e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__={},exports;exports=__webpack_exports__,Object.defineProperty(exports,"__esModule",{value:!0}),__webpack_require__(75631),module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/logtail.js b/bin/logtail.js index c64cccc..b2500f9 100755 --- a/bin/logtail.js +++ b/bin/logtail.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={37975:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const i=r(1708),n=r(22573),s=r(38639);function o(){return(0,s.toNotBoolean)(i.env.PS_LOG_COLOR)??(!(0,n.blank)(i.env.NO_COLOR)||["dumb","unknown"].includes(i.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(r){return l()?`[${e}m${r}[${t}m`:r}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const i=r(19851),n=r(7282),s=r(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,i.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,i.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const i=r(40958),n=r(36783),s=r(76790),o=r(22573),a=r(50357),l=r(98553),u=r(55835),c=r(31586),d=r(68708),h=r(34666),f=r(59455),m=r(84885);var g=r(40958);function p(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,r=i.primitiveValueOfOrElse){const n=new Set(t.map(r));return e.filter((e=>n.has(r(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],r=e.lastIndexOf(t);return[{t,count:r+1},...v(e.slice(r+1))]}function w(...e){const t=[],r=Math.max(...e.map((e=>e?.length??0)));for(let i=0;ie?.[i])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function E(e,t){return(0,i.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,r){return C(e,t,r).index}function C(e,t,r){if((0,i.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let i=0;ie.slice(r,r+t)))}async function x(e,t){return(0,i.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return g.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return g.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return g.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=p,t.mapAllDefined=function(e,t){return p(e)?t(e):void 0},t.mapAll=function(e,t){return p(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const r of(0,f.toA)(e))if(null!=r&&!0===await t(r))return r},t.findLastAsync=async function(e,t){for(let r=(e=(0,f.toA)(e)).length-1;r>=0;r--){const i=e[r];if(null!=i&&!0===await t(i))return i}},t.first=function(e,t){if(null!=e)for(const r of(0,f.toA)(e))if(null!=r){const e=t(r);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null!=i){const e=await t(i,r);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,i.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,r){for(let i=r;i<=e.length-1;i++)if(t(e[i]))return i},t.findLast=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},t.findLastIndex=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},t.concat=function(...e){const t=[];for(const r of e)if(Array.isArray(r))for(const e of r)null!=e&&t.push(e);else null!=r&&t.push(r);return t},t.moveToEnd=function(e,t){return(0,i.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const r=e[t];if(null==r)return e;e.push(r);for(let r=t;r(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const r=e.findIndex(t);return r>=0?e.splice(r,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,i.uniqBy)(e,t),e)},t.partition=function(e,t){const r=[],i=[];let n=0;for(const s of e)(t(s,n++)?r:i).push(s);return[r,i]},t.isUniq=function(e){return e.every(((t,r)=>e.indexOf(t)===r))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,i.compact)((0,i.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),r=[];return(0,c.times)(t,(t=>e.map((e=>r.push(e?.[t]))))),r},t.unFlatZip=function(e,t){const r=e.length/t;if(r!==Math.round(r))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const i=(0,c.times)(t,(()=>new Array(r)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=E,t.least=function(e){return E(e,(e=>e))},t.greatestBy=function(e,t){return(0,i.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const r=C(e??[],t,h.lt);return null==e||null==r||r.index<0||null==r.value?void 0:{result:e[r.index],index:r.index,value:r.value}},t.reverse=function(e){const t=[];for(let r=e.length-1;r>=0;r--)t.push(e[r]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(r(s)));return n},t.collectBatchedAsync=async function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(await r(s)));return n},t.contextFilter=function(e,t){let r;return e.filter(((e,i)=>(0,d.tap)(t(e,i,r),(t=>{t&&(r=e)}))))},t.clusterSome=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.some((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterEvery=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.every((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterAsync=async function(e,t){const r=[];e:for(const i of e){for(const e of r)if(null!=i&&await x(e,(e=>t(i,e)))){e.push(i);continue e}null!=i&&r.push([i])}return r},t.someAsync=async function(e,t){if(null!=e)for(let r=0;r=0&&!0===(0,u.map)(e[i],(e=>r(e,i))))return i}{const i=t+n;if(ie+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,r){return e.lengthr))),e}},36557:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=r(77988),l=o(r(1708)),u=r(19851),c=r(42659),d=r(55835),h=r(31586),f=r(85556),m=r(54993),g=r(50213),p=r(79089),y=r(45255),v=r(25764),w=r(38836),S=r(99331),b=r(95937),P=r(98314),_=r(38835),E=r(70025),M=r(8769),C=r(43334),T=r(95402),x=r(28874),D=r(63870);class k extends w.EndableWrapper{constructor(e,t,r=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,i,"m",n).call(this)),r,"worker"===e?(0,D.commandTimeoutMs)():y.ShortCommandTimeoutMs),i.add(this),this.t=t;const o=t;o.on("childStart",(async r=>{null!=r.pid?(this.logger.info("Started child process",{pid:r.pid}),(0,p.renice)(r.pid).catch((e=>this.onError("renice failed",e))),(0,T.addPid)({pid:r.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,r,i)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&T.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,E.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=k,i=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(C.isWin?3:1)*c.minuteMs,maxTasksPerProcess:x.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:x.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:x.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,g.mkLogger)(t))),spawnTimeoutMillis:(0,D.commandTimeoutMs)(),taskTimeoutMillis:x.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=r(92460),d=r(31586);class h{constructor(e){if(i.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,r;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,i,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,r;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,i,"m",a).call(this,0,(e=>{var t,r;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(r=u(this,s,"f"),--r),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,i,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const r=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=r}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const i=r(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:r}of n)if(o(e,t))return e.subarray(t.length).toString(r);return e.toString()}function o(e,t){return t.every(((t,r)=>e[r]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,i.toS)(e)},t.bufferStartsWith=o},9092:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,r]of e)this.set(t,r)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const r=this.normalizer(e);return null!=e&&null!=r&&this.store.set(r,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=r(40958),a=r(23838),l=s(r(68708)),u=r(59455),c=r(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const r of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(r,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const r=this.lookup(e);if(null!=r)return r;let i,n=-1;for(const[r,s]of this.m.entries()){const o=(0,c.diceCoeff)(r,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(i=e,n=o)}}return i}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),r=this.m.get(t);if(null!=r){for(const e of r)delete this.obj[e];this.m.delete(t)}return r}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const i=r(76790),n=r(31586),s=r(68708),o=r(54993),a=r(82647),l=r(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const r=this.get(e)+t;return 0===r?this.m.delete(e):this.m.set(e,r),r}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,r]of this.m.entries())e[(0,o.toS)(t)]=r;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,i.sortBy)([...this.entries()],(([t,r])=>[-r,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,r]of(0,i.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,r);return e}addAll(e){for(const[t,r]of e.entries())this.incr(t,r);return this}get toS(){return(0,i.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let r=0;for(const[i,n]of this.m.entries()){const s=e(i);t.fill(s,r,r+n),r+=n}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const i=r(19851),n=r(72993),s=r(45969),o=r(43334);t.EditionType=(0,i.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,i.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const i=r(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),r=t-this.ts;this.ts=t,(0,i.map)(this.listener,(t=>t(e,r))),r>2&&this.l.log(r>500?"warn":r>100?"info":"debug",e,{elapsedMs:r})}},t.elapsed=function(e){const t=Date.now(),r=e();return{elapsedMs:Date.now()-t,result:r}},t.thenElapsed=async function(e){const t=Date.now(),r=await e;return{elapsedMs:Date.now()-t,result:r}}},23467:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const i=r(50357),n=r(55835),s=r(68708);var o=r(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,i.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,i.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,i.eql,(()=>!1))},t.eqlPicked=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))},t.eqlOmit=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.omit)(e,...r),(0,s.omit)(t,...r))},t.eqlAsyncPicked=async function(e,t,...r){return(0,n.map2Or)(await e,await t,((e,t)=>(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))),(()=>!1))}},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(31586),a=r(54993),l=r(77377),u=r(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const r of this.expireListeners)r(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[i.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const r of this.expireListeners)r(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const r of this.expireListeners)r(e,t)}const r=this.priorCache[e];if(void 0!==r&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,r)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const r=this.currentCache[t]??this.priorCache[t];null!=r&&e(t,r)}}deleteIf(e){for(const t of this.keys()){const r=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=r&&e(t,r)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const r=t();return this.set(e,r),r}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=r(31586),d=r(85556),h=r(54993),f=r(54557),m=r(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,i.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,i,l(this,i,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,i,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,r,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(r=l(this,n,"f"),++r),"f"),c.promise):(u(this,i,(o=l(this,i,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,i,(a=l(this,i,"f"),++a),"f"),c}get(e){var t,r;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,i,(r=l(this,i,"f"),++r),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,i,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const r=this.get(e);if(null!=r){if(r instanceof Error)throw r;return r}return this.set(e,t())}getOrSetAsync(e,t){const r=(0,h.toS)(e);{const e=this.get_(r);if(null!=e)return e instanceof m.Deferred?e.promise:e}const i=new m.Deferred(this.opts.name).observe(t());return this.cache.set(r,i),(0,c.gt0)(this.opts.timeoutMs)&&i.setTimeout(this.opts.timeoutMs),i.promise.then((e=>{this.set(r,e)}),(e=>{var t,i;this.cache.set(r,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(i=l(this,a,"f"),++i),"f")})),i.promise}},i=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class i{constructor(e){this.maxSize=e,this[r]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(r=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=i},53507:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(31586),a=r(68708),l=r(50213),u=r(68852),c=r(81168),d=r(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,i.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,r=!0){return new m(e,t,r).entries};class m{constructor(e,t,r=!0){this.warnIfMissingHeaders=r,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const i=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,i).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let r=e;r!==t;t>e?r++:r--)if(this.blankColumns.has(r))return r;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),r=[];let i,a=0;for(;null!=(i=t.exec(this.headerRow));){const l=this.headerRow.substring(a,i.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:i.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(i.index,t.lastIndex),d=i.index+((0,c.indexOfNonSpace)(u)??0),h=i.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),g=e.find((e=>e.text===m));if(null==g||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:i,left:d,right:h});else{const e=(0,n.last)(r);if(r.push(g),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=g.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,i.index-((0,c.lastIndexOfNonSpace)(l)??l.length));g.leftIdx=g.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),g.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(r);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),r}}t.Fixed=m},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const i=r(51455),n=r(98553);var s=r(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const r=(0,n.parseJSON)(e);return null==r?void 0:t(r)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,i.readFile)(e)).toString())}},19851:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=r(57975),a=r(40958),l=r(50357),u=r(31586),c=r(65812),d=r(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),i.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,i,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const r=await e,i=await t;if(!(0,l.eql)(r,i))for(const e of this.watchers)e(i);null!=this.ttlMs&&this.ttlMs>0&&void 0!==i&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(42659),a=r(50213),l=r(81168),u=r(5916),c=r(56519),d=r(84777),h=r(44198),f=r(6012),m=r(43334),g=r(24399),p=r(63870);t.DefaultLocale="en";const y=(0,i.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?E():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,p.commandTimeoutMs)()}),t.envLocale=(0,i.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const r=w.exec(e.trim())?.groups;return null==r?void 0:(0,n.compact)([r.lang,r.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(g.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function E(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=E,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const i=r(48161),n=r(1708),s=r(45599),o=r(68708),a=r(50213),l=r(88158),u=r(96175),c=r(23560),d=r(84968),h=r(37805),f=r(9727),m=r(3790),g=r(29325),p=r(43334),y=r(28874);t.logStartup=(0,s.defer)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:n.argv,arch:(0,i.arch)(),platform:(0,i.platform)(),os:(0,u.osFullName)(),isPacked:(0,g.isPacked)(),isElectron:p.isElectron,versions:(0,o.pick)(n.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:n.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const i=r(19851),n=r(32105),s=r(14593);t.rootLoggers=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},9103:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const i=r(98553),n=r(54557);t.memoize=function(e,t){let r=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return r++,s.getOrSet((0,i.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,i.stringify)(e)),o.size=()=>s.size,o.callCount=()=>r,o}},7282:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=i(r(1708)),s=r(38639),o=r(54993),a=r(19851),l=r(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(55835),a=r(31586),l=r(39926),u=r(54993),c=r(20014);var d=r(31586);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,r){return(0,o.orElse)(h(e,t),r)},t.mapGte0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>=0?t(r):void 0},t.mapGt0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>0?t(r):void 0},t.mapGt0=function(e,t){const r=(0,a.toInt)(e);return null!=r&&r>0?t(r):void 0},t.map2Gt0=function(e,t,r){const i=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=i&&i>0&&null!=n&&n>0?r(i,n):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(f.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(m(e))}function p(e,t){if(null==e||null==t)return;const r=[e,t].map((e=>e.toString(2))),i=Math.max(...r.map((e=>e.length)));return r.map((e=>(0,l.leftPad)(e,i,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let r=0;for(let i=0;ie/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,r){this.store[e*this.columns+t]=r}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(p(e,t),(([e,t])=>(0,i.count)([...e],((e,r)=>e!==t.charAt(r)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(p(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,i.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,r){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let i=0;const n=r*e.length;for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const i=r(40958),n=r(42659),s=r(96249),o=r(55835),a=r(31586),l=r(68708),u=r(34666),c=r(41583),d=r(48884),h=r(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const r={};for(const[i,n]of(0,l.entries)(e)){const e=t(i,n);null!=e&&(r[i]=e)}return r}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const r of e){const e=r();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(r=>t(r,e[r])?e[r]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,r){if(null!=e)return t(e);throw new Error(r)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,i.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[r,i]of m(t))null==e[r]&&(e[r]=i);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[r,i]of(0,l.entries)(t))null==e[r]&&(e[r]=i);return e},t.pickMap=function(e,t,r){const i={};for(const n of t)i[n]=r(n,e[n]);return i},t.mapEntries=g,t.mapNullEntries=function(e,t,r){const i={};let n=0;for(const s of(0,l.keys)(e))if(i[s]=t(s,e[s]),n++,(0,a.gt)(n,r))break;return i},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const r={};for(const i of(0,h.sortIgnoreCase)((0,l.keys)(t)))r[i]=e(t[i]);return r}return t},t.deepDelete=function e(t,...r){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...r))):g(t,((t,i)=>r.includes(t)?void 0:e(i,...r)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const r of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[r])return e[r]}},t.pairToObject=function(e,t){const r={};return r[e]=t,r},t.zipPojos=function(...e){const t={};for(const r of(0,i.uniq)((0,s.flatten)(e.map(l.keys))))t[r]=e.map((e=>e?.[r]));return t}},96175:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const i=r(31421),n=r(73024),s=r(48161),o=r(19851),a=r(22573),l=r(42659),u=r(55835),c=r(51926),d=r(54993),h=r(48884),f=r(50213),m=r(6012),g=r(45969),p=r(43334),y=r(76280),v=r(30933),w=(0,o.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return k();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,g.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function _(){return"ubuntu"===(0,t.osDistributionLinux)()}function E(){return"fedora"===(0,t.osDistributionLinux)()}function M(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(p.isLinux)for(const e of b)try{const t=(0,n.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>p.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=_,t.hasApt=function(){return P()||_()},t.isFedora=E,t.isAlpine=M;const C={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},T={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function x(e,t){const[r,i]=function(e){return e.split(".").slice(0,2)}(e),n=t[r];return(0,c.isString)(n)?n:n?.[i]}const D=(0,o.lazy)((()=>(0,i.execSync)("sw_vers -productVersion").toString().trim()));function k(e=D()){try{return(0,a.mapNotBlankOr)(function(e=D()){return x(e,C)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":x(e,T);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=k,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(p.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(p.isMac){const e=D();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(p.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(_())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(E())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(M())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},12801:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=i(r(48161)),s=r(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const i=r(41400),n=r(56409),s=r(31586),o=r(22911),a=r(73614),l=r(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:r,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const g=[];function p(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...i){f=!0,m=Date.now()+(0,s.max_)(t,r);const n=d=new o.Deferred(c);(0,s.gt0)(r)&&n.setTimeout(r);try{n.resolve(await e(...i))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),g.forEach((e=>e.resolve())),g.length=0}return n.promise}const w=(...e)=>{if(p()){if(!0===u)return null;const t=d?.promise;return h=e,(0,i.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return g.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>p(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const i=r(68708),n=r(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const r=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:r.push((0,i.pick)(n,"index","groups"));return r},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,r){const i=[];for(const t of e)try{i.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{i.push(s(t))}const n=0===i.length?t.NothingRegExp:i.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,r)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let r="",i=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(r+=t.source,i||(i=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):r+=s((0,n.toS)(t));return new RegExp(r,t??(i?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=i(r(48161)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(42659),u=r(41400),c=r(96249),d=r(31586),h=r(51926),f=r(54993),m=r(50213),g=r(12801),p=r(22277),y=r(84777),v=r(34102),w=r(43334),S=r(24399),b=r(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let E=!0;const M=(0,o.lazy)((()=>new p.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const r=(0,g.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=g.PriorityClassToNode[r]),E)try{return n.default.setPriority(e,t),t}catch(r){const i=-13===r?.errno||"EACCES"===r?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:i,error:r}),i)return;E=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&g.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,r):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,g.PriorityClassToPosix[r]??g.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+r),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=i(r(1708)),s=r(19851),o=r(40958),a=r(5670),l=r(54993),u=r(7282),c=r(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function g(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=g,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||g())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||g())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const i=r(59455);function n(e){return e instanceof Set?e:new Set((0,i.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,i.toA)(e.keys()).every((e=>t.has(e)))&&(0,i.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,r){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),r())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const r=n(t);return new Set([...e].filter((e=>r.has(e))))},t.diff=function(e,t){const r=n(t);return new Set([...e].filter((e=>!r.has(e))))}},19913:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const i=r(5670),n=r(57150),s=r(7282),o=r(23560),a=r(17181);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=i.ServiceNames.main);const t=o.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,a.setupLogger)(),(0,n.logStartup)())}},12089:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=r(98553),d=r(34666),h=r(54993),f=r(62344),m=r(56038);t.shim1=function(e){return new g(e.name,e.impl,e.cache,e.toKey)};class g extends f.ExtensibleFunction{constructor(e,t,r,o){super(),i.add(this),this.impl=t,this.cache=r,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,i,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,i,"m",o).call(this,e),(()=>u(this,i,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,i,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,i=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const i=r(42659);t.ShortCommandTimeoutMs=7*i.secondMs},92322:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=r(76790),o=r(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,i.set(this,[])}[(i=new WeakMap,Symbol.iterator)](){return n(this,i,"f")[Symbol.iterator]()}get length(){return n(this,i,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,r=n(this,i,"f").length-1;for(;t<=r;){const s=t+Math.floor((r-t)/2),o=this.valueOf(n(this,i,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:r=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,i,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:r}){if(t>=this.length)return[...n(this,i,"f")];const o=t=>t<0||t>n(this,i,"f").length-1?null:(r??this.diff)(n(this,i,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return n(this,i,"f").shift()}at(e){return(0,o.at)(n(this,i,"f"),e)}toA(){return[...n(this,i,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,i,"f").length-1){const e=[...n(this,i,"f")];return n(this,i,"f").length=0,e}return n(this,i,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,i,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const i=r(1708),n=r(82328),s=r(84542),o=r(95705),a=r(28874);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(i.stderr)||i.stderr.write(e)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},82328:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const i=r(1708),n=r(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(i.stdout)}},71567:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=i(r(1708)),s=r(22573),o=r(98553),a=r(23560),l=r(82328),u=r(38835),c=r(70025),d=r(95705);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:r,stream:i}){if(null==i||(0,d.streamEnded)(i))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);i.write(n+"\n"),(0,a.isWorkerService)()&&null!=r&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?i.write(u.FailStr+"\n"):i.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const r of e)r.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(55835),a=r(31586),l=r(39926),u=r(34666),c=r(51926),d=r(59455),h=r(54993),f=r(48884),m=r(68852),g=r(38835);var p=r(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return p.splitFirst}});var y=r(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=r(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,r){if(0===r.length)throw new Error("rightPad() given empty pad");const i=String(e);return i+(0,l.padding)(r,t-i.length)},t.padReplace=function(e,t,r,i){return(0,c.strslice)(e,0,t)+(0,l.padding)(i,r)+(0,c.strslice)(e,t+r)},t.contains=function(e,t,r){return(0,h.toS)(e).indexOf((0,h.toS)(t),r)>-1},t.countChars=function e(t,r,i=0){if(null==r||0===r.length)return 0;const n=t.indexOf(r,i);return-1===n?0:1+e(t,r,n+r.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,r){const i=Math.min(Math.ceil(e.length/t),r??e.length)-1;return i<=0?[e]:[...(0,a.times)(i,(r=>e.slice(r*t,(r+1)*t))),e.slice(i*t)]},t.spliceCapture=function(e,t){const r=t.exec(e);if(null==r||null==r[1])return;const i=r[0].indexOf(r[1])+r.index;return{captured:r[1],uncaptured:e.substring(0,i)+e.substring(i+r[1].length),unmatched:e.substring(0,r.index)+e.substring(r.index+r[0].length),matchedIndex:i}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,r={}){if(null==t)return e;const i=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(i.slice(-n.length),n,r)?i.slice(0,-n.length):i},t.gist=function(e,t=80,r=80){const i=(0,h.toS)(e),n=i.length-(t+r);return n<=0?i:i.slice(0,t).trim()+" …(+"+n+" chars)…"+i.slice(-r).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const r=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===r?e.localeCompare(t):r}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,i.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,o.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const r=S(e.cmp[0],t.cmp[0]);return 0!==r?r:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,i.isEmpty)(e)||(0,s.blank)(t))return;for(const r of e)if((0,c.equalsIgnoreCase)(r,t))return{index:0,match:r};for(const r of e){const e=t.indexOf(r);if(e>=0)return{index:e,match:r}}const r=t.normalize();for(const t of e){{const e=r.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=r.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=r.toLowerCase(),i=e.toLowerCase(),n=t.indexOf(i);if(n>=0)return{index:n,match:i}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function E(e){return _.reduce(((e,[t,r])=>e.replace(t,r)),e).normalize()}t.dumbquote=E;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(E(e))&&(e=e.slice(1,-1).trim())),e};const C=/^['‘’].*['‘’]$/,T=/^["“”„«»〃].*["“”„«»〃]$/;function x(e,t){const r=D(e,t);return(0,f.flatZip)(r.nonSeparators,r.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+g.NonRetriableErrorFlag);const r=[],i=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,r.push(e.substring(s,n.index)),i.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),C.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const r=(0,i.compactBlanks)(e),n=Math.max(...r.map((e=>e.length)));for(let e=0;e(0,o.map)(r[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,i.compactBlanks)(e)),r=t.filter(((e,r)=>!P(t[r+1],e)));return(0,n.sortBy)(r,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const r=Math.min(e.length,t.length);for(let i=0;i4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const r=new Set;for(const i of(0,d.toA)(e))if(null!=i&&!(0,s.blank)(i))for(const e of i.split(t))(0,s.blank)(e)||r.add(e);return[...r].join(t)},t.dedupeNeedle=function(e,t,r){if((0,s.blank)(t))return e;const i=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>i.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(r)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const i=r(54993);function n(e){return(0,i.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>"_"+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>" "+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=i(r(77598)),s=r(73913),o=r(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,r=o.Radix58,i=224){return r.encodeBuffer(a(e,i)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,r=o.GeoRadix,i=224){return l(e,t,r,i)}},94863:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const i=r(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,i.toS)(e).toLowerCase().normalize()}},96859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(31586),a=r(39926),l=r(51926),u=r(54993),c=r(55222),d=r(97352),h=r(88158),f=r(77377),m=r(81168);function g(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const r=new d.Array2D(e.length);let i=0,n="";for(let s=0;s=i&&(i=r.get(s,o),n=(0,l.substr)(e,s-i+1,i)));return n}function p(e,t){if(null==e||null==t)return;if(e===t)return 0;const r=y(e,t);if(null!=r)return r;const i=e.normalize(),n=t.normalize();return e!==i||t!==n?y(i,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,r,i)=>r===t.charAt(i)?e:e+1),0)}function v(e,t){const r=e.toUpperCase().normalize(),i=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>r===i?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(r),t=w(i);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,r)=>e+t[r+1]))}function S(e,t){const r=(0,f.intersection)(e,t),n=[];return r.forEach((r=>{const s=Math.min((0,i.count)(e,(e=>e===r)),(0,i.count)(t,(e=>e===r)));(0,o.times)(s,(()=>n.push(r)))})),n}function b(e,t,r){const n=(0,i.commonPrefixLength)(e,t);return r((0,l.strslice)(e,n))-r((0,l.strslice)(t,n))}function P(e){const t=(0,i.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[r,i]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(r,i,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:g(e,t).length/Math.max(e.length,t.length)},t.lcs=g,t.hamming=p,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const E=/[^\da-z]+/gi;function M(e,t){const[r,i]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(E,"").toLowerCase()));return b(r,i,(e=>c.RadixAlphaNum.decode(e)))}function C(e,t){let r;for(let i=Math.max(e.length,t.length);i>=0;i--){const n=(0,o.mapNumericOr)(e.charCodeAt(i),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(i),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);r=null==r?a:(r+a)/2}return r}t.radixDiff=M,t.str=function(e,t){return{pref:(0,i.commonPrefixLength)(e,t),ham:p(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,i.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=C,t.paddedPositionalDiff=function(e,t,r=8){return C((0,a.leftPad)(e,r," "),(0,a.leftPad)(t,r," "))}},84885:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const i=r(98553),n=r(88158);t.stringifySorted=function(e){return(0,i.stringify)((0,n.sortedKeys)(e))}},22277:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=r(73614);class u{constructor(e,t=!1){i.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,i,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,i,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const r=this.delegate.get(e);return null==r||a(this,i,"m",n).call(this,e,r)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,r]of this.delegate)a(this,i,"m",n).call(this,t,r)||e(t,t,this)}has(e){return null!=e&&!a(this,i,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield[t,t])}()}toA(){return a(this,i,"m",s).call(this),[...this.delegate.keys()]}[(i=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const r=t<=Date.now()-this.ttlMs;if(r){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return r},s=function(){for(const[e,t]of this.delegate)a(this,i,"m",n).call(this,e,t)}},94174:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(38639),c=r(31586),d=r(50213),h=r(45255),f=r(84777),m=r(96706),g=r(43334),p=r(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>g.isWin?p.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>g.isWin?g.isWin?p.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const i=r(42659),n=r(55835),s=r(31586),o=r(97790),a=r(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const r=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(r))return;const[o,a,u,c,d,h,f]=r,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*i.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+i.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class r extends Error{}t.AbortError=r},76740:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=r(45599),l=r(56409),u=r(73568);t.Abortable=class{constructor(){this._aborted=!1,i.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,i,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,i,"f")&&clearTimeout(s(this,i,"f")),o(this,i,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},i=new WeakMap,n=new WeakMap},22911:function(e,t,r){var i,n,s,o,a,l,u,c,d,h,f,m,g=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(r(87997)),w=y(r(57975)),S=r(45599),b=r(26905),P=r(55835),_=r(31586),E=r(68708),M=r(20214),C=r(57153),T=r(85556),x=r(50213),D=r(70025),k=r(95937),O="TIMEOUT",I=(0,S.defer)((()=>(0,x.mkLogger)("async.Deferred")));class L{static async*toAsyncIterable(e,t){const r=[...e].reverse(),i=(0,_.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=i&&r.push(i);;){for(let i=r.length-1;i>=0;i--){const n=r[i];if(n.isSettled){if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});r.splice(i,1),yield n.value}}if(r.every((e=>e.name===O)))break;try{await Promise.race(r)}catch{}}i?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var r,m,y;i.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,C.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(p(r=n,n,(y=g(r,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{p(this,u,e,"f"),p(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return g(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:g(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,E.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return g(this,o,"f")}get elapsedMs(){return(g(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,i=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=g(this,h,"f")&&(v.default.clearTimeout(g(this,h,"f")),p(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(p(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),g(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return g(this,a,"f")===C.PromiseStates.pending}get value(){return this.isResolved?g(this,l,"f"):void 0}get error(){return g(this,d,"f")}get isSettled(){return g(this,a,"f")!==C.PromiseStates.pending}get isResolved(){return g(this,a,"f")===C.PromiseStates.resolved}get isRejected(){return g(this,a,"f")===C.PromiseStates.rejected}get settledMs(){return null==g(this,o,"f")?void 0:g(this,o,"f")-this.startedAt}resolve(e){return g(this,i,"m",m).call(this,(()=>{p(this,a,C.PromiseStates.resolved,"f"),p(this,l,e,"f"),g(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return g(this,i,"m",m).call(this,(()=>{p(this,d,t,"f"),p(this,a,C.PromiseStates.rejected,"f"),g(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=L,n=L,m=function(e){if(g(this,a,"f")===C.PromiseStates.pending){(0,P.map)(g(this,h,"f"),v.default.clearTimeout),e(),p(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:g(this,l,"f")});return this},s={value:0}},27395:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const i=r(19851),n=r(40958),s=r(42659),o=r(23838),a=r(13538),l=r(50213),u=r(7282),c=r(97352),d=r(77740),h=r(25764),f=r(99331),m=r(73614),g=(0,i.lazy)((()=>(0,l.mkLogger)("async.Endable"))),p=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const r=await e;if(null==r||!0===r?.ended)return;const i=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,r.endTimeoutMs,y);g().trace(r.name+" ending...",{timeoutMs:i});try{await(0,a.thenOrTimeoutError)(r.end(),i,(0,u.isTest)())}catch(e){try{g().warn(r.name+".end() failed",e)}catch{}}}function w(){p.filterInPlace(((e,t)=>!0!==t.ended)),g().debug("vacuumEndables()",p.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),p.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,i.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;g().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const r=p.get(t)??[];(0,n.isNotEmpty)(r)&&(g().debug("endEndables(): ending "+t),await Promise.allSettled(r.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,n.compact)(p.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const r=p.get(t)??[];e[t]=r.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,r){var i,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=r(87997),h=r(55835),f=r(31586),m=r(68708),g=r(25764),p=r(38836),y=r(99331);class v extends p.EndableWrapper{constructor(e){super(e.name,(()=>u(this,i,"m",o).call(this)),e.rank??g.EndableRanks.first,e.endTimeoutMs),i.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,r=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!r&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,i,"m",o).call(this);const h=()=>{u(this,i,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,i,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,i=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const i=r(50989);t.EndableRanks=(0,i.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=r(19851),l=r(45599),u=r(56409),c=r(50213),d=r(27395),h=r(25764),f=r(99331),m=r(56519);t.EndableWrapper=class{constructor(e,t,r=h.EndableRanks.first,o){this.endTimeoutMs=o,i.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(r,this)}setName(e){o(this,i,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,i,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},i=new WeakMap,n=new WeakMap},99331:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const i=r(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,i.isTest)()?e:e||n}},45608:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=i(r(1708)),s=r(22573),o=r(45599),a=r(37975),l=r(50213),u=r(71567),c=r(57159),d=r(57902),h=r(28874),f=r(27395),m=r(99331),g=r(56038),p=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(g.PromiseTimer.instance().report())}));async function v(e){p().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const r=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==r.errno||!0===r.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const i=(0,s.toNotBlank)(e?.reason)??r.toString();for(const e of t.onFatalHandlers)await e(i)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(r=>{v({reason:`${e}:${t}`,status:0,error:r})}))}))},5916:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=r(45599),f=r(50357),m=r(31586),g=r(41583),p=r(62344),y=r(50213),v=r(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:r,timeoutMs:i}){return new S(e,t,r,i)};class S extends p.ExtensibleFunction{constructor(e,t,r,l){super(),i.add(this),this.later=e,this.desc=t,this.ttlMs=r,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,i,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,i,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,i,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=async function(e,t){var r;try{const r=await t;if(!(0,f.eql)(e?.value??await(e?.promise),r))for(const e of c(this,a,"f"))await e.onChange(r)}catch(e){const t=(0,g.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(r=c(this,s,"f"),++r),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,i,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},56519:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const i=r(40958),n=r(76790),s=r(38639),o=r(42659),a=r(41400),l=r(31586),u=r(20214),c=r(13538),d=r(42279),h=r(32639),f=r(59455),m=r(41583),g=r(48884),p=r(50213),y=r(88158),v=r(15674),w=r(42638);var S=r(20214);async function b(e){if(null==e)return[];const t=(0,i.compact)(await e);return(0,i.isEmpty)(t)?[]:(0,i.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:r,timeoutMs:n}){const s=[];for(const o of(0,i.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(r(o),n):r(o));null!=e&&s.push([e,o])}catch(t){(0,p.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:r,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,i.compact)(await e);if((0,i.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:r,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(r,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(r,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,p.mkLogger)(r).warn("failed to apply",{ea:e,error:t})}})));return(0,i.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,r){const i=[];for(const n of(0,g.batches)((0,f.toA)(await e),t)){const e=await b(n);i.push(...await b(r(e)))}return i},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const r of(0,i.compact)(e)){const e=await r();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;if(null!=e)if(Array.isArray(e))for(const r of e){const e=await r;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;null!=e&&t.push(e)}return(0,i.uniq)(t)},t.asyncFind=async function(e,t){for(const r of e)if(await t(r))return r},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:r,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,i.compact)(t),f:r,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const r=await E({name:"partitionAsync",arr:e,f:t});return[r.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),r.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,r=(e=>console.error(e)),i=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,i)}catch(e){r((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),r=(()=>{})){let i,n=null;try{i=await((0,h.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await r(n??i)}catch{}if(null!=n)throw n;return i},t.thenNot=async function(e,t=!0){if(null==e)return t;const r=await e;return null==r?t:!(0,s.isTrue)(r)},t.thenMap2=async function(e,t,r){const i=await e;if(null==i)return;const n=await t;return null!=n?r(i,n):void 0},t.thenMapOr=async function(e,t,r){const i=await e;if(null==i)return r();const n=await t(i);return null==n?r():n},t.thenMap2Or=async function(e,t,r,i){const n=await e;if(null==n)return i();const s=await t;if(null==s)return i();const o=await r(n,s);return null==o?i():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null==i)continue;const e=await t(i,r);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const r of e){const e=await r();if(null!=e){const r=await t(e);if(null!=r)return r}}},t.firstResolvedDefinedPromise=async function(e,t){for(const r of e)try{const e=await r();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const r of t)try{const t=await r();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:r}){const i=await E({name:e,arr:t,f:r});return(0,n.sortBy)(i,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const i=r(19851),n=r(40958),s=r(76790),o=r(42659),a=r(49769),l=r(31586),u=r(68708),c=r(42279),d=r(41583),h=r(22454),f=r(14121),m=r(50213),g=r(7282),p=r(34102),y=r(82647),v=r(25764),w=r(38836),S=r(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,r){const i=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-i)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-i;return r?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),r?.((0,d.toErr)(t),Date.now()-i),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),r=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),i=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",r.stats()],...i])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:r.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:(0,l.mapFinite)(r.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:r.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:{sumSec:(0,l.sigFigs)(r.sum/o.secondMs,3),...(0,u.omit)(r.stats(),"sum")}})),{})}}function _(e,t,r){return P.instance().time(e,t,r)}function E(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,i.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.isTest)()&&(0,p.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const r=Date.now(),i=t();return E(e,Date.now()-r),i},t.pushTime=E,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,r){return(0,i.lazy)((async()=>_(e,t)),r)}},42638:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(r(66261)),m=r(40958),g=r(55835),p=r(31586),y=r(42279),v=r(54993),w=r(89788),S=r(82647),b=r(15674),P=r(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){i.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,p.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:r,serialId:n}){const s=d(this,i,"m",l).call(this,{name:e,l:t,payload:r,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const r=t.map((t=>d(this,i,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(r)}serial(e,t,r){return this.enqueue({name:e,l:t,serialId:e,payload:r})}push(e,t,r){return d(this,i,"m",u).call(this,new P.Deferred(e,{payload:r}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),r=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,p.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=function({name:e,l:t,payload:r,serialId:i}){const n=new P.Deferred(e,{payload:r,serialId:i});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const r=Date.now();return this.lastWorkTs=r,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-r),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const r=new _(e);return()=>r.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:r}){return new _(e,(0,g.map)(r,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class r extends Error{}t.RedoableError=r},4867:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const i=r(40958),n=r(34546),s=r(41400),o=r(31586),a=r(83104),l=r(85556),u=r(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:r}){let a=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,r?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:r}){let l=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,r?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let r=e=>null;t.setTimeoutHandler=function(e){r=e},t.onTimeout=function({soft:e}={}){r(e)}},73614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const i=r(87997);t.setUnrefTimeout=function(e,t,...r){return(0,i.setTimeout)(e,Math.round(t),...r).unref()},t.setUnrefInterval=function(e,t,...r){return(0,i.setInterval)(e,Math.round(t),...r).unref()}},31562:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const i=r(38639),n=r(42659),s=r(41400),o=r(32639),a=r(31586),l=r(45255),u=r(95937);async function c(e,{timeoutMs:t,intervalMs:r,acceptable:i,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const i=r??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(i,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:i.isTrue,timeoutResult:!1})}},9727:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=i(r(1708)),s=r(45599),o=r(41400),a=r(50357),l=r(68708),u=r(48884),c=r(36638),d=r(44198),h=r(59958),f=r(96706),m=r(34102),g=r(19851),p=r(19043),y=r(66184),v=r(50213),w=r(7282),S=r(88158),b=r(45969),P=r(43334),_=r(28874),E=r(3790);function M(e){return C().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const C=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const r of t.names)e.add(r);for(const r of t.keys)e.add(r)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const T=["HOME","LANG","USER"],x=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],D=(0,g.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?T:x),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function k(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const r of(0,_.persistedSettings)()){const i=e?r.value:r.envValue;null==i||(0,a.eql)(i,r.defaultValue)||r.addToEnv(t)}return t}t.sanitizedEnv=(0,g.lazy)((()=>(0,l.filter)(n.default.env,(e=>M(e)||!(0,E.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=k,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:I({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function I({overrides:e,forceCLocale:r=!0,forWorker:i=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...D(),...r?(0,p.childProcLocale)():{},...k(i),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,E.isHiddenEnvKey)(e)?"(hidden)":t])),[r,i]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(r)),e.debug("non PS env:",(0,l.fromEntries)(i))}return n}t.childEnv=I},84777:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=i(r(31421)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(42659),c=r(98553),d=r(56409),h=r(31586),f=r(68708),m=r(51926),g=r(50213),p=r(7282),y=r(88158),v=r(79089),w=r(45255),S=r(22911),b=r(4867),P=r(73614),_=r(70025),E=r(57159),M=r(36868),C=r(66184),T=r(45643),x=r(95402),D=r(9727),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const r=e.pid;if(null==r||r<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(r===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(r===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+r+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,x.killPid)(r).catch((e=>{k().warn("endProcess(): kill("+r+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,p.isSingleSpecTests)())return!0;if(await(0,T.waitForPidExit)(r,t))return k().debug("endProcess(): exitted",O(e)),!0;{x.Pids.instance()?.onKill(r);const t=e.kill("SIGKILL");k().warn("endProcess("+r+") had to resort to SIGKILL",{killResult:t}),t||await(0,x.killPid)(r,!0).catch((e=>{k().warn("endProcess(): kill("+r+",true) failed: "+e)}))}return(0,T.waitForPidExit)(r,5e3)}function L(e,r,i,n=0){const o=new Date,a=[];return(0,v.niceable)(r,i)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,x.addPid)({pid:e.pid,cmd:r,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function F(e,t,r,i){const s=(0,D.spawnOptions)(i);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:r,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:r}),L(n.default.execFile(e,t,s),e,t,r)}async function A(e,t,r){const i=r.quiet??!1,n=r.ignoreStderr??!1,s=r.ignoreExitCode??!1,o=F(e,t,r.timeoutMs,(0,f.omit)(r,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===r.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],g=[],p=[],y=new S.Deferred(f);o.on("error",(e=>p.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>p.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>p.push(e))),o.stderr?.on("data",(e=>g.push(e))),o.stderr?.on("end",(()=>P.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:r.timeoutMs,halt:r.halt}),k().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt});const C=g.join("");(0,l.notBlank)(C)&&p.push(new Error(C)),!i&&(0,a.isNotEmpty)(p)&&k().warn(f+" resulted in errors:",p);const T=r.isIgnorableError??_.isIgnorableError,x=p.filter((e=>!0!==T(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:C}}catch(e){throw k().error("stdoutResult_() failed",e),await(0,x.killPid)(o.pid,!0),e}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,r,i){const s=(0,D.spawnOptions)(i);return k().debug("spawn()",{command:e,args:t,maxAgeMs:r}),L(n.default.spawn(e,t,s),e,t,r)},t.execFile=F,t.stdoutResult_=A,t.stdout_=async function(e,t,r){const i=await A(e,t,r);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(i.result),meta:{cmd:e,args:t,opts:r,result:i}})}},3790:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const i=r(22573),n=r(41400),s=r(19851),o=r(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,i.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},69554:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const s=r(6858),o=r(1708),a=r(37805),l=r(22573),u=r(55835),c=r(7282),d=r(19913),h=r(43334),f=r(41269),m=r(80061),g=r(94361);t.CLI=class{constructor(e,t,r){this.serviceName=e,this.args=t,this.additionalDescription=r,i.set(this,[]),(0,d.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return n(this,i,"f").push(...e),this}async parse(e=o.argv,t){let r=(0,m.addHelpFooter)(new s.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{r=r.arguments(e)}));for(const e of n(this,i,"f"))r=e.beforeParse(r);r.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":a.version)+")"),r.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,o.exit)(0)})),r.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=r.opts();for(const e of n(this,i,"f"))await(e.afterParse?.(d));return r}},i=new WeakMap},41269:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const i=r(1708),n=r(31586),s=r(51926),o=r(17344),a=r(37805),l=r(84542);function u(e,t){const r=t?.maxLineLen??(0,n.toInt)(i.env.maxLineLen)??i.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:r,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const i=r(1708),n=r(38639),s=r(17181),o=r(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,n.mapBoolean)(e.color,(e=>{i.env.PS_LOG_COLOR=String(e),o.Settings.logColor.envValue=e,(0,s.setupLogFormatter)()}))}}},94361:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const i=r(19851),n=r(40958),s=r(55835),o=r(31586),a=r(94174),l=r(44198),u=r(45969);function c(e,t,r){const i=(0,o.toGt0)((0,l.env)()[t]);return null==i||r.includes(i)?void 0:`WARNING: ${e} is running as ${r} but $${t}=${i}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,i.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},76596:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const i=r(51168),n=r(19851),s=r(22573),o=r(42659),a=r(55835),l=r(31586),u=r(68708),c=r(34666),d=r(50213),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,r){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=r}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const r=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),i=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(r,i)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),r=Date.now();return t<=r?0:t-r},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const i=r(22573),n=r(31586),s=r(54557),o=r(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,i.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,i.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const i=r(51168),n=r(40958),s=r(22573),o=r(42659),a=r(31586),l=r(51926),u=r(68852),c=r(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=i.Duration.fromISO(e);if(t.isValid)return t.toMillis();const r=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(r,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const r=(0,a.toFloat)(e);if(null!=r){if((0,s.blank)(t))return r;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*o.yearMs;case"weeks":case"week":case"w":return r*o.weekMs;case"days":case"day":case"d":return r*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return r*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return r*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return r*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return r;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,r=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const i=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const r=Math.floor(t/e.ms);t-=r*e.ms,r>0&&i.push(r+e.s)}return i.join(r)}},84248:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const i=r(50989);t.AutoVacuumModes=(0,i.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const i=r(50989);t.CheckpointTypes=(0,i.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const i=r(50989);t.RepairModes=(0,i.strEnum)("dump","recover")},34365:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const i=r(50989);t.SynchronousModes=(0,i.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(r(76760)),a=r(40958),l=r(22573),u=r(55835),c=r(72993),d=r(19851),h=r(97352),f=r(94174),m=r(44198),g=r(96706),p=r(8769),y=r(57159),v=r(70698),w=r(64680),S=r(29882),b=r(45969),P=r(43334),_=r(28874),E=r(41692),M=r(32774),C=r(80612),T=r(32551),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,g.getEnv)("TEMP"),(0,g.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const r of t)(0,l.blank)(r)||e.push({dir:(0,o.join)(r,".photostructure-cache"+x()),preexistingDir:r});return e}}function k(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:M.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(P.isWin?[(0,g.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,r=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return r.push(...D()),r}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,C.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,C.firstDir)({dirs:k(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,E.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(I)}));function I(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,p.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=I},46292:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const i=r(19851),n=r(45969),s=r(41692),o=r(32774),a=r(10924),l=r(84373),u=r(80612);t.configDir=(0,i.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const i=r(66430),n=r(45969),s=r(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,i.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=i(r(76760)),s=r(40958),o=r(72993),a=r(44198),l=r(96706),u=r(43334),c=r(80612),d=r(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const i=r(22573),n=r(96706),s=r(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,i.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const i=r(44652),n=r(40958),s=r(22573),o=r(66430);function a({dirs:e,desc:t}){for(const{dir:r,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(r)){if((0,o.isReadWriteableDirectorySync)(r))return r;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,i.mkdirpSync)(r),r}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const i=r(48161),n=r(76760),s=r(1708),o=r(19851),a=r(40958),l=r(68284),u=r(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,i.homedir)()}))},46296:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(55835),u=r(54993),c=r(72993),d=r(96706),h=r(45969),f=r(43334),m=r(32707),g=r(6707),p=r(49776),y=r(32774),v=r(80612),w=r(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,p.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,g.readTomlFileSync)((0,m.systemSettingsFile)()),r=(0,u.toS)(t?.logDir);return(0,a.notBlank)(r)?r:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const i=r(76760),n=r(19851),s=r(22573),o=r(44198),a=r(43334),l=r(24399),u=r(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,i.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const i=r(38639),n=r(7282),s=r(29325),o=r(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,i.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const i=r(38639),n=r(44198);t.doNotTrack=function(){return(0,i.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=i(r(73024)),s=r(76760),o=i(r(1708)),a=r(19851),l=r(40958),u=r(41400),c=r(68708),d=r(76850),h=r(7282),f=r(23560),m=r(32551),g=r(34102),p=r(53265),y=r(45969),v=r(59958),w=r(6012),S=r(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),r={...o.default.env};for(const i of e)try{const e=(0,d.debom)(n.default.readFileSync((0,p.resolve)(i))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,i]of(0,c.entries)(s))t.test(e)||(r[e]=i)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+i,e)}return r})),(0,u.later)((()=>{(0,g.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const i=r(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,i.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const i=r(50989);t.EnvKeys=(0,i.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const i=r(22573),n=r(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const r={};if((0,i.blank)(e))return r;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,i.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");r[t?e.toLowerCase():e]=o}}return r}},96706:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=i(r(1708)),s=r(19851),o=r(22573),a=r(38639),l=r(41400),u=r(40583),c=r(79840),d=r(83556),h=r(34102),f=r(44198),m=r(83373);function g(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=g,(0,l.later)((()=>{f.env.watchLater(g),(0,h.ee)().on("clearCache",g)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},98314:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const i=r(58587),n=r(19851),s=r(40958),o=r(22573),a=r(26905),l=r(96249),u=r(51926),c=r(23541),d=r(54993),h=r(89788),f=r(50213),m=r(81168),g=r(84542),p=r(41954),y=r(38835),v=r(70025),w=r(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,p.getErrorDescriptions)(e));const r=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,g.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(r)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const r=(0,s.uniqSubstrings)(b(e)),i=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(r.join(a.ErrorDelimiter)),i-o.length,n)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new i.Rate,t.fatalErrorRate=new i.Rate,t.internalErrorRate=new i.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const r=(0,d.toS)(t?.[e]);if((0,o.notBlank)(r))return r}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,r=256,i=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:r})+" at "+(0,a.shortStack)(e?.stack,i).join("; ")}},41954:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const i=r(40958),n=r(26905),s=r(55835),o=r(54993),a=r(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const r of e)(0,s.map)((0,n.errorErrno)(r),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(r),(e=>t.push(l[e]?.description)));return(0,i.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const i=r(40958),n=r(76790),s=r(50989),o=r(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,i.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const i=r(40958),n=r(38639),s=r(26905),o=r(54993),a=r(68852),l=r(73568),u=r(78656),c=r(98314),d=r(38835);function h(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const r=(0,o.toS)(e)+(0,i.compact)(t).join("");return h(r)+f(r).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const g=/Can't write [a-z\d]+ files/i,p=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const r=(0,c.errorToS)(e);return!g.test(r)&&(!!p.test(r)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const r=(0,c.errorToS)(e);return!(!r.includes("EBUSY")&&!r.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const r=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>r.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const i=r(22573),n=r(31586),s=r(68708),o=r(7282),a=r(23560),l=r(45608),u=r(34102),c=r(28874),d=r(98314),h=r(38835),f=r(70025),m=r(57159),g=r(5012);function p(e,t){try{if((0,i.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,g.stack)()),!1;const r=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===r.fatal,c=!0===r.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",r));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:r}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:r.toString(),status:r.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=p,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,r){return p(e+h.InternalErrorFlag,{cause:t,...r})}},57159:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const i=r(40958),n=r(22573),s=r(38639),o=r(26905),a=r(98553),l=r(68708),u=r(59455),c=r(41583),d=r(48884),h=r(81168),f=r(98314),m=r(38835),g=r(70025);t.toWrappedError=function(e,t){const r=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof p&&(null==t||(0,n.blank)(r.message)||e.message.includes(r.message)))return e;const i=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,r?.message);return new p(i??"(missing error message)",r)};class p extends Error{constructor(e,t={}){super(e),this.causes=(0,i.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const r=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??r.some(g.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(r.map(g.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(r.map(g.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(r.map(g.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,g.stripErrorFlags)(function(e,t){let r=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const i=t?.path;return(0,n.blank)(i)||(r=(0,h.dedupeNeedle)(r,i,"file")),(0,f.joinErrorMessages)([r[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...r.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new p(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=p},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=r(49769),a=r(55835),l=r(54993),u=r(22911),c=r(89788),d=r(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,i.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,i,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const r=this.target.emit(e,...t),o=s(this,i,"f").get(e);return null!=o&&(o.resolve(t),s(this,i,"f").delete(e)),r}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},i=new WeakMap,n=new WeakMap},34102:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const i=r(78474),n=r(19851),s=r(15197);t.ee=(0,n.lazy)((()=>{const e=new i.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=i(r(73024)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(65843),u=r(16287),c=r(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):p({stat:e,r:!0,w:!0,x:!0})}function g(e,t){return c.isWin?f(t,n.default.constants.R_OK):p({stat:e,r:!0,x:!0})}function p({stat:e,r:t=!1,w:r=!1,x:i=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(r&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!i||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=g,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const r of(0,l.selfAndAncestorG)(e)){const i=await(0,u.statMaybe)(r);if(null!=i){if(!i.isDirectory())return!1;if(t){if(!g(i,e))return!1}else if(t=!0,!m(i,e))return!1}}return!0},t.access=p},21144:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=i(r(76760)),s=r(19851),o=r(81168),a=r(57159),l=r(43334),u=r(88561),c=r(29882),d=r(65238),h=r(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const r=(0,c.parseNativePath)((0,h.resolve)(...e)),i=await m(r.dir);for(const e of await(0,d.readdir_)(i))if((0,o.equalsIgnoreCase)(e.basename,r.base))return n.default.join(i,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const i=r(73024),n=r(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,i.readdirSync)(e)}catch(e){return[]}}function l(e,t){const r=a(e);return t.every((e=>r.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,r){var i,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&l(t,e,r);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(r(44652)),g=c(r(73024)),p=r(51455),y=f(r(76760)),v=f(r(1708)),w=r(46466),S=f(r(57975)),b=f(r(38522)),P=r(19851),_=r(40958),E=r(5233),M=r(22573),C=r(42659),T=r(50357),x=r(96249),D=r(98553),k=r(55835),O=r(31586),I=r(68708),L=r(97790),F=r(39926),A=r(51926),N=r(59455),R=r(54993),j=r(48884),B=r(22911),V=r(99331),z=r(56519),W=r(56038),q=r(31562),U=r(76850),G=r(70025),H=r(34102),J=r(80875),$=r(50213),K=r(70417),Y=r(43334),Z=r(81168),X=r(96859),Q=r(65162),ee=r(94174),te=r(64660),re=r(21144),ie=r(84542),ne=r(89968),se=r(20197),oe=r(88561),ae=r(50597),le=r(33456),ue=r(29882),ce=r(78133),de=r(43899),he=r(65238),fe=r(53265),me=r(17217),ge=r(16287),pe=r(68284),ye=r(66003),ve=r(27794),we=r(73428),Se=r(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(i.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,i=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),r=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(r)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const r=(0,me.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,M.blank)(r))throw new Error("BaseFile.for(): empty nativePathOrFile");const i=be().get(r);if(null!=i)return i;const n=(0,fe.resolve)(r),s=new Pe(n,t);return be().set(r,s),be().set(n,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const r=[];for(const i of t)!0===await e(i)&&r.push(i);return r}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,i,"m",s).call(this)??await d(e=this.clearThisAndParent(),i,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const r of t)await r.visitDescendants(e),await e(r)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const r=await this.childDirectories();if(null==r)return t;for(const i of r)t.push(...(0,N.toA)(await i.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const r=await d(this,n,"f").call(this)??[];for(const t of r)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const i of r)if(i.isDirectory()){const r=await this._directoryEntryChild(i).someDescendant(e,t-1);if(null!=r)return r}}descendantsSync(e){const t=this.directoryEntrySync(),r=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&r.push(this.forDirectoryEntry(t))})),r}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,re.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,r)=>this.join((0,R.toS)(e),(0,F.pad2)(t+1),(0,F.pad2)(r))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,r="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(r,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,r="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(r,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,r){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(r??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,ge.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,ge.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,C.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,ge.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>=(0,C.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(r=>Math.abs(r-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>(0,C.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,L.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,q.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*C.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,J.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,J.parseJSON)((0,g.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,g.readFileSync)(this.nativePath)}readFile_(){return(0,p.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return g.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,E.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,V.ending)()?1:3,timeoutMs:0,retryDelay:C.secondMs,errorIsRetriable:G.isRetriableError})}async gunzip(){return d(this,i,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,i,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,i,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return g.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return g.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const r=await this.children((async r=>!r.isNameHidden()&&t===r.size()&&r.nativePath!==e.nativePath));if((0,_.isEmpty)(r))return;const i=await e.sha();if(null!=i)for(const e of r.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===i)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),r=g.default.createReadStream(this.nativePath,{flags:"r"});return r.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),r.close()):t.maybeReject(e)})),r.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(r,(0,A.newlineRe)(),(i=>{const n=e.exec(i);null!=n&&(t.maybeResolve(n),r.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,r)=>{for(const i of e)for(const e of r)if((0,O.closeTo)(i,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),r=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&r.setTimeout(e.timeoutMs),_e)try{const i=(0,g.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(i,n)=>{try{const s=await e.f(i,(0,k.denull)(n));t(s)&&r.resolve(s)}catch(e){r.reject(e)}}));r.finally((()=>{i.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const i=setInterval((async()=>{try{const i=await e.f();t(i)&&r.resolve(i)}catch(e){r.reject(e)}}),e.intervalMs);e.persistent||i.unref(),r.finally((()=>{clearInterval(i)}))}return r}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const r=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([g.default.createReadStream(this.nativePath,{autoClose:!0}),t,g.default.createWriteStream(r.nativePath,{autoClose:!0})]),await this.unlink(),r}))},Pe.attrTTL=3*C.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},84542:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const i=r(40958),n=r(96249),s=r(51926),o=r(54993),a=r(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,i.compactBlanks)(l(...e))}},70698:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const i=r(76760),n=r(19851),s=r(50213),o=r(37805),a=r(29882),l=r(93854),u=r(17217),c=r(16287),d=r(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const r=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return r===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,i.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const r=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(r),await(0,d.writeTextfile_)((0,a.joinNativePath)([r,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(45969),u=r(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(r(44652)),l=o(r(73024)),u=r(76760),c=r(57975),d=r(19851),h=r(59455),f=r(50213),m=r(81168),g=r(34102),p=r(29882),y=r(65238),v=r(14427),w=r(17217),S=r(16287),b=r(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class E{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,p.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new E(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:r,base:i}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,p.parseNativePath)(e)},n=await a.stat(t);return new E(r,new P(i,n))}clear(){return(0,g.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return E.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,p.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,p.parseNativePath)(this.dir);return e.dir===this.dir?this:new E(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>E.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new E(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const r of t)r.isDirectory()&&await r.visitDescendants(e);for(const r of t)r.isFile()&&await e(r);for(const r of t)r.isDirectory()&&await e(r)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const r of t)r.isFile()&&e(r);for(const r of t)r.isDirectory()&&(r.visitDescendantsSync(e),e(r))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async r=>{!0===await e(r)&&t.push(r)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,g.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,g.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=E},20197:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=i(r(76760)),s=r(39926),o=r(29882),a=r(16287),l=r(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if(await(0,o.mkdirp_)(i.dir),!r.requireNumber&&await(0,a.isEmptyFile)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if(await(0,a.isEmptyFile)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)},t.ensureNewNativePathSync_=function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if((0,o.mkdirpSync_)(i.dir),!r.requireNumber&&(0,l.isEmptyFileSync)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if((0,l.isEmptyFileSync)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)}},88561:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=r(40958),a=r(22573),l=r(41400),u=r(68708),c=r(25764),d=r(38836),h=r(34102),f=r(80049),m=r(50213),g=r(88158),p=r(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:p.ShortCommandTimeoutMs,...e}),i.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,i,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,g.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,i=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const i=r(73024),n=r(22573),s=r(45599),o=r(96249),a=r(68708),l=r(54993),u=r(49047),c=r(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...r]of d)for(const i of r)e[i]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof i.Dirent?e.name:(0,l.toS)(e),r=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(r)?void 0:h()[r]??r}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const r of t)if(r===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const i=r(68708),n=r(17217),s=r(16287),o=r(68284);async function a(e){return(0,i.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,i.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},4001:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const i=r(22573),n=r(55835),s=r(31586),o=r(51926),a=r(54993),l=r(97352),u=r(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,i.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,r){if(t.ymdIsoRE.test(e))return e;let i=e;for(const e of r.aggressive?d:c){const t=i.match(e);if((0,s.gt0)(t?.index)){const e=i.slice(0,t.index).trim();e.length>0&&(i=e)}}return e===i?e:f(i,r)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),r=t.pop();if((0,i.blank)(r))return e;const n=(0,u.parsePosixPath)(r),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),r=h(t),i=(0,o.stripPrefix)(t.toLowerCase().normalize(),r);return(0,n.map)((0,l.extractInt)(i),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,g=/(?<=.{6})_cover$/i,p=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(g,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(p.exec(t),(e=>t=e[1].trim())),t}},14977:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=i(r(44652)),s=i(r(73024)),o=r(46466),a=i(r(38522)),l=r(49769),u=r(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=i(r(77598)),s=i(r(73024)),o=r(46466),a=r(19851),l=r(98553),u=r(68708),c=r(23467),d=r(80049),h=r(73913),f=r(50213),m=r(12089),g=r(37628),p=r(43624),y=r(17217),v=r(16287),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:r=!0}={}){const i=(0,y.toNativePath_)(e);if(r){const t=S().get(i);if(null!=t){if((0,c.eql)(t.stats,await(0,p.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:i,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:i,prior:t}),S().delete(i)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),r=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(r)),stats:(0,u.pick)(await(0,v.stat_)(r),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],r="sha512"){const i=n.default.createHash(r);return await(0,o.pipeline)([e,...t,i]),i.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,g.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},25675:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const i=r(22573),n=r(54993),s=r(7282),o=r(43334),a=r(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,i.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const i=r(57075),n=r(51926),s=r(54993);class o extends i.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,r){const i=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=i.pop();this._prior=o??"";let a=!1;for(const e of i)a||(a=!this.push(e));a?setTimeout(r,1):r()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=i(r(76760)),s=r(17217),o=r(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},29882:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(5233),u=r(22573),c=r(98553),d=r(39426),h=r(51926),f=r(48884),m=r(50213),g=r(81168),p=r(70025),y=r(43334),v=r(78133),w=r(53265),S=r(17217),b=r(16287),P=r(66430),_=r(5545);function E(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=E,t.containsHiddenPathname=function(e){return k(e).some(E)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!E(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return C((0,v.posix2native)(e))},t.extname=function(e){return C(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,g.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function C(e){const t=M.exec(e)?.groups,r=t?.ext2??"",i=s.default.parse(t?.path??e);return{...i,ext:(i.ext??"")+r,base:(i.base??"")+r}}function T(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),r=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(r))return!1;const i=e.acceptSelf??!1;return t===r?i:r.startsWith((0,g.ensureSuffix)(t,s.default.sep))}catch(r){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:r}),!1}}function D(e,t,r){if(null==t||null==r)return!1;const i=e(t),n=e(r);return null!=i&&null!=n&&(y.isLinux?i===n:(0,g.equalsIgnoreCase)(i,n))}function k(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&k(e).length===(y.isWin?1:0)}function I({p:e,maxLength:t}){const r=(0,S.toNativePath_)(e);if(r.length<=t)return r;const i=k(e),n=[],s=[i.pop()];for(;i.length>0;)if(n.length=t){i.unshift(n.pop());break}}else if(s.unshift(i.pop()),F([...n,...s]).length>=t){i.push(s.shift());break}return i.length>0&&n.push("…"),F([...n,...s])}function L(e){return e.startsWith("\\\\")}function F(e){return(0,h.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=C,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(S.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const r=(0,S.toNativePath_)(e),i=(0,S.toNativePath_)(t);if((0,u.blank)(r)||(0,u.blank)(i))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return r===i?"":(0,g.stripPrefix)((0,v.native2posix)(i).normalize(),(0,g.ensureSuffix)((0,v.native2posix)(r),"/").normalize()).normalize()},t.ellipsizePath=I,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:r=4,arrLength:i=e.length}){const n=[];for(const i of e.slice(0,r))n.push(I({p:i,maxLength:t}));return n.join(", ")+(i>r?`, and ${i-r} more…`:"")},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const r=C(e);return`${r.base}${t}${r.ext}`},t.isUNC=L,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(L(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(31586),u=r(51926),c=r(12168),d=r(59455),h=r(54993),f=r(50213),m=r(44198),g=r(96706),p=r(45969),y=r(43334),v=r(64660),w=r(21144),S=r(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const r=await(0,S.statMaybe)(e,"trace");return null!=r&&r.isFile()&&(0,l.gte)(r.size,t)&&(0,v.isStatRX)(r,e)}function E(){if(y.isWin){const e=(0,a.toNotBlank)((0,g.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,g.getEnv)("SystemDrive"))??"C:",r=(0,a.toNotBlank)((0,g.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(r,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,p.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...E()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:r}){const i=(0,o.uniq)((0,o.compactBlanks)([...M(),...(0,d.toA)(r)]));for(const r of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(r,".exe"):r;for(const t of i){const r=n.default.join(t,e);if(await _(r))return y.isLinux?r:(0,w.actualPath)(r)}}b().warn("Failed to find tool",{tool:e,dirs:i})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},78133:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=i(r(76760)),s=r(22573),o=r(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const r=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",i=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(i[0],t)&&i.unshift(),r+i.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(48884),u=r(50213),c=r(45969),d=r(29325),h=r(43334),f=r(65843),m=r(25675),g=r(53265);function p(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(n.default.join((0,g.execDir)(),"resources"),n.default.join((0,g.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,g.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const r of t){if((0,f.hasChildrenSync)(r,e))return r;for(const t of(0,f.ancestors)(r).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const i=n.default.join(r,"node_modules","photostructure");if((0,f.hasChildrenSync)(i,e))return i}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:p("bin"),Data:p("data"),ICC:p("data","icc"),Migrations:p("data","migrations"),Public:p("public"),Tools:p("tools"),Views:p("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const i=r(44652),n=r(19851),s=r(31586),o=r(50213),a=r(57902),l=r(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,i.readFile)(e)}catch(r){return void u().log(t,".readFileMaybe("+e+")",r)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const i=r(44652),n=r(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:r}){let s=-1;try{const n=r??(await(0,i.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,i.open)(e,"r"),await(0,i.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,i.close)}}},69428:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(r(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},32323:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const i=r(57075);class n extends i.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=i(r(51455)),s=r(76760),o=r(19851),a=r(76790),l=r(22573),u=r(42659),c=r(41400),d=r(31586),h=r(13538),f=r(83104),m=r(54127),g=r(50213),p=r(95937),y=r(34102),v=r(28874),w=r(63870),S=r(88561),b=r(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,g.mkLogger)("fs.Readdir")));async function _(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const E=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||E.prior()?.delete(e)}async function C(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await E().getOrSetAsync(e,(()=>async function(e){const r=Date.now()+2*(0,b.statTimeoutMs)(),i=T(e),n=await(0,h.thenOrTimeout)(i,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===f.Timeout&&(0,p.onTimeout)({soft:!1}),n!==f.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),E.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!E().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=E().get(e)},t.childDirectories_=async function(e){return(await C(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?C(e):T(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=C,t.readdirCached=function(e){return E().get(e)},t.readdirUncached_=T},53265:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=r(73024),s=i(r(76760)),o=r(40958),a=r(22573),l=r(45599),u=r(50213),c=r(43334),d=r(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function g(...e){for(const t of m()){const r=s.default.resolve(t,...e);if((0,n.existsSync)(r))return r}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?g(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=g},50274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const i=r(50989);t.SidecarExts=(0,i.strEnum)("xmp","mie","exv")},14427:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const i=r(22573),n=r(38639);t.isSimpleDirent=function(e){return null!=e&&(0,i.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=i(r(73024)),s=i(r(76760)),o=r(22573),a=r(98553),l=r(81168),u=r(43334),c=r(29882),d=r(53265),h=r(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function g(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=g,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(g(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const p=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(p)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),r=t.indexOf(s.default.sep);return r>0?t.slice(1,r):void 0}},t.findFileIndex=function(e,t){for(let r=0;r(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,p.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((r=>{y().log(t,"stat() failed",{error:r,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const r=S(e),i=S(t);if(r!==i)return"inconsistent file type: "+r+" ≠ "+i;for(const r of["size","mtime"]){const i=e[r],n=t[r],s=(0,u.diff)(b(i),b(n));if(null==s||s>1)return"unmatched "+r+": "+i+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const r=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=r&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(r)},t.isNonEmptyFile=async function(e,t=0){const r=await w(e);return null!=r&&r.isFile()&&r.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.access)({stat:r,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.isStatRWX)(r,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=i(r(73024)),s=r(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const r=o(e);return t.emptyIsNew?null==r:a(r)},t.isNonEmptyFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const i=r(28874);t.statTimeoutMs=function(){return i.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const i=r(22573),n=r(56409);t.onDataChunked=function(e,t,r){const i=new s(t,r,!0);return i.read(e),i.done};class s{constructor(e,t,r=!0){this.sep=e,this.onData=t,this.filterBlanks=r,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,i.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,i.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=i(r(57075)),s=r(41400),o=r(55835),a=r(68708),l=r(42279),u=r(99331),c=r(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((r,i)=>{!1===e.write(t,(e=>{e&&i(e)}))?e.once("drain",r):r()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:r,ea:i}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(i,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(r,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends n.default.Transform{constructor(e){super({transform:(e,t,r)=>{this.onProgress(this.bytes+=e.length),r(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=i(r(73024)),s=r(76760),o=r(22573),a=r(76596),l=r(64660),u=r(78133),c=r(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},27794:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=i(r(44652)),s=r(19851),o=r(22573),a=r(42659),l=r(31586),u=r(68708),c=r(13538),d=r(29882),h=r(17217),f=r(16287),m=r(41080);function g(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const r=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const i=(0,h.toNativePath_)(t.file);r&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(g(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),p=Math.round(g(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(i,new Date(p),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!r||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(i),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},5545:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=i(r(76760)),s=r(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const r=t.driveRe.exec(e)?.groups;return null==r?e:r.drive.toUpperCase()+(0,s.toS)(r.path??n.default.sep)}},58722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const i=r(57075),n=r(22911);class s extends i.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,r){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),r()}}t.WritableToBuffer=s},73428:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(51926),a=r(54993),l=r(34102),u=r(84542),c=r(29882);async function d(e,t){const r=s.default.dirname(e);await(0,c.mkdirp_)(r),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",r)}function h(e,t){const r=s.default.dirname(e);(0,c.mkdirpSync_)(r),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",r)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const r=(0,u.crlf)(...(0,o.wrap)(t));await d(e,r)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=i(r(73024)),s=r(76760),o=r(46466),a=r(38522),l=r(19851),u=r(40958),c=r(98553),d=r(80875),h=r(50213),f=r(57159),m=r(29882),g=r(57902),p=r(32323),y=r(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,r){const i=[],s=[n.default.createReadStream(e,{autoClose:!0,...r}).on("error",(e=>i.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>i.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>i.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(i))throw new f.WrappedError("zPipe("+e+") failed",{causes:i,path:e})}async function b(e,t){const r=new y.WritableToBuffer;return await S(e,r,t),await r.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const r=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new p.ReadableBuffer(r),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=g.LogLevels.warn){try{return await P(e)}catch(r){return void v().log(t,"readJsonGz("+e+"): failed",r)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,r=g.LogLevels.warn){try{await _(e,t)}catch(t){v().log(r,"outputJsonGz("+e+"): failed",t)}}},33866:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const i=r(50989);t.HealthCheckIds=(0,i.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},52086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const i=r(50989);t.CropStrategies=(0,i.strEnum)("center","entropy","attention")},48584:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const i=r(50989);t.SharpFailOns=(0,i.strEnum)("none","truncated","error","warning")},49794:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const i=r(57975),n=r(19851),s=r(40958),o=r(22573),a=r(54993),l=r(37975),u=r(7282),c=r(23560),d=r(28874),h=r(66184),f=r(93475),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function g(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=g,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=g(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,i.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:g(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:r,meta:i})}}},32105:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const i=r(19851),n=r(23560),s=r(66184),o=r(72210);class a{log(e,t,r,i){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:r,meta:i})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,i.lazy)((()=>new a))},14593:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const i=r(57975),n=r(22573),s=r(26905),o=r(55835),a=r(68708),l=r(13538),u=r(50213),c=r(97352),d=r(45255),h=r(76740),f=r(57159),m=r(57902),g=/logger|lazy/i;class p{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!g.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[i.inspect.custom](){return this.toLogJSON()}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const r=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(r),this.log(!0===r.ignorable?"warn":"error",".throw() "+r.message,{stack:r.stack,...t}),r}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let r;try{r=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const i=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:i,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(r,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const r of this.loggers())if(r.enabled(e,t??this.context))return!0;return!1}log(e,t,r){for(const i of this.loggers())i.log(e,this.context,t,r)}elapsed(e,t,r){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...r})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=p},89179:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const i=r(50213),n=r(43705);t.currentFileLogger=function(){return(0,i.rootLoggers)().find((e=>e instanceof n.LogWriter))}},28981:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const i=r(19851),n=r(51879);t.DefaultLogFormatter=(0,i.lazy)((()=>new n.PlaintextLogFormatter))},31256:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(41400),a=r(98553),l=r(55835),u=r(31586),c=r(68708),d=r(72993),h=r(23560),f=r(81168),m=r(98314),g=r(57902),p=r(93475),y=(0,i.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,r]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(r)}}}(0,o.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,g.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,p.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:r,meta:i})}}},51576:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=r(77030),o=r(19851),a=r(22573),l=r(42659),u=r(41400),c=r(98553),d=r(56409),h=r(31586),f=r(25764),m=r(38836),g=r(50213),p=r(409),y=r(28874),v=r(31256),w=r(28538),S=(0,o.lazy)((()=>(0,g.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),r=(0,h.toInt)(t);return(0,a.blank)(e)||!(0,h.gt0)(r)?void 0:{host:e,port:r}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),i.set(this,(0,p.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,i,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,r,s){if(this.enabled(e,t))try{const o=this.socket;null==o?n(this,i,"f").call(this):o.write(this.logFormatter.format(e,t,r,s)+b)}catch(i){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:r,meta:s,error:i})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}i=new WeakMap},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const i=r(76760),n=r(42659),s=r(28874);t.datedLogDir=function(e,t){return(0,i.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},4904:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const i=r(76790),n=r(31586),s=r(51926),o=r(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,i.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const i=r(19851),n=r(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,i.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,i.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,r){return(0,t.logFilter)().enabled(e)?r():void 0},t.isLogged=function(e,r){return(0,t.logFilter)().enabled(e,r)}},28538:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=r(19851),u=r(40958),c=r(22573),d=r(54993),h=r(28874),f=r(66184),m=r(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){i.add(this),this.setting=e,this.silent=!1,n.set(this,[]),s.set(this,(0,l.lazy)((()=>{a(this,n,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const r of t){const t=f.LogLevelRe.exec(r.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+r+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),r=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=r:a(this,n,"f").push({prefix:e,levelIndex:r})}}}))),e.watch((()=>a(this,s,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const r=(0,m.levelIndex)(e);if(null!=t){const e=a(this,i,"m",o).call(this,t);if(null!=e)return r<=e.levelIndex}return r<=this.defaultLevelIndex}highlight(e){const t=a(this,i,"m",o).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap,s=new WeakMap,i=new WeakSet,o=function(e){if(null==e||0===a(this,n,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return a(this,n,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const i=r(31586),n=r(50989),s=r(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,r){return(0,i.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(r))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const i=r(40958),n=r(68708),s=r(20214),o=r(51926),a=r(23541),l=r(48884),u=r(88158),c=r(98314),d=r(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(r,h=4){if(null==r)return null;if(h<0)return"…";if((0,o.isString)(r)||Buffer.isBuffer(r))return(0,o.ellipsize)(r.toString(),256,32);if((0,a.isError)(r))return(0,c.errorToVerbose)(r);if(Array.isArray(r)){const t=d.Settings.logContextLimit.valueOrDefault,i=Math.floor(t/2);return r.length<=t?r:[...r.slice(0,i).map((t=>e(t,h-1))),`… (${r.length} total entries)`,...r.slice(-i).map((t=>e(t,h-1)))]}if("object"==typeof r||"function"==typeof r){for(const t of["toLogJSON","toJSON"])if("function"==typeof r[t])return e(r[t](),h-1);if((0,s.isPromiseLike)(r))return t.PromisePlaceholder;if("…"in r)return r;const a=(0,u.mapNullEntries)(r,((t,r)=>e(r,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(r),(0,n.keys)(a));return(0,i.isNotEmpty)(c)&&(a["…"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return r}},24068:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const i=r(73024),n=r(76760),s=r(1708),o=r(87997),a=r(19851),l=r(22573),u=r(42659),c=r(49769),d=r(55835),h=r(34666),f=r(20214),m=r(7282),g=r(23560),p=r(54826),y=r(82328),v=r(22277),w=r(25764),S=r(38836),b=r(99331),P=r(42638),_=r(76596),E=r(98314),M=r(89968),C=r(29882),T=r(28874),x=r(28981),D=r(20839),k=r(21727),O=r(66184),I=r(57902),L=r(72210),F=r(98192);function A(e){const t=(0,x.DefaultLogFormatter)();for(const r of e)(0,p.consoleLog)(t.formatLogEntry(r))}t.DefaultLogEntryWriter=A;class N extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,T.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,p.consoleLog)("tailing "+e+"..."),await(0,C.mkdirp_)(e),this.root=await M.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,g.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,L.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),D.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,L.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,p.consoleLog)("LogTail(): watching "+e)));try{return(0,i.watch)(e,((t,r)=>{(0,l.notBlank)(r)&&this.watchListener(t,(0,n.join)(e,r))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,p.consoleError)("LogTail(): failed to read "+e+": "+(0,E.errorToS)(t))))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,_.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,k.datedLogDir)(this.root.nativePath);try{await(0,C.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,p.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,E.errorToS)(e))))}(0,b.ending)()||this.ended||e&&(0,p.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,L.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,L.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await M.DirectoryEntry.for(t);if(null==e)return;const r=e.size();if(null==r||r<=0)return;const i=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(i,r))return;await(0,f.thenMap)((0,F.readLogEntries)(e,{start:i,end:r}),(e=>(0,L.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,r)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,p.consoleError)("Failed to read "+t+": "+(0,E.errorToS)(e))))}}))}}t.LogTail=N,N.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new N))},72210:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const i=r(92322),n=r(82328),s=r(28981),o=r(20839),a=r(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new i.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const r of e)l?t.logEntries.add(r):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(r))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(r(73024)),f=r(76760),m=r(19851),g=r(42659),p=r(41400),y=r(98553),v=r(31586),w=r(409),S=r(23560),b=r(81168),P=r(78406),_=r(25764),E=r(20197),M=r(14977),C=r(36868),T=r(28874),x=r(32105),D=r(20839),k=r(21727),O=r(66184),I=r(93475),L=r(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,r,i){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:r,meta:i})}enabled(){return!0}end(){}async flush(){}};class F extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*D.DefaultLogFlushMs),rank:_.EndableRanks.logger,unref:!0,onEnd:()=>c(this,n,"f").call(this)}),i.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,g.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*g.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,i,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:x.ConsoleLogger.instance(),flushEveryMs:D.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,i,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,r,i){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,r,i);else{const n={ts:Date.now(),l:e,ctx:t,msg:r};null!=i&&(n.meta=(0,I.prepMeta)(i)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,L.recentLogEntries)()),(0,L.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=F,n=new WeakMap,i=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,i,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const r=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,r);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,i,"m",o).call(this,e,t),c(this,i,"m",u).call(this))},l=async function(){await c(this,i,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,E.ensureNewNativePath_)({nativePath:(0,f.join)((0,k.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),r=h.default.createWriteStream(t).on("error",c(this,i,"m",a).call(this,"file write stream"));this._logfile={stream:r,nativePath:t},this._nextForcedRotateTs=(0,g.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,C.endStream)(e.stream),T.Settings.logCompression.valueOrDefault&&(await(0,p.delay)(this.logOpts.flushEveryMs),await(0,M.gzip_)(e.nativePath))}catch(e){c(this,i,"m",o).call(this,"_closeCurrent()",e)}}},51879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(68708),a=r(54993),l=r(23560),u=r(81168),c=r(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,i.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:r,meta:i})}}},98192:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const i=r(22573),n=r(84542),s=r(4001),o=r(13047),a=r(4904);function l(e){if(!(0,i.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const r=(0,s.stripCopySuffixFromName)(e.name),i=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,n.splitLines)(a)){const t=l(e);null!=t&&i.push({...t,from:r})}return i},t.chunkToLogEntry=l},22662:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const i=r(19851),n=r(76790),s=r(68708),o=r(89788),a=r(57902);t.SentLogLevels=(0,i.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,i.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},17181:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const i=r(76760),n=r(41400),s=r(55835),o=r(37975),a=r(50213),l=r(27395),u=r(46296),c=r(96706),d=r(73428),h=r(28874),f=r(49794),m=r(32105),g=r(89179),p=r(28981),y=r(51576),v=r(66184),w=r(28538),S=r(24068),b=r(43705),P=r(51879);function _(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),E();const e=(0,u.logDir)();let t=(0,g.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,i.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new b.LogWriter(e));const r=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&r.push(m.ConsoleLogger.instance()),(0,s.map)((0,y.logBroadcaster)(),(e=>r.push(e))),a.rootLoggers.set(r),h.Settings.tailLogs.valueOrDefault&&S.LogTail.instance()}function E(){const e=h.Settings.logColor.valueOrDefault;(0,o.setColorEnabled)(e),p.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=_,t.setupLogFormatter=E,(0,n.later)((()=>{h.Settings.logStdout.watchLater(_),h.Settings.logDir.watchLater(_),h.Settings.tailLogs.watchLater(_),h.Settings.logColor.watchLater(E),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},36389:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=i(r(1708)),s=r(24068),o=r(40958),a=r(5670),l=r(69554),u=r(38790),c=r(46296);!async function(){const e=(0,c.logDir)(),t=await new l.CLI(a.ServiceNames.logtail,"[LOG_DIR]","Normally logtail watches all files in the default logging directory, "+e+". Specify LOG_DIR or set the PS_LOG_DIR environment variable to override this directory.").add(u.ColorArgs).parse();n.default.on("SIGINT",(()=>n.default.exit(0))),n.default.on("SIGTERM",(()=>n.default.exit(0)));const r=(0,o.compactBlanks)(t.args);new s.LogTail(r[0]??e)}()},82647:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=r(57975),a=r(40958),l=r(96249),u=r(55835),c=r(31586),d=r(68708),h=r(59455),f=r(48884),m=r(89788),g=r(22454),p=r(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const r=t.clone();return r.pushAll(e.samples),r}if(t.n<=t.maxSamples){const r=e.clone();return r.pushAll(t.samples),r}{const r=new y(Math.max(e.maxSamples,t.maxSamples));r._n=e.n+t.n,r._min=Math.min(e._min,t._min),r._max=Math.max(e._max,t._max),r._m=e._m*e.n/r.n+t._m*t.n/r.n,r._s=e._s*e.n/r.n+t._s*t.n/r.n;const i=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return r._samples.push(...i),r._weightedTotalAvg=(0,p.weightedAvg)([r._m,...i]),r}}constructor(e=20){i.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(i=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,p.min)([this._min,e.min]),this._max=(0,p.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),r={};return r.k=t(this.n),this.empty||(r.mean=t(this.avg),r.sum=t(this.sum),r.sd=t(this.stdDev),r.max=t(this.max),r.min=t(this.min)),r}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,i,"m",n).call(this,-1)}get p29(){return s(this,i,"m",n).call(this,-.5)}get p38(){return s(this,i,"m",n).call(this,-.25)}get p69(){return s(this,i,"m",n).call(this,.5)}get p84(){return s(this,i,"m",n).call(this,1)}get p98(){return s(this,i,"m",n).call(this,2)}get p99(){return s(this,i,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new g.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,p.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,p.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,p.avg)}get sampleSlope(){return(0,p.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,p.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const i=r(40958),n=r(55835),s=r(31586),o=r(30976),a=r(48884),l=r(70417);function u(e,t){const r=Math.pow(2,t),i=[];for(;e>0;)i.unshift(e%r),e=Math.floor(e/r);return i}t.concatBits=function(e,t){const r=Math.pow(2,t);return e.reduce(((e,t)=>e*r+(0,s.clamp)(0,r,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,r){return(0,n.map2)(e,t,((e,t)=>(0,i.sum)((0,a.zip)(u(e,r),u(t,r)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,r[t]=o):i[t]=o}return s}unzip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max));for(let n=0;n(r[e]+i[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,r){return!0!==r&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let r=0;rs?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const r=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,i.sum)(e,((r,i)=>t(r,i)?Math.pow(2,e.length-i-1):0))}},55222:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const i=r(77598),n=r(22573),s=r(55835),o=r(32639),a=r(88158),l=r(81168),u=BigInt(0);function c(e,t,r=0){if(!isFinite(t)||e<=1)return[];const i=[];if(0===t)i.unshift(0);else for(;t>0;)i.unshift(t%e),t=Math.floor(t/e);for(;i.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const r=e<0;return r&&(e=Math.abs(e),t--),(r?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],r=BigInt(this.base);let i=e;for(;i>u;)t.push(Number(i%r)),i/=r;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let r of e)for(t.forEach(((e,i)=>{r+=e<<8,t[i]=r%this.base,r=Math.floor(r/this.base)}));r>0;)t.push(r%this.base),r=Math.floor(r/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const r=BigInt(this.base);let i=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;i=i*r+BigInt(e)}return t?BigInt(-1)*i:i}randomChars(e){return this.encodeBuffer((0,i.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,r="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(r)}tokenEql(e,t,r){const i=this.normalizeToken(e),n=this.normalizeToken(t);return i.length>=r&&i===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const i=r(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,i.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},70417:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=r(40958),l=r(55835),u=r(31586),c=r(59455),d=r(22454),h=r(77377),f=r(82647);function m(e){let t;for(const r of e)null!=r&&(null==t||rt)&&(t=r);return t}function y(e,t){const r=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&r.incr(t);return r.topKeys(t)}function v(e,t){let r=0,i=0;for(const n of e){if(null!=n){const e=t(n,r);(0,u.isNumber)(e)&&(i+=e)}r++}return i}t.min=m,t.max=p,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,r)=>e-t[r]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const r of e)(0,u.isNumber)(r)&&(t+=r);return t},t.sumf=v;class w{constructor(){i.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,i,"f")/(s(this,i,"f")+1)+e/(s(this,i,"f")+1),"f"),o(this,i,(t=s(this,i,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const r of e)t.push(r);return t.mean}function b(e){const t=S(e);if(null==t)return;let r=0,i=0;for(const n of e)(0,u.isNumber)(n)&&(i++,r+=(n-t)*(n-t));return r/i}function P(e){let t=0;for(const r of e)t+=r*r;return Math.sqrt(t)}function _(e,t){let r=0;for(let i=0;i(1-t)*e+t*(r+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),r=S(t);if(null!=r){const e=(t.length-1)/2,i=v(t,((t,i)=>(t-r)*(i-e))),n=v(t,(e=>(e-r)**2));return 0===n?0:i/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let r;t=(0,u.clamp)(0,1,t);for(const i of e)r=null==r?i:r*t+i*(1-t);return r},t.centroid=function(e){const t=e[0].length,r=[];for(let i=0;ie[i]))));return r},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},45969:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const i=r(73024),n=r(38639),s=r(19851),o=r(59958),a=r(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,i.existsSync)("/.running-in-container"))))},29325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const i=r(76760),n=r(19851),s=r(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,i.join)("core","platform","IsPacked"))))},43334:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(22573),a=r(38639),l=r(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=i(r(73024)),s=r(19851),o=r(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const i=r(58587),n=r(59455),s=r(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(i.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,i.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=r(58587),d=u(r(31421)),h=u(r(1708)),f=r(40958),m=r(22573),g=r(42659),p=r(55835),y=r(31586),v=r(97790),w=r(59455),S=r(54993),b=r(54557),P=r(19851),_=r(50213),E=r(88158),M=r(409),C=r(78406),T=r(25764),x=r(99331),D=r(56519),k=r(46292),O=r(8769),I=r(83278),L=r(32144),F=r(29882),A=r(43334),N=r(24399),R=r(58261),j=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),B=10*g.secondMs;function V(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const r=(0,p.map)(t.start,(e=>e.getTime())),i=e.startTime;return(0,y.gt0)(r)&&(0,y.gt0)(i)&&Math.abs(r-i){const e=Date.now()-2*g.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,L.isJsonExt)(t)&&(0,F.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:g.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,r=e.force??A.isWin,i=await this.pidfiles(),n=await this.pids(i??[]);if((0,f.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,R.pidInfos)(n);if(null!=a){for(const n of i){const i=await n.readJson();if(null==i){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=i.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:i,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!V(i,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:i,pidEntry:u}),await n.unlink("debug"),s.push(i);continue}const c=(0,y.gt0)(i.timeoutMs)?i.startTime+i.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(i.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:i}),o.push(W(l,r,!1)),s.push({...i,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,r=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(r&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const r=a(this,i,"m",s).call(this,e.pid),n=(0,v.opt)((0,E.Try)((()=>(0,F.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await r.writeJson_(l),j().debug("addPid() wrote "+r,l),r}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,i,"m",s).call(this,e);return(0,D.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,g.ago)(g.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new C.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*g.minuteMs,rank:T.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=q,n=new WeakMap,o=new WeakMap,i=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},q.instance=(0,P.lazy)((()=>(0,p.map)((0,k.configDir)(),(e=>new q(I.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return q.instance()?.addPid_(e,t)}},58261:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=r(31421),s=r(48161),o=i(r(1708)),a=r(40958),l=r(22573),u=r(42659),c=r(31586),d=r(68708),h=r(59455),f=r(54993),m=r(48884),g=r(53507),p=r(19851),y=r(50213),v=r(84968),w=r(48963),S=r(56519),b=r(84777),P=r(8103),_=r(45879),E=r(43334),M=r(24399),C=r(45643),T=(0,p.lazy)((()=>(0,y.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){if(E.isLinux)return async function(e){const t=[];for(const r of e)t.push(z(await(0,_.readFileMaybe)("/proc/"+r+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,C.existingPids)(e),r=(await(0,m.collectBatchedAsync)(t,20,E.isWin?L:R)).filter((e=>x(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:r,meta:{pids:e}})}t.isProcEntry=x,t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,C.existingPids)(e),(t=>{const r=[o.default.pid,...t];return e.filter((e=>!r.includes(e)))}))},t.pidInfos=D;const k="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function L(e){if(M.PowerShell.instance().ended)return N(e);const t=[k,"-Id",I(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function N(e){const t=["process"];if((0,a.isNotEmpty)(e)){const r=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",r)}t.push("get",A.join(","));const r=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),i=(0,d.onlyReqValued)((0,g.parseFixed)(A,r.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return i.find((e=>e.pid===o.default.pid))||i.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),i}async function R(e){return t=(await(0,b.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,g.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=N;const j=(0,p.lazy)((()=>{try{if(E.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){T().warn("clk_tck failed",{error:e})}return 100})),B=(0,p.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),V=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function z(e){const t=V.exec((0,f.toS)(e))?.groups,r=(0,c.toInt)(t?.pid),i=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(r)&&!(0,l.blank)(i)&&(0,c.gt0)(n)?{pid:r,cmd:i,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},24399:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const i=r(58587),n=r(19851),s=r(22573),o=r(42659),a=r(41400),l=r(55835),u=r(13538),c=r(36557),d=r(14121),h=r(50213),f=r(7282),m=r(45255),g=r(81168),p=r(25764),y=r(38836),v=r(99331),w=r(56519),S=r(31562),b=r(84777),P=r(34102),_=r(43334),E=r(28874),M=r(63870),C="{ready}",T=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),p.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new i.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",E.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${C}"}`,...(0,s.mapNotBlankOr)(E.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:C,fail:"Error",exitCommand:"exit",maxProcs:E.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),p.EndableRanks.postdb),E.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(E.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,g.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const r=this.mockResults.get(e);return t(r.stdout,r.stderr,r.passed)}try{const r=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new i.Task(e,((r,i,n)=>t((0,l.map)(r,(t=>(0,g.stripPrefix)(t,e))),i,n)))));return this.logger.tap({msg:"execute()",result:r.result,meta:{elapsedMs:r.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,g.ensureSuffix)(e,T),((e,t,r)=>({stdout:e,stderr:t,passed:r})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const r=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,g.ellipsize)(t.stdout),after:(0,g.ellipsize)(r)}),JSON.parse(r)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,n.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const i=r(50989);t.AggregateTypes=(0,i.strEnum)("union","intersection")},71988:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const i=r(50989);t.AssetFileSortCriteria=(0,i.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const i=r(22573),n=r(38639),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(i.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const i=r(50989);t.ColorDistanceFunctions=(0,i.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const i=r(36507),n=r(22573),s=r(45599),o=r(50213),a=r(81168),l=r(98314),u=r(8769),c=r(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,i.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,r){try{return(0,n.blank)(t)?void 0:(0,i.Cron)(t,{name:e,unref:!0,protect:!0,catch:r=>(0,u.onError)(r,{name:e,crontab:t}),...r})}catch(r){return void d().warn("invalid cron",{name:e,crontab:t,error:r})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const i=r(70488),n=r(91655),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration})}get valueOrDefault(){return(0,i.decodeDuration)(super.valueOrDefault)}get value(){return(0,i.decodeDuration)(super.value)}set value(e){super.userValue=(0,i.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,i.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,i.decodeDuration)(this.defaultValue)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const i=r(22573),n=r(53265),s=r(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,i.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const i=r(51926),n=r(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,i.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=r(19851),a=r(40958),l=r(79666),u=r(50357),c=r(57924),d=r(98553),h=r(55835),f=r(68708),m=r(39926),g=r(46891),p=r(42279),y=r(59455),v=r(40583),w=r(81168),S=r(44198),b=r(96706),P=r(34102),_=r(28283),E=r(81075),M=r(98778),C=r(10357);t.settingsToObj=function(e){const t={};for(const r of e)r.hasValue()&&(t[r.name]=r.value);return t},t.Setting=class{constructor(e){i.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,i,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const r=this.opts.whyInvalid?.(e);return null!=r?s(this,i,"m",n).call(this,e??t)+": "+r:null==this.fromEnv(e)?s(this,i,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const r=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=r)return r}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const r=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(r)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return E.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,p.tot)(this.optsOverrides.defaultValue)??(0,p.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,p.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const r=e??(0,S.env)(),i=t??this.value;return null!=i&&(r[this.key]=this.toEnv(i)),null==e&&b.caseInsensitiveEnv.unset(),r}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const r=e??(0,S.env)(),i=this.toEnvValue(t);return null!=i&&(r[this.key]=i,null==e&&b.caseInsensitiveEnv.unset()),r}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const r of t.delete(e)??[])delete process.env[r];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],C.WrapComments);function r(e,r){(0,a.isEmpty)(r)||t.push(...(0,w.wrap)(["",(1===r.length?e:(0,g.pluralize)(e))+": "+(0,c.orList)(r.map((e=>(0,d.stringify)(e))))],C.WrapComments))}r("alias",this.opts.aliases),r("environment alias",this.altKeys);for(const[e,r]of(0,f.entries)(this.addToJSON())){const i=Array.isArray(r)?(0,c.orList)(r.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(r);t.push(...(0,w.wrap)(["",e+": "+i],C.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Example value:"],key:this.name,value:(0,p.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Default value:"],key:this.name,value:(0,p.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,p.tot)(this.fileValue)}),e}},i=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const i=r(50989);t.SettingCategories=(0,i.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const i=r(58587),n=r(51168),s=r(76760),o=r(19851),a=r(40958),l=r(76790),u=r(22573),c=r(42659),d=r(73722),h=r(68708),f=r(50989),m=r(12168),g=r(54993),p=r(37975),y=r(9092),v=r(40583),w=r(79840),S=r(7282),b=r(12801),P=r(4328),_=r(70488),E=r(84248),M=r(5531),C=r(99315),T=r(34365),x=r(34580),D=r(96706),k=r(50274),O=r(33866),I=r(52086),L=r(48584),F=r(45969),A=r(43334),N=r(24540),R=r(70379),j=r(71300),B=r(33209),V=r(48987),z=r(68268),W=r(61208),q=r(99023),U=r(30577),G=r(1485),H=r(19861),J=r(55111),$=r(30933),K=r(22859),Y=r(71988),Z=r(38483),X=r(90536),Q=r(75164),ee=r(10546),te=r(90967),re=r(67958),ie=r(55948),ne=r(57039),se=r(9945),oe=r(74589),ae=r(844),le=r(96093),ue=r(23561),ce=r(69005),de=r(87652),he=r(81075),fe=r(58305),me=r(57571),ge=r(72564),pe=r(80372),ye=r(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new pe.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new pe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new pe.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,p.noColor)()}),logContextLimit:new oe.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new pe.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>G.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:G.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>G.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new pe.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new pe.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,F.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new ge.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:J.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new i.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new pe.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:E.AutoVacuumModes,defaultValue:E.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:C.RepairModes,defaultValue:C.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,F.isDocker)()}),skipHealthCheckIds:new ge.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new pe.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new pe.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:U.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new pe.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,N.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new pe.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new pe.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,$.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:k.SidecarExts,defaultValue:k.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new pe.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ie.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:re.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,$.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:I.CropStrategies.attention,strEnum:I.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:L.SharpFailOns.truncated,strEnum:L.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>V.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:R.DateTagFormats.ym,strEnum:R.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:q.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,F.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,r]of(0,h.entries)(t.Settings))r._setName(e);function be(e){const r=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,F.isDocker)()&&r.unshift("/opt/photostructure/tools/bin"),r.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(r).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,D.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const r of(0,t.persistedSettings)()){for(const t of r.names)e.set(t,r);for(const t of r.keys)e.set(t,r)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,g.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const i=r(19851),n=r(31586),s=r(7282),o=r(49776),a=r(46292),l=r(32774),u=r(55086),c=r(46296),d=r(55939),h=r(96706),f=r(83278),m=r(92234),g=r(45969),p=r(60865),y=r(30933),v=r(15674),w=r(28874);t.setSettingsDefaults=(0,i.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,g.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=p.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const i=r(76760),n=r(40958),s=r(22573),o=r(98553),a=r(55835),l=r(59455),u=r(19851),c=r(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function h(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",i.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const r=t.split("|");for(const t of r)e.set(t,r)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const i=r(40958),n=r(98553),s=r(55835),o=r(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,i.uniq)(e)))),fromEnv:t=>{return r=t,n=e.strEnum,(0,i.compact)((0,o.splitStringArray)(r)?.map((e=>n.getCI(e))));var r,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const i=r(22573),n=r(81168),s=r(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,i.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const i=r(76760),n=r(55835),s=r(46292),o=r(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,i.join)(e,o.SettingsToml)))}},80496:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const i=r(50989);t.TagInferenceSettingValues=(0,i.strEnum)("never","always","auto")},6707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const i=r(90858),n=r(44652),s=r(22573),o=r(76850),a=r(50213),l=r(81168),u=r(84542),c=r(17217),d=r(68284),h=r(98778);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,i.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const i=r(22573),n=r(96249),s=r(98553),o=r(68708),a=r(51926);function l(e,t,r){if((0,i.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,i.blank)(r?.prefix)?[n]:(0,a.wrap)(n.split("\n"),r)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,i.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},65162:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const i=r(4001),n=r(81168);t.bname=function(e,t=!0){let r=(0,n.isString)(e)?e:e.name;return t&&(r=(0,i.stripCopySuffixFromName)(r)),r=(0,n.trimLeftPadding)((0,i.stripDSC)(r)),r.toLowerCase().normalize()}},70379:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const i=r(50989);t.DateTagFormats=(0,i.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},68268:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const i=r(50989);t.KeywordReparentingStrategies=(0,i.strEnum)("move","copy","retain")},61208:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const i=r(50989);t.NameTagFormats=(0,i.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const i=r(50989);t.NameTagOrders=(0,i.strEnum)("western","eastern")},60865:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const i=r(37805),n=r(30577);t.channel=function(){return(0,n.extractUpdateChannel)(i.version)},t.baseVersion=()=>[i.versionMajor,i.versionMinor,i.versionPatch].join("."),t.versionMajorMinor=i.versionMajor+"."+i.versionMinor},76280:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const i=r(38064),n=r(22573),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof i.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const r={loose:!0,includePrerelease:!0};if((0,i.satisfies)(e,t,r))return!0;const s=o(e);return null!=s&&(0,i.satisfies)(s,t,r)},t.toSemver=function(e){try{return e instanceof i.SemVer?e:(0,i.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const i=r(50989);t.UpdateChannels=(0,i.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const r of t.UpdateChannels.values)if(e.includes("-"+r))return r;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},1485:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const i=r(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,i.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69375:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const i=r(19851),n=r(22573),s=r(50213),o=r(9103),a=r(7282),l=r(29882),u=r(43334),c=r(28874),d=(0,i.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,g=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function p(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),r=t[0],i=t[t.length-1];return c.Settings.excludedRootDirectories.has(r)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(i)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===r&&!1===m?.test(e)?"LinuxRunRE":!0===g?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=p(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=p},63870:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const i=r(42659),n=r(12168),s=r(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/i.secondMs},55111:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const i=r(50989);t.HelmetPlugins=(0,i.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},30933:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=i(r(48161)),s=r(19851),o=r(42659),a=r(31586),l=r(50213),u=r(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),r=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??r)),meta:{availableParallelism:e,cpuInfoLength:r}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=i(r(48161)),s=r(19851),o=r(31586),a=r(12168),l=r(50213),u=r(45879),c=r(70417),d=r(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),r=(2*e+t)/3;if((0,d.isDocker)()){const i=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(i))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([i,r]),meta:{freemem:e,totalmem:t,cgroupMem:i}})}return h().tap({msg:"estimatedFreeMem() ",result:r,meta:{result:(0,a.fmtBytes)(r),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},15674:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const i=r(19851),n=r(42659),s=r(41400),o=r(31586),a=r(12168),l=r(50213),u=r(7282),c=r(34102),d=r(57902),h=r(28874),f=r(30933),m=r(58444),g=r(22751),p=(0,i.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,i.lazy)((()=>{const e=(0,o.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*a.MB;return p().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,r=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return p().tap({msg:"timeoutPenalization()",level:r>1?d.LogLevels.warn:d.LogLevels.debug,result:r,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,i.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const r=g.timeoutRate.prior()?.eventsPerMinute??0,i=w();if(1!==i){const e=t;t*=i,p().warn("Recent timeouts! Throttling down.",{penalization:i,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),p().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:i,timeoutsPerSecond:r,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,i.lazy)((function(){return(0,o.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const i=r(58587),n=r(87997),s=r(19851),o=r(42659),a=r(41400),l=r(50213),u=r(7282),c=r(45255),d=r(34102),h=r(976),f=r(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new i.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const g=(0,s.lazy)((()=>(0,n.setInterval)(p,o.minuteMs).unref()));function p(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),g()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),p()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const i=r(76790),n=r(22573),s=r(50357),o=r(98553),a=r(49769),l=r(34666),u=r(30976),c=r(42279),d=r(32639),h=r(59455),f=r(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function g(e){return null==e||0===(0,h.toA)(e).length}function p(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,r)=>e===t[r]))}function v(e,t){for(let r=0;r=e.length||r>=e.length)return e;const i=e[t];return e.splice(t,1),e.splice(r,0,i),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&(0,a.getOrSet)(r,e,(()=>i))}return[...r.values()]}function P(e,t,r=1,i=(e=>e)){const n=[];if(et;s-=r)n.push(i(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=g,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,r){return m(e)?t(e):(0,c.tot)(r)},t.toPrimitive=p,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let r=0;rt.includes(e)))},t.includesAll=function(e,t){if(g(e)||g(t))return!1;for(const r of t)if(!e.includes(r))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const r=(0,i.sortBy)(e,p),n=(0,i.sortBy)(t,p);return r.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const r of t)null==r||e.some((e=>(0,s.eql)(e,r)))||e.push(r);return e},t.pushUniqBy=function(e,t,r){const i=e.map(r);for(const n of t){const t=r(n);i.includes(t)||(e.push(n),i.push(t))}return e},t.insertAt=function(e,t,...r){return e.splice(t,0,...r),e},t.insertUniq=function(e,t,r){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let i=0;i0)return e.splice(i,0,t),e}return e.push(t),e},t.remove=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),r!==e.length},t.removeSame=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>e!==t)))),r!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const r of e)null==r||(0,s.eql)(t[t.length-1],r)||t.push(r);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const r=[];for(const e of(0,i.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))r.some((t=>t.includes(e)))||r.push(e);return(0,i.sortBy)(r,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&r.set(e,i)}return[...r.values()]},t.uniqBy2=function(e,t){const r=[];for(const i of e)null!=i&&r.every((e=>!t(i,e)))&&r.push(i);return r},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,r,i)=>e+(t(r,i)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,r,i)=>e+t(r,i)),0)},t.firstMatch=function(e,t){for(const r of S(t)){const t=e.exec(r);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let r=0;for(;e[r]===t[r];)r++;return r},t.anneal=function({array:e,expense:t,allowedDelta:r}){const i=Math.round(r);if(i<2)return e;for(let r=0;re)){return P(e,t,1,r)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,r,i=t.primitiveValueOfOrElse){const n=new Set(r.map(i));return e.filter((e=>!n.has(i(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const i=r(40958),n=r(36783),s=r(41801),o=r(98553),a=r(49769),l=r(55835),u=r(34666),c=r(59455);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const r=new Map;for(const i of e)(0,a.getOrSet)(r,(0,o.stringify)(t(i)),(()=>i));return f(r.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,l.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,i.compact)(e),i.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,r)=>0===r||t>=e[r-1]))},t.sortedBy=function(e,t){return e.every(((r,i)=>0===i||t(r)>=t(e[i-1])))},t.sortBy=f,t.deepSortBy=function e(t,r){return f(t,r).map((t=>(0,s.isIterable)(t)?e(t,r):t))},t.pushSorted=function(e,t,r){const i=e.findIndex((e=>r(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const i=r(32639);t.asPromise=async function(e){const t=await e;return(0,i.isFunction)(t)?t():t}},5233:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const i=r(41400),n=r(31586),s=r(13538),o=r(41583);t.retryOnReject_=async function(e,t){const r=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return r();const a=t.onRetryWaitUntil??(e=>(0,i.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await r()}catch(e){const r=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(r)||l>t.maxRetries)throw r;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},22573:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const i=r(55835),n=r(42279),s=r(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const r=(0,s.toS)(e);return a(r)?t(r):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const r=(0,s.toS)(e).trim();return r.length>0?r:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,r){return(0,i.orElse)(l(e,t),r)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function r(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function i(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const r=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(r)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=r,t.toBoolean=function(e){return!!r(e)||!i(e)&&void 0},t.toNotBoolean=function(e){return!r(e)&&(!!i(e)||void 0)},t.boolToInt=function(e){return r(e)?1:0},t.isFalse=i,t.isDisabled=function(e){return i(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>r(e)))},t.and=function(e){return e.every((e=>r(e)))},t.maybeAnd=function(e){let t;for(const r of e){if(!1===r)return!1;!0===r&&(t=!0)}return t},t.mapBoolean=function(e,t){return r(e)?t(!0):i(e)?t(!1):void 0},t.mapTrue=function(e,t){return r(e)?t():void 0}},79666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const i=r(98553);t.clone=function(e){return null==e?e:JSON.parse((0,i.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const i=r(40958),n=r(22573),s=r(30301),o=r(55835),a=r(31586),l=r(39926),u=r(51926),c=r(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function g(e){return e instanceof Date}function p(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=g,t.thisYear=function(){return(new Date).getFullYear()},t.ago=p,t.hence=function(e,t){return p(-e,t)},t.unixtime=function(e){const r=g(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(r/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,r={includeMs:!0}){const i=Math.floor(e/t.hourMs);e-=i*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(i)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(r.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const r=()=>{const e=t%100;return t=Math.floor(t/100),e},i=10*r(),n=r(),s=r(),o=r(),a=r(),l=r();return new Date(t,l-1,a,o,s,n,i)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,r="ago"){return e<1e3?"just now":(r=(0,n.blank)(r)?"":(0,u.ensurePrefix)(r," "),et.ms<=e)))){const s=Math.floor(e/i.ms);e-=s*i.ms,s>0&&(i.ms>=t.dayMs?r:n).push(s+i.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+r.join("")+((0,i.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=g(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const i=r(38639),n=r(73872);function s(e,t,r){if(null==r||y(e)||y(t))return null;const i=r.get(e)?.get(t);return"boolean"==typeof i?i:null}function o(e,t,r,i){if(null==r||y(e)||y(t))return;let n=r.get(e);null!=n?n.set(t,i):(n=new WeakMap,n.set(t,i),r.set(e,n))}function a(e,t,r,i){if(null!=r?.comparator)return u(e,t,r,i);const n=l(e,t);return null!==n?n:u(e,t,r)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,r,i){r??(r={});const u=!1===r.memoize?void 0:r.memoize??(r.memoize=new WeakMap),d=r?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const r=d(e,t,i);if(!1===r||!0===r)return o(e,t,u,r),r;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,r,i){switch(r){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return g(e,t,["name","message","code"],i);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,i);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,r){return c(h(e),h(t),r)}(e,t,i);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),i);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),i);case"Set":case"Map":return function(e,t,r){if(e.size!==t.size)return!1;if(0===e.size)return!0;const i=[],n=[];return e.forEach((function(e,t){i.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(i.sort(),n.sort(),r)}(e,t,i);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return p(e,t,i)}}(e,t,y,r);return o(e,t,u,v),v}function c(e,t,r){const i=e.length;if(i!==t.length)return!1;if(0===i)return!0;let n=-1;for(;++n{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,r,i=!1;const n=function(){if(i){if(null!=r)throw r;return t}try{return i=!0,t=e()}catch(e){throw r=e,e}};return n.prior=()=>t,n.hasPrior=()=>i,n}},41400:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const i=r(42659),n=r(35556),s=r(31586),o=r(68708);function a(e,t=!0){return new Promise((r=>{if(e<=0)r();else{const s=setTimeout((()=>r()),Math.ceil(e+.5));e>i.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const r=Math.max(1,Math.ceil(t)),s=n.isNode&&r<=1?setImmediate(e):setTimeout(e,r);return n.isBrowser||t<=i.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},50357:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const i=r(12487),n=r(68708),s=r(34666),o=r(32639);function a(e,t){return(0,i.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const r of(0,n.keys)(e))if(!a(e[r],t[r]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,r){if(null==e||null==t)return e===t;if(null!=r){const i=d.get(r);if(null!=i)return i(e,t)??null}for(const r of c){const i=r(e,t);if(null!=i)return i}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(31586),a=r(68708),l=r(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const r=[];for(const t of e)null!=t&&(t instanceof Error?r.push(u(t),c(t),t?.message):r.push((0,l.toS)(t)));return(0,i.uniq)((0,i.compactBlankish)((0,s.flatten)((0,i.compact)(r).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const r=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,i.isEmpty)(r)?["(missing stack)"]:r}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},96249:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const i=r(59455);t.flatten=function(e,t=[]){for(const r of(0,i.toA)(e))if(null!=r)for(const e of(0,i.toA)(r))null!=e&&t.push(e);return t}},57924:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const i=r(40958);function n(e,t){return null==(e=(0,i.uniq)((0,i.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},73722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const i=r(50989);t.FitSizes=(0,i.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,i.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const i=r(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,r){if((0,i.lt0)(t))return[...e].slice(t,r);const n=e[Symbol.iterator]();if((0,i.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,r){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(r))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],r=[];return function e(i,n){if((0,isFunction_1.isFunction)(i))return;let s,o,a,l=toJSON(i);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(i===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let i=0;t.Latch=class{constructor(e=i++){this.id=e,this[r]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},r=Symbol.toStringTag},30301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const i=r(40958),n=r(50357),s=r(31586),o=r(65812);t.lazy=function(e,t){let r,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return r=Date.now(),async function(e,r){if((0,i.isEmpty)(l))return;const s=await e,a=await r;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==r||(0,s.gt0)(t)&&r+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,r){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const i=r();return null!=i&&e.set(t,i),i}},t.deleteIf=function(e,t){for(const[r,i]of e.entries())t(r,i)&&e.delete(r)}},55835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const i=r(42279),n=r(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,r){return null==e||null==t?void 0:r(e,t)}function a(e,t){return null!=e?e:(0,i.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,r,i){return null==e||null==t||null==r?void 0:i(e,t,r)},t.orElse=a,t.mapOr=function(e,t,r){return null!=e?t(e):(0,i.tot)(r)},t.map2Or=function(e,t,r,i){return a(o(e,t,r),i)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const i=r(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,i.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const i=r(40958),n=r(76790),s=r(50357),o=r(98553),a=r(49769),l=r(55835),u=r(51926),c=r(59455);class d{static fromJSON(e){const t=new d;for(const[r,i]of Object.entries(e))t.add(r,...i);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,i.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const r=(0,a.getOrSet)(this.store,e,(()=>[]));return r.push(...t),r}addUniq(e,...t){return(0,i.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const r=this.store.get(e);if(null==r)return!1;{const i=r.filter((e=>!(0,s.eql)(e,t)));return 0===i.length?this.store.delete(e):this.store.set(e,i),r.length!==i.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,i.uniq)(t))){for(const t of this.keys()){const r=this.store.get(t),n=null==r?[]:e(t,r);(0,i.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,i.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield[t,r])}()}tuples(){const e=this;return function*(){for(const[t,r]of e.store.entries())for(const e of(0,c.toA)(r))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[r,n]of this.store.entries()){const s=(0,i.findIndexes)(n,(t=>!e(r,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(r)}return t}inverse(){const e=new d;for(const[t,r]of this.store.entries())for(const i of r)e.add(i,t);return e}findKeyByTuple(e){for(const[t,r]of this.tuples())if(e(t,r))return t}filterKeysByTuple(e){const t=[];for(const[r,i]of this.entries())i.some((t=>e(r,t)))&&t.push(r);return t}toJSON(){const e={};for(const[t,r]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=r;return e}}function h(e,t){const r=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>r.add(t,e))))),r}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const r=h(e,t);return(0,n.sortBy)((0,c.toA)(r.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const r=globalThis;t.isBrowser="object"==typeof r?.window&&"object"==typeof r?.document,t.isNode="string"==typeof r?.process?.versions?.node},31586:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const i=r(76790),n=r(22573),s=r(42279),o=r(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,r)=>a(t)&&a(r)&&e(t,r);function f(e,r,n){return!(null==n||!a(n))&&([e,r]=(0,i.sort)([e,r]),(0,t.lte)(e,n)&&(0,t.gte)(r,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function p(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return p(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const r=Math.pow(10,t);return P(e*r)/r}function E(e,t,r){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${r})`);return a(r)?rt?t:r:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,r=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(r>=1)return!1;const i=(0===t?1e-5:t)*(1-r);return f(t-i,t+i,e)},t.within=f,t.max_=function(...e){let t;for(const r of e)a(r)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const r=y(e);return null==r?void 0:t(r)},t.mapFloat=function(e,t){const r=v(e);return null==r?void 0:t(r)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,r){return b(e,(e=>b(t,(t=>r(e,t)))))},t.mapNumericOr=function(e,t,r){return a(e)?t(e):r},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const r=t-P(Math.ceil(Math.log10(Math.abs(e)))),i=Math.pow(10,Math.abs(r));return r<0?P(e/i)*i:P(e*i)/i},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!w(e))return[];const r=Math.round(e);return r<=0?[]:[...Array(r)].map(((e,r)=>t(r)))},t.pct=function(e,t){return E(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const r=Math.round(e??-1);return null==t||f(0,t,r)?r+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const r of e){if(!a(r))return;t+=r}return t}},68708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(32639),a=r(55835),l=r(31586),u=r(34666),c=r(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function g(e){return h(e).map((t=>e[t]))}function p(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const r of e)if(null!=r&&Array.isArray(r)){const[e,i]=r;null!=e&&void 0!==i&&("object"!=typeof t&&(t={}),t[e]=i)}return t}function v(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>null!=e)))return e;const r=t.filter((([,e])=>null!=e));return(0,i.isEmpty)(r)?void 0:y(r)}function w(e,t,r={}){return y((0,i.compact)((0,n.sort)(h(e)).map((r=>t(r,e[r])))).filter((([e,t])=>null!=e&&void 0!==t)),r)}function S(...e){const t=(0,i.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const r=t.filter(d);if(t.length!==r.length)return t;const n={};for(const e of(0,i.uniq)((0,i.flatMap)(r,h)))n[e]=S(...r.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const r=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(r.test(t))return{key:t,value:e[t]}}function P(e){return g(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const r=v(e);return m(r)?t(r):void 0},t.values=g,t.entries=p,t.fromEntries=y,t.assignFields=function(e,t,r){if(null==t)return e;for(const[i,n]of p(t))!0!==r?.omitKeys?.includes(i)&&(null==n&&!0!==r?.assignNullish||(e[i]=n));return e},t.assignUndefinedFields=function(e,t,...r){if(null==t)return e;for(const i of r){const r=t[i];void 0!==r&&void 0===e[i]&&(e[i]=r)}return e},t.assignAllFields=function(e,t){for(const[r,i]of p(t??{}))e[r]=i;return e},t.definedValues=function(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>void 0!==e)))return e;const r=t.filter((([,e])=>void 0!==e));return(0,i.isEmpty)(r)?void 0:y(r)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,i.compact)(t.map(e));{const r=(0,i.compact)(p(t).map((([t,r])=>(0,a.map)(e(r),(e=>[t,e])))));return 0===r.length?void 0:y(r)}}},t.compactBlankValues=function(e){if(null==e)return;const t=p(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,i.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickCompact=function(e,...t){if(null==e)return;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickNonBlank=function(e,...t){if(null==e)return e;const r={};for(const i of t){const t=e[i];(0,s.notBlank)(t)&&(r[i]=t)}return r},t.pickFirst=function(e,t,r=a.defined){if(null!=e)for(const i of t)if(r(e[i]))return e[i]},t.pickDeep=function e(t,...r){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...r)));const i={};function n(e,t){if(null==t)return;const r=i[e];i[e]=null==r?t:S(r,t)}for(const i of r){const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const i of h(t))((0,l.toInt)(i)??-1)>=0&&n(i,e(t[i],...r));return i},t.pluck=b,t.pluckDeep=function e(t,r){if(null==t||(0,s.blank)(r))return;if(Array.isArray(t)){const n=(0,i.compact)(t.map((t=>e(t,r))));return(0,i.isEmpty)(n)?void 0:{key:n[0].key,value:(0,i.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(r,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const r=p(e).filter((([e])=>!t.includes(e)));return(0,i.isEmpty)(r)?void 0:y(r)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(p(e).filter((([e,r])=>t(e,r))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,i.uniq)(t)},t.maybeCall=function(e,t,...r){const i=e?.[t];return(0,o.isFunction)(i)?i.bind(e)(...r):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const r=t.toLowerCase().normalize();for(const t of h(e))if(r===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const r=w(t,((t,r)=>[t,e(r)])),i=g(r);return 1===i.length?i[0]:r}},97790:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(r||(r={})),t.None=r;class i{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new i(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,r){return s(e).flatMap((e=>s(t).flatMap((t=>r(this.a,e,t)))))}zip3(e,t,r,i){return s(e).flatMap((e=>s(t).flatMap((t=>s(r).flatMap((r=>i(this.a,e,t,r)))))))}}function n(e){return e instanceof i||e===t.None}function s(e){return n(e)?e:null!=e?new i(e):t.None}t.Some=i,t.isOpt=n,t.opt=s},39926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const i=r(31586),n=r(54993),s={};function o(e,t){if(t<1)return"";if(!(0,i.gte)(s[e]?.length,t)){let r=s[e]??e;for(;r.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const i=r(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,i.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const i=r(40958),n=r(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,r){return o(e)?t(e):r()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,r){if(null==e&&null==r)return 0;if(null==e)return-1;if(null==r)return 1;const i=typeof e,s=typeof r;if(!("string"!==i&&"symbol"!==i||"string"!==s&&"symbol"!==s)){const i=(0,n.toS)(e),s=(0,n.toS)(r),o=i.localeCompare(s);return i[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(r)?u(e,r):i!==s?a.indexOf(i)-a.indexOf(s):e>r?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const i=r(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const r=await e;return null==r?void 0:t(r)},t.thenCollect=async function(e,t){const r=[];for(const n of(0,i.toA)(await e))if(null!=n){const e=await n;if(null!=e){const i=await t(e);null!=i&&r.push(i)}}return r},t.thenTap=async function(e,t=console.dir.bind(console)){const r=await e;return await t(r),r},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:r}){const i=await e;return t(i)?r(i):void 0}},57153:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const i=r(50989);t.PromiseStates=(0,i.strEnum)("pending","resolved","rejected")},30976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const i=r(40958),n=r(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,r){return null==r||0===r.length?s(e,t):a(e,t,1,r)[0]}function a(e,t,r,i){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(i??[]);if(t===e&&0===n&&0===o.size&&1===r)return[e];const a=n-o.size;if(r>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:r,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const r=Math.floor(Math.random()*(e+1));e!==r&&([t[e],t[r]]=[t[r],t[e]])}return t},t.sample=function(e,t){const r=[];for(const i of a(0,e.length,t))r.push(e[i]);return r},t.pickWeightedRandom=function(e){if((0,i.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let r=l(0,(0,i.sum)(t,(e=>e.priority)));return t.find((e=>(r-=e.priority,r<=0)))}},5670:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const i=r(50989);t.ServiceNames=(0,i.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const r=e.indexOf(t);return-1===r?[e]:[e.slice(0,r),e.slice(r+t.length)]}},50989:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const i=r(68708),n=r(42279);t.strEnum=function(...e){const t=Object.freeze(e),r=(0,i.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?r[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const r=o(e),i=o(t);return null==r||null==i?void 0:r>i?1:r{const r=o(e);return null==r?void 0:t[r]}}}},51926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const i=r(40958),n=r(17586),s=r(22573),o=r(96249),a=r(41801),l=r(31586),u=r(59455),c=r(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,r){if(d(e))return t<0&&(t+=e.length),e.slice(t,r);{const i=f();return null!=i?(0,a.sliceIterable)(i.segment(e),t,r).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,r).join("")}}function g(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function p(e,t){const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.startsWith(i)?r.slice(i.length):r}function y(e,t){if(null==t)return e;const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.endsWith(i)?r.slice(0,-i.length):r}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,r){null==r&&(r=e.length);for(let i=r;i>=0;i--)if(m(e,i).startsWith(t))return i;return-1}function b(e,t,{normalize:r=!0}={}){if(null==e||null==t)return!1;const i=(0,c.toS)(e),n=(0,c.toS)(t);return i.length===n.length&&(i===n||i.toLowerCase()===n.toLowerCase()||"function"==typeof i.localeCompare&&0===(r?i.normalize():i).localeCompare(r?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,i.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,r){return d(e)?e.slice(t,null==r?void 0:t+r):m(e,t,null==r?void 0:t+r)},t.charArr=g,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=p,t.stripPrefixes=function e(t,r){if(null==t)return"";const i=(0,c.toS)(t);for(const t of r)if(null!=t&&t.length>0&&i.startsWith(t))return e(i.slice(t.length),r);return i},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:r}){return y(p(e,t),r)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:r}){return w(v(e,t),r)},t.ellipsize=function(e,t=80,r=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),r=(0,l.clamp)(0,t-1,(0,l.round)(r));const i=g(e);return i.length<=t?i.join(""):i.slice(0,t-1-r).join("")+"…"+(r>0?i.slice(-r).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,r){const i=r?.maxLineLen??80,n=r?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const i=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(i.map((t=>e(t,r))))}if((t=v((0,c.toS)(t),n).trim()).length<=i)return[t];const s=S(t," ",i);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),r)];{const i=t.indexOf(" ",n.length+1);return i>0&&i{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const i=r(42659),n=r(68708),s=r(42279),o=r(83104),a=r(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,r=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(r,i)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,r(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,r(t))}catch(e){n&&(n=!1,i(e))}finally{clearTimeout(s)}}))}async function c(e,t,r=!0){const n=await u(e,t,r);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,r=!0){return u(e,t,r).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,r=!0){const i=t-Date.now();return i<=0?o.Timeout:u(e,i,r)},t.thenOrOnTimeout=async function(e,t,r){return t<=0?e:new Promise((async(i,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{i(await r())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),i(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,r=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(n)+")");return c(e,n,r)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:r,unref:i=!0}){if(null==e)return(0,s.tot)(r);const n=await u(e,t,i);return n===o.Timeout?(0,s.tot)(r):n}},42279:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const i=r(32639);t.tot=function(e){return(0,i.isFunction)(e)?e():e},t.tol=async function(e){return(0,i.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class r extends Error{}t.TimeoutError=r},12168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const i=r(22573),n=r(30301),s=r(31586),o=r(46891),a=r(50989),l=r(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let r=0;for(const i of e)(0,s.isNumber)(i)&&(r+=i/t.MB);return(0,s.round)(r)},t.fmt=c,t.fmtToInt=function(e){return(0,i.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const r=Math.floor(Math.log10(e)),i=Math.floor(r/3),n=Math.pow(10,3*i),o=d[i];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,r=3){return f(e*t.MB,r)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const r=Math.floor(Math.log2(e)),i=Math.floor(r/10),n=Math.pow(2,10*i),o=h[i];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,r){return null==e?"":(0,i.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(r??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,r){return r??(r=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:r}}},65812:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const i=r(68708);t.setUnrefTimeout=function(e,t){const r=setTimeout(e,t);return(0,i.maybeCall)(r,"unref")??r}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const i=r(41801),n=r(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,i.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const i=r(40958),n=r(23541),s=r(59455),o=r(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,i.compact)((0,s.toA)(e).map(a))}},54993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const i=r(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,i.stringify)(e)}}t.toStr=s},90858:e=>{e.exports=require("@iarna/toml")},58587:e=>{e.exports=require("batch-cluster")},6858:e=>{e.exports=require("commander")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},38064:e=>{e.exports=require("semver")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},77030:e=>{e.exports=require("node:net")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}var __webpack_exports__={},exports;exports=__webpack_exports__,Object.defineProperty(exports,"__esModule",{value:!0}),__webpack_require__(36389),module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={37975:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const i=r(1708),n=r(22573),s=r(38639);function o(){return(0,s.toNotBoolean)(i.env.PS_LOG_COLOR)??(!(0,n.blank)(i.env.NO_COLOR)||["dumb","unknown"].includes(i.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(r){return l()?`[${e}m${r}[${t}m`:r}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const i=r(19851),n=r(7282),s=r(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,i.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,i.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const i=r(40958),n=r(36783),s=r(76790),o=r(22573),a=r(50357),l=r(98553),u=r(55835),c=r(31586),d=r(68708),h=r(34666),f=r(59455),m=r(84885);var g=r(40958);function p(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,r=i.primitiveValueOfOrElse){const n=new Set(t.map(r));return e.filter((e=>n.has(r(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],r=e.lastIndexOf(t);return[{t,count:r+1},...v(e.slice(r+1))]}function w(...e){const t=[],r=Math.max(...e.map((e=>e?.length??0)));for(let i=0;ie?.[i])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function E(e,t){return(0,i.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,r){return C(e,t,r).index}function C(e,t,r){if((0,i.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let i=0;ie.slice(r,r+t)))}async function x(e,t){return(0,i.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return g.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return g.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return g.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=p,t.mapAllDefined=function(e,t){return p(e)?t(e):void 0},t.mapAll=function(e,t){return p(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const r of(0,f.toA)(e))if(null!=r&&!0===await t(r))return r},t.findLastAsync=async function(e,t){for(let r=(e=(0,f.toA)(e)).length-1;r>=0;r--){const i=e[r];if(null!=i&&!0===await t(i))return i}},t.first=function(e,t){if(null!=e)for(const r of(0,f.toA)(e))if(null!=r){const e=t(r);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null!=i){const e=await t(i,r);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,i.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,r){for(let i=r;i<=e.length-1;i++)if(t(e[i]))return i},t.findLast=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},t.findLastIndex=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},t.concat=function(...e){const t=[];for(const r of e)if(Array.isArray(r))for(const e of r)null!=e&&t.push(e);else null!=r&&t.push(r);return t},t.moveToEnd=function(e,t){return(0,i.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const r=e[t];if(null==r)return e;e.push(r);for(let r=t;r(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const r=e.findIndex(t);return r>=0?e.splice(r,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,i.uniqBy)(e,t),e)},t.partition=function(e,t){const r=[],i=[];let n=0;for(const s of e)(t(s,n++)?r:i).push(s);return[r,i]},t.isUniq=function(e){return e.every(((t,r)=>e.indexOf(t)===r))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,i.compact)((0,i.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),r=[];return(0,c.times)(t,(t=>e.map((e=>r.push(e?.[t]))))),r},t.unFlatZip=function(e,t){const r=e.length/t;if(r!==Math.round(r))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const i=(0,c.times)(t,(()=>new Array(r)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=E,t.least=function(e){return E(e,(e=>e))},t.greatestBy=function(e,t){return(0,i.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const r=C(e??[],t,h.lt);return null==e||null==r||r.index<0||null==r.value?void 0:{result:e[r.index],index:r.index,value:r.value}},t.reverse=function(e){const t=[];for(let r=e.length-1;r>=0;r--)t.push(e[r]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(r(s)));return n},t.collectBatchedAsync=async function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(await r(s)));return n},t.contextFilter=function(e,t){let r;return e.filter(((e,i)=>(0,d.tap)(t(e,i,r),(t=>{t&&(r=e)}))))},t.clusterSome=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.some((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterEvery=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.every((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterAsync=async function(e,t){const r=[];e:for(const i of e){for(const e of r)if(null!=i&&await x(e,(e=>t(i,e)))){e.push(i);continue e}null!=i&&r.push([i])}return r},t.someAsync=async function(e,t){if(null!=e)for(let r=0;r=0&&!0===(0,u.map)(e[i],(e=>r(e,i))))return i}{const i=t+n;if(ie+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,r){return e.lengthr))),e}},36557:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=r(77988),l=o(r(1708)),u=r(19851),c=r(42659),d=r(55835),h=r(31586),f=r(85556),m=r(54993),g=r(50213),p=r(79089),y=r(45255),v=r(25764),w=r(38836),S=r(99331),b=r(95937),P=r(98314),_=r(38835),E=r(70025),M=r(8769),C=r(43334),T=r(95402),x=r(28874),D=r(63870);class k extends w.EndableWrapper{constructor(e,t,r=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,i,"m",n).call(this)),r,"worker"===e?(0,D.commandTimeoutMs)():y.ShortCommandTimeoutMs),i.add(this),this.t=t;const o=t;o.on("childStart",(async r=>{null!=r.pid?(this.logger.info("Started child process",{pid:r.pid}),(0,p.renice)(r.pid).catch((e=>this.onError("renice failed",e))),(0,T.addPid)({pid:r.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,r,i)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&T.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,E.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=k,i=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(C.isWin?3:1)*c.minuteMs,maxTasksPerProcess:x.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:x.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:x.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,g.mkLogger)(t))),spawnTimeoutMillis:(0,D.commandTimeoutMs)(),taskTimeoutMillis:x.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=r(92460),d=r(31586);class h{constructor(e){if(i.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,r;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,i,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,r;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,i,"m",a).call(this,0,(e=>{var t,r;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(r=u(this,s,"f"),--r),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,i,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const r=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=r}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const i=r(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:r}of n)if(o(e,t))return e.subarray(t.length).toString(r);return e.toString()}function o(e,t){return t.every(((t,r)=>e[r]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,i.toS)(e)},t.bufferStartsWith=o},9092:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,r]of e)this.set(t,r)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const r=this.normalizer(e);return null!=e&&null!=r&&this.store.set(r,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=r(40958),a=r(23838),l=s(r(68708)),u=r(59455),c=r(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const r of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(r,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const r=this.lookup(e);if(null!=r)return r;let i,n=-1;for(const[r,s]of this.m.entries()){const o=(0,c.diceCoeff)(r,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(i=e,n=o)}}return i}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),r=this.m.get(t);if(null!=r){for(const e of r)delete this.obj[e];this.m.delete(t)}return r}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const i=r(76790),n=r(31586),s=r(68708),o=r(54993),a=r(82647),l=r(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const r=this.get(e)+t;return 0===r?this.m.delete(e):this.m.set(e,r),r}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,r]of this.m.entries())e[(0,o.toS)(t)]=r;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,i.sortBy)([...this.entries()],(([t,r])=>[-r,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,r]of(0,i.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,r);return e}addAll(e){for(const[t,r]of e.entries())this.incr(t,r);return this}get toS(){return(0,i.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let r=0;for(const[i,n]of this.m.entries()){const s=e(i);t.fill(s,r,r+n),r+=n}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const i=r(19851),n=r(72993),s=r(45969),o=r(43334);t.EditionType=(0,i.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,i.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const i=r(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),r=t-this.ts;this.ts=t,(0,i.map)(this.listener,(t=>t(e,r))),r>2&&this.l.log(r>500?"warn":r>100?"info":"debug",e,{elapsedMs:r})}},t.elapsed=function(e){const t=Date.now(),r=e();return{elapsedMs:Date.now()-t,result:r}},t.thenElapsed=async function(e){const t=Date.now(),r=await e;return{elapsedMs:Date.now()-t,result:r}}},23467:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const i=r(50357),n=r(55835),s=r(68708);var o=r(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,i.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,i.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,i.eql,(()=>!1))},t.eqlPicked=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))},t.eqlOmit=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.omit)(e,...r),(0,s.omit)(t,...r))},t.eqlAsyncPicked=async function(e,t,...r){return(0,n.map2Or)(await e,await t,((e,t)=>(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))),(()=>!1))}},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(31586),a=r(54993),l=r(77377),u=r(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const r of this.expireListeners)r(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[i.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const r of this.expireListeners)r(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const r of this.expireListeners)r(e,t)}const r=this.priorCache[e];if(void 0!==r&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,r)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const r=this.currentCache[t]??this.priorCache[t];null!=r&&e(t,r)}}deleteIf(e){for(const t of this.keys()){const r=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=r&&e(t,r)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const r=t();return this.set(e,r),r}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=r(31586),d=r(85556),h=r(54993),f=r(54557),m=r(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,i.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,i,l(this,i,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,i,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,r,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(r=l(this,n,"f"),++r),"f"),c.promise):(u(this,i,(o=l(this,i,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,i,(a=l(this,i,"f"),++a),"f"),c}get(e){var t,r;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,i,(r=l(this,i,"f"),++r),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,i,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const r=this.get(e);if(null!=r){if(r instanceof Error)throw r;return r}return this.set(e,t())}getOrSetAsync(e,t){const r=(0,h.toS)(e);{const e=this.get_(r);if(null!=e)return e instanceof m.Deferred?e.promise:e}const i=new m.Deferred(this.opts.name).observe(t());return this.cache.set(r,i),(0,c.gt0)(this.opts.timeoutMs)&&i.setTimeout(this.opts.timeoutMs),i.promise.then((e=>{this.set(r,e)}),(e=>{var t,i;this.cache.set(r,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(i=l(this,a,"f"),++i),"f")})),i.promise}},i=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class i{constructor(e){this.maxSize=e,this[r]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(r=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=i},53507:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(31586),a=r(68708),l=r(50213),u=r(68852),c=r(81168),d=r(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,i.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,r=!0){return new m(e,t,r).entries};class m{constructor(e,t,r=!0){this.warnIfMissingHeaders=r,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const i=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,i).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let r=e;r!==t;t>e?r++:r--)if(this.blankColumns.has(r))return r;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),r=[];let i,a=0;for(;null!=(i=t.exec(this.headerRow));){const l=this.headerRow.substring(a,i.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:i.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(i.index,t.lastIndex),d=i.index+((0,c.indexOfNonSpace)(u)??0),h=i.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),g=e.find((e=>e.text===m));if(null==g||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:i,left:d,right:h});else{const e=(0,n.last)(r);if(r.push(g),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=g.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,i.index-((0,c.lastIndexOfNonSpace)(l)??l.length));g.leftIdx=g.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),g.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(r);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),r}}t.Fixed=m},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const i=r(51455),n=r(98553);var s=r(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const r=(0,n.parseJSON)(e);return null==r?void 0:t(r)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,i.readFile)(e)).toString())}},19851:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=r(57975),a=r(40958),l=r(50357),u=r(31586),c=r(65812),d=r(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),i.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,i,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const r=await e,i=await t;if(!(0,l.eql)(r,i))for(const e of this.watchers)e(i);null!=this.ttlMs&&this.ttlMs>0&&void 0!==i&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(42659),a=r(50213),l=r(81168),u=r(5916),c=r(56519),d=r(84777),h=r(44198),f=r(6012),m=r(43334),g=r(24399),p=r(63870);t.DefaultLocale="en";const y=(0,i.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?E():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,p.commandTimeoutMs)()}),t.envLocale=(0,i.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const r=w.exec(e.trim())?.groups;return null==r?void 0:(0,n.compact)([r.lang,r.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(g.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function E(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=E,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const i=r(48161),n=r(1708),s=r(45599),o=r(68708),a=r(50213),l=r(88158),u=r(96175),c=r(23560),d=r(84968),h=r(37805),f=r(9727),m=r(3790),g=r(29325),p=r(43334),y=r(28874);t.logStartup=(0,s.defer)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:n.argv,arch:(0,i.arch)(),platform:(0,i.platform)(),os:(0,u.osFullName)(),isPacked:(0,g.isPacked)(),isElectron:p.isElectron,versions:(0,o.pick)(n.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:n.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const i=r(19851),n=r(32105),s=r(14593);t.rootLoggers=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},9103:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const i=r(98553),n=r(54557);t.memoize=function(e,t){let r=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return r++,s.getOrSet((0,i.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,i.stringify)(e)),o.size=()=>s.size,o.callCount=()=>r,o}},7282:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=i(r(1708)),s=r(38639),o=r(54993),a=r(19851),l=r(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(55835),a=r(31586),l=r(39926),u=r(54993),c=r(20014);var d=r(31586);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,r){return(0,o.orElse)(h(e,t),r)},t.mapGte0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>=0?t(r):void 0},t.mapGt0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>0?t(r):void 0},t.mapGt0=function(e,t){const r=(0,a.toInt)(e);return null!=r&&r>0?t(r):void 0},t.map2Gt0=function(e,t,r){const i=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=i&&i>0&&null!=n&&n>0?r(i,n):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(f.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(m(e))}function p(e,t){if(null==e||null==t)return;const r=[e,t].map((e=>e.toString(2))),i=Math.max(...r.map((e=>e.length)));return r.map((e=>(0,l.leftPad)(e,i,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let r=0;for(let i=0;ie/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,r){this.store[e*this.columns+t]=r}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(p(e,t),(([e,t])=>(0,i.count)([...e],((e,r)=>e!==t.charAt(r)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(p(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,i.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,r){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let i=0;const n=r*e.length;for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const i=r(40958),n=r(42659),s=r(96249),o=r(55835),a=r(31586),l=r(68708),u=r(34666),c=r(41583),d=r(48884),h=r(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const r={};for(const[i,n]of(0,l.entries)(e)){const e=t(i,n);null!=e&&(r[i]=e)}return r}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const r of e){const e=r();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(r=>t(r,e[r])?e[r]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,r){if(null!=e)return t(e);throw new Error(r)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,i.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[r,i]of m(t))null==e[r]&&(e[r]=i);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[r,i]of(0,l.entries)(t))null==e[r]&&(e[r]=i);return e},t.pickMap=function(e,t,r){const i={};for(const n of t)i[n]=r(n,e[n]);return i},t.mapEntries=g,t.mapNullEntries=function(e,t,r){const i={};let n=0;for(const s of(0,l.keys)(e))if(i[s]=t(s,e[s]),n++,(0,a.gt)(n,r))break;return i},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const r={};for(const i of(0,h.sortIgnoreCase)((0,l.keys)(t)))r[i]=e(t[i]);return r}return t},t.deepDelete=function e(t,...r){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...r))):g(t,((t,i)=>r.includes(t)?void 0:e(i,...r)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const r of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[r])return e[r]}},t.pairToObject=function(e,t){const r={};return r[e]=t,r},t.zipPojos=function(...e){const t={};for(const r of(0,i.uniq)((0,s.flatten)(e.map(l.keys))))t[r]=e.map((e=>e?.[r]));return t}},96175:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const i=r(31421),n=r(73024),s=r(48161),o=r(19851),a=r(22573),l=r(42659),u=r(55835),c=r(51926),d=r(54993),h=r(48884),f=r(50213),m=r(6012),g=r(45969),p=r(43334),y=r(76280),v=r(30933),w=(0,o.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return k();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,g.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function _(){return"ubuntu"===(0,t.osDistributionLinux)()}function E(){return"fedora"===(0,t.osDistributionLinux)()}function M(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(p.isLinux)for(const e of b)try{const t=(0,n.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>p.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=_,t.hasApt=function(){return P()||_()},t.isFedora=E,t.isAlpine=M;const C={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},T={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function x(e,t){const[r,i]=function(e){return e.split(".").slice(0,2)}(e),n=t[r];return(0,c.isString)(n)?n:n?.[i]}const D=(0,o.lazy)((()=>(0,i.execSync)("sw_vers -productVersion").toString().trim()));function k(e=D()){try{return(0,a.mapNotBlankOr)(function(e=D()){return x(e,C)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":x(e,T);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=k,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(p.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(p.isMac){const e=D();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(p.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(_())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(E())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(M())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},12801:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=i(r(48161)),s=r(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const i=r(41400),n=r(56409),s=r(31586),o=r(22911),a=r(73614),l=r(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:r,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const g=[];function p(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...i){f=!0,m=Date.now()+(0,s.max_)(t,r);const n=d=new o.Deferred(c);(0,s.gt0)(r)&&n.setTimeout(r);try{n.resolve(await e(...i))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),g.forEach((e=>e.resolve())),g.length=0}return n.promise}const w=(...e)=>{if(p()){if(!0===u)return null;const t=d?.promise;return h=e,(0,i.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return g.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>p(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const i=r(68708),n=r(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const r=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:r.push((0,i.pick)(n,"index","groups"));return r},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,r){const i=[];for(const t of e)try{i.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{i.push(s(t))}const n=0===i.length?t.NothingRegExp:i.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,r)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let r="",i=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(r+=t.source,i||(i=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):r+=s((0,n.toS)(t));return new RegExp(r,t??(i?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=i(r(48161)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(42659),u=r(41400),c=r(96249),d=r(31586),h=r(51926),f=r(54993),m=r(50213),g=r(12801),p=r(22277),y=r(84777),v=r(34102),w=r(43334),S=r(24399),b=r(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let E=!0;const M=(0,o.lazy)((()=>new p.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const r=(0,g.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=g.PriorityClassToNode[r]),E)try{return n.default.setPriority(e,t),t}catch(r){const i=-13===r?.errno||"EACCES"===r?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:i,error:r}),i)return;E=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&g.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,r):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,g.PriorityClassToPosix[r]??g.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+r),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=i(r(1708)),s=r(19851),o=r(40958),a=r(5670),l=r(54993),u=r(7282),c=r(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function g(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=g,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||g())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||g())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const i=r(59455);function n(e){return e instanceof Set?e:new Set((0,i.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,i.toA)(e.keys()).every((e=>t.has(e)))&&(0,i.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,r){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),r())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const r=n(t);return new Set([...e].filter((e=>r.has(e))))},t.diff=function(e,t){const r=n(t);return new Set([...e].filter((e=>!r.has(e))))}},19913:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const i=r(5670),n=r(57150),s=r(7282),o=r(23560),a=r(17181);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=i.ServiceNames.main);const t=o.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,a.setupLogger)(),(0,n.logStartup)())}},12089:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=r(98553),d=r(34666),h=r(54993),f=r(62344),m=r(56038);t.shim1=function(e){return new g(e.name,e.impl,e.cache,e.toKey)};class g extends f.ExtensibleFunction{constructor(e,t,r,o){super(),i.add(this),this.impl=t,this.cache=r,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,i,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,i,"m",o).call(this,e),(()=>u(this,i,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,i,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,i=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const i=r(42659);t.ShortCommandTimeoutMs=7*i.secondMs},92322:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=r(76790),o=r(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,i.set(this,[])}[(i=new WeakMap,Symbol.iterator)](){return n(this,i,"f")[Symbol.iterator]()}get length(){return n(this,i,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,r=n(this,i,"f").length-1;for(;t<=r;){const s=t+Math.floor((r-t)/2),o=this.valueOf(n(this,i,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:r=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,i,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:r}){if(t>=this.length)return[...n(this,i,"f")];const o=t=>t<0||t>n(this,i,"f").length-1?null:(r??this.diff)(n(this,i,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return n(this,i,"f").shift()}at(e){return(0,o.at)(n(this,i,"f"),e)}toA(){return[...n(this,i,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,i,"f").length-1){const e=[...n(this,i,"f")];return n(this,i,"f").length=0,e}return n(this,i,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,i,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const i=r(1708),n=r(82328),s=r(84542),o=r(95705),a=r(28874);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(i.stderr)||i.stderr.write(e)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},82328:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const i=r(1708),n=r(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(i.stdout)}},71567:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=i(r(1708)),s=r(22573),o=r(98553),a=r(23560),l=r(82328),u=r(38835),c=r(70025),d=r(95705);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:r,stream:i}){if(null==i||(0,d.streamEnded)(i))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);i.write(n+"\n"),(0,a.isWorkerService)()&&null!=r&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?i.write(u.FailStr+"\n"):i.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const r of e)r.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(55835),a=r(31586),l=r(39926),u=r(34666),c=r(51926),d=r(59455),h=r(54993),f=r(48884),m=r(68852),g=r(38835);var p=r(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return p.splitFirst}});var y=r(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=r(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,r){if(0===r.length)throw new Error("rightPad() given empty pad");const i=String(e);return i+(0,l.padding)(r,t-i.length)},t.padReplace=function(e,t,r,i){return(0,c.strslice)(e,0,t)+(0,l.padding)(i,r)+(0,c.strslice)(e,t+r)},t.contains=function(e,t,r){return(0,h.toS)(e).indexOf((0,h.toS)(t),r)>-1},t.countChars=function e(t,r,i=0){if(null==r||0===r.length)return 0;const n=t.indexOf(r,i);return-1===n?0:1+e(t,r,n+r.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,r){const i=Math.min(Math.ceil(e.length/t),r??e.length)-1;return i<=0?[e]:[...(0,a.times)(i,(r=>e.slice(r*t,(r+1)*t))),e.slice(i*t)]},t.spliceCapture=function(e,t){const r=t.exec(e);if(null==r||null==r[1])return;const i=r[0].indexOf(r[1])+r.index;return{captured:r[1],uncaptured:e.substring(0,i)+e.substring(i+r[1].length),unmatched:e.substring(0,r.index)+e.substring(r.index+r[0].length),matchedIndex:i}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,r={}){if(null==t)return e;const i=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(i.slice(-n.length),n,r)?i.slice(0,-n.length):i},t.gist=function(e,t=80,r=80){const i=(0,h.toS)(e),n=i.length-(t+r);return n<=0?i:i.slice(0,t).trim()+" …(+"+n+" chars)…"+i.slice(-r).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const r=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===r?e.localeCompare(t):r}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,i.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,o.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const r=S(e.cmp[0],t.cmp[0]);return 0!==r?r:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,i.isEmpty)(e)||(0,s.blank)(t))return;for(const r of e)if((0,c.equalsIgnoreCase)(r,t))return{index:0,match:r};for(const r of e){const e=t.indexOf(r);if(e>=0)return{index:e,match:r}}const r=t.normalize();for(const t of e){{const e=r.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=r.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=r.toLowerCase(),i=e.toLowerCase(),n=t.indexOf(i);if(n>=0)return{index:n,match:i}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function E(e){return _.reduce(((e,[t,r])=>e.replace(t,r)),e).normalize()}t.dumbquote=E;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(E(e))&&(e=e.slice(1,-1).trim())),e};const C=/^['‘’].*['‘’]$/,T=/^["“”„«»〃].*["“”„«»〃]$/;function x(e,t){const r=D(e,t);return(0,f.flatZip)(r.nonSeparators,r.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+g.NonRetriableErrorFlag);const r=[],i=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,r.push(e.substring(s,n.index)),i.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),C.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const r=(0,i.compactBlanks)(e),n=Math.max(...r.map((e=>e.length)));for(let e=0;e(0,o.map)(r[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,i.compactBlanks)(e)),r=t.filter(((e,r)=>!P(t[r+1],e)));return(0,n.sortBy)(r,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const r=Math.min(e.length,t.length);for(let i=0;i4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const r=new Set;for(const i of(0,d.toA)(e))if(null!=i&&!(0,s.blank)(i))for(const e of i.split(t))(0,s.blank)(e)||r.add(e);return[...r].join(t)},t.dedupeNeedle=function(e,t,r){if((0,s.blank)(t))return e;const i=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>i.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(r)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const i=r(54993);function n(e){return(0,i.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>"_"+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>" "+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=i(r(77598)),s=r(73913),o=r(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,r=o.Radix58,i=224){return r.encodeBuffer(a(e,i)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,r=o.GeoRadix,i=224){return l(e,t,r,i)}},94863:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const i=r(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,i.toS)(e).toLowerCase().normalize()}},96859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(31586),a=r(39926),l=r(51926),u=r(54993),c=r(55222),d=r(97352),h=r(88158),f=r(77377),m=r(81168);function g(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const r=new d.Array2D(e.length);let i=0,n="";for(let s=0;s=i&&(i=r.get(s,o),n=(0,l.substr)(e,s-i+1,i)));return n}function p(e,t){if(null==e||null==t)return;if(e===t)return 0;const r=y(e,t);if(null!=r)return r;const i=e.normalize(),n=t.normalize();return e!==i||t!==n?y(i,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,r,i)=>r===t.charAt(i)?e:e+1),0)}function v(e,t){const r=e.toUpperCase().normalize(),i=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>r===i?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(r),t=w(i);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,r)=>e+t[r+1]))}function S(e,t){const r=(0,f.intersection)(e,t),n=[];return r.forEach((r=>{const s=Math.min((0,i.count)(e,(e=>e===r)),(0,i.count)(t,(e=>e===r)));(0,o.times)(s,(()=>n.push(r)))})),n}function b(e,t,r){const n=(0,i.commonPrefixLength)(e,t);return r((0,l.strslice)(e,n))-r((0,l.strslice)(t,n))}function P(e){const t=(0,i.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[r,i]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(r,i,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:g(e,t).length/Math.max(e.length,t.length)},t.lcs=g,t.hamming=p,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const E=/[^\da-z]+/gi;function M(e,t){const[r,i]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(E,"").toLowerCase()));return b(r,i,(e=>c.RadixAlphaNum.decode(e)))}function C(e,t){let r;for(let i=Math.max(e.length,t.length);i>=0;i--){const n=(0,o.mapNumericOr)(e.charCodeAt(i),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(i),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);r=null==r?a:(r+a)/2}return r}t.radixDiff=M,t.str=function(e,t){return{pref:(0,i.commonPrefixLength)(e,t),ham:p(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,i.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=C,t.paddedPositionalDiff=function(e,t,r=8){return C((0,a.leftPad)(e,r," "),(0,a.leftPad)(t,r," "))}},84885:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const i=r(98553),n=r(88158);t.stringifySorted=function(e){return(0,i.stringify)((0,n.sortedKeys)(e))}},22277:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=r(73614);class u{constructor(e,t=!1){i.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,i,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,i,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const r=this.delegate.get(e);return null==r||a(this,i,"m",n).call(this,e,r)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,r]of this.delegate)a(this,i,"m",n).call(this,t,r)||e(t,t,this)}has(e){return null!=e&&!a(this,i,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield[t,t])}()}toA(){return a(this,i,"m",s).call(this),[...this.delegate.keys()]}[(i=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const r=t<=Date.now()-this.ttlMs;if(r){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return r},s=function(){for(const[e,t]of this.delegate)a(this,i,"m",n).call(this,e,t)}},94174:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(38639),c=r(31586),d=r(50213),h=r(45255),f=r(84777),m=r(96706),g=r(43334),p=r(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>g.isWin?p.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>g.isWin?g.isWin?p.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const i=r(42659),n=r(55835),s=r(31586),o=r(97790),a=r(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const r=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(r))return;const[o,a,u,c,d,h,f]=r,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*i.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+i.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class r extends Error{}t.AbortError=r},76740:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=r(45599),l=r(56409),u=r(73568);t.Abortable=class{constructor(){this._aborted=!1,i.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,i,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,i,"f")&&clearTimeout(s(this,i,"f")),o(this,i,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},i=new WeakMap,n=new WeakMap},22911:function(e,t,r){var i,n,s,o,a,l,u,c,d,h,f,m,g=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(r(87997)),w=y(r(57975)),S=r(45599),b=r(26905),P=r(55835),_=r(31586),E=r(68708),M=r(20214),C=r(57153),T=r(85556),x=r(50213),D=r(70025),k=r(95937),O="TIMEOUT",I=(0,S.defer)((()=>(0,x.mkLogger)("async.Deferred")));class L{static async*toAsyncIterable(e,t){const r=[...e].reverse(),i=(0,_.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=i&&r.push(i);;){for(let i=r.length-1;i>=0;i--){const n=r[i];if(n.isSettled){if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});r.splice(i,1),yield n.value}}if(r.every((e=>e.name===O)))break;try{await Promise.race(r)}catch{}}i?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var r,m,y;i.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,C.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(p(r=n,n,(y=g(r,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{p(this,u,e,"f"),p(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return g(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:g(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,E.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return g(this,o,"f")}get elapsedMs(){return(g(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,i=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=g(this,h,"f")&&(v.default.clearTimeout(g(this,h,"f")),p(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(p(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),g(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return g(this,a,"f")===C.PromiseStates.pending}get value(){return this.isResolved?g(this,l,"f"):void 0}get error(){return g(this,d,"f")}get isSettled(){return g(this,a,"f")!==C.PromiseStates.pending}get isResolved(){return g(this,a,"f")===C.PromiseStates.resolved}get isRejected(){return g(this,a,"f")===C.PromiseStates.rejected}get settledMs(){return null==g(this,o,"f")?void 0:g(this,o,"f")-this.startedAt}resolve(e){return g(this,i,"m",m).call(this,(()=>{p(this,a,C.PromiseStates.resolved,"f"),p(this,l,e,"f"),g(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return g(this,i,"m",m).call(this,(()=>{p(this,d,t,"f"),p(this,a,C.PromiseStates.rejected,"f"),g(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=L,n=L,m=function(e){if(g(this,a,"f")===C.PromiseStates.pending){(0,P.map)(g(this,h,"f"),v.default.clearTimeout),e(),p(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:g(this,l,"f")});return this},s={value:0}},27395:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const i=r(19851),n=r(40958),s=r(42659),o=r(23838),a=r(13538),l=r(50213),u=r(7282),c=r(97352),d=r(77740),h=r(25764),f=r(99331),m=r(73614),g=(0,i.lazy)((()=>(0,l.mkLogger)("async.Endable"))),p=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const r=await e;if(null==r||!0===r?.ended)return;const i=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,r.endTimeoutMs,y);g().trace(r.name+" ending...",{timeoutMs:i});try{await(0,a.thenOrTimeoutError)(r.end(),i,(0,u.isTest)())}catch(e){try{g().warn(r.name+".end() failed",e)}catch{}}}function w(){p.filterInPlace(((e,t)=>!0!==t.ended)),g().debug("vacuumEndables()",p.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),p.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,i.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;g().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const r=p.get(t)??[];(0,n.isNotEmpty)(r)&&(g().debug("endEndables(): ending "+t),await Promise.allSettled(r.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,n.compact)(p.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const r=p.get(t)??[];e[t]=r.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,r){var i,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=r(87997),h=r(55835),f=r(31586),m=r(68708),g=r(25764),p=r(38836),y=r(99331);class v extends p.EndableWrapper{constructor(e){super(e.name,(()=>u(this,i,"m",o).call(this)),e.rank??g.EndableRanks.first,e.endTimeoutMs),i.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,r=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!r&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,i,"m",o).call(this);const h=()=>{u(this,i,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,i,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,i=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const i=r(50989);t.EndableRanks=(0,i.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=r(19851),l=r(45599),u=r(56409),c=r(50213),d=r(27395),h=r(25764),f=r(99331),m=r(56519);t.EndableWrapper=class{constructor(e,t,r=h.EndableRanks.first,o){this.endTimeoutMs=o,i.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(r,this)}setName(e){o(this,i,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,i,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},i=new WeakMap,n=new WeakMap},99331:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const i=r(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,i.isTest)()?e:e||n}},45608:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=i(r(1708)),s=r(22573),o=r(45599),a=r(37975),l=r(50213),u=r(71567),c=r(57159),d=r(57902),h=r(28874),f=r(27395),m=r(99331),g=r(56038),p=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(g.PromiseTimer.instance().report())}));async function v(e){p().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const r=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==r.errno||!0===r.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const i=(0,s.toNotBlank)(e?.reason)??r.toString();for(const e of t.onFatalHandlers)await e(i)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(r=>{v({reason:`${e}:${t}`,status:0,error:r})}))}))},5916:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=r(45599),f=r(50357),m=r(31586),g=r(41583),p=r(62344),y=r(50213),v=r(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:r,timeoutMs:i}){return new S(e,t,r,i)};class S extends p.ExtensibleFunction{constructor(e,t,r,l){super(),i.add(this),this.later=e,this.desc=t,this.ttlMs=r,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,i,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,i,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,i,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=async function(e,t){var r;try{const r=await t;if(!(0,f.eql)(e?.value??await(e?.promise),r))for(const e of c(this,a,"f"))await e.onChange(r)}catch(e){const t=(0,g.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(r=c(this,s,"f"),++r),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,i,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},56519:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const i=r(40958),n=r(76790),s=r(38639),o=r(42659),a=r(41400),l=r(31586),u=r(20214),c=r(13538),d=r(42279),h=r(32639),f=r(59455),m=r(41583),g=r(48884),p=r(50213),y=r(88158),v=r(15674),w=r(42638);var S=r(20214);async function b(e){if(null==e)return[];const t=(0,i.compact)(await e);return(0,i.isEmpty)(t)?[]:(0,i.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:r,timeoutMs:n}){const s=[];for(const o of(0,i.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(r(o),n):r(o));null!=e&&s.push([e,o])}catch(t){(0,p.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:r,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,i.compact)(await e);if((0,i.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:r,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(r,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(r,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,p.mkLogger)(r).warn("failed to apply",{ea:e,error:t})}})));return(0,i.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,r){const i=[];for(const n of(0,g.batches)((0,f.toA)(await e),t)){const e=await b(n);i.push(...await b(r(e)))}return i},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const r of(0,i.compact)(e)){const e=await r();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;if(null!=e)if(Array.isArray(e))for(const r of e){const e=await r;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;null!=e&&t.push(e)}return(0,i.uniq)(t)},t.asyncFind=async function(e,t){for(const r of e)if(await t(r))return r},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:r,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,i.compact)(t),f:r,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const r=await E({name:"partitionAsync",arr:e,f:t});return[r.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),r.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,r=(e=>console.error(e)),i=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,i)}catch(e){r((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),r=(()=>{})){let i,n=null;try{i=await((0,h.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await r(n??i)}catch{}if(null!=n)throw n;return i},t.thenNot=async function(e,t=!0){if(null==e)return t;const r=await e;return null==r?t:!(0,s.isTrue)(r)},t.thenMap2=async function(e,t,r){const i=await e;if(null==i)return;const n=await t;return null!=n?r(i,n):void 0},t.thenMapOr=async function(e,t,r){const i=await e;if(null==i)return r();const n=await t(i);return null==n?r():n},t.thenMap2Or=async function(e,t,r,i){const n=await e;if(null==n)return i();const s=await t;if(null==s)return i();const o=await r(n,s);return null==o?i():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null==i)continue;const e=await t(i,r);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const r of e){const e=await r();if(null!=e){const r=await t(e);if(null!=r)return r}}},t.firstResolvedDefinedPromise=async function(e,t){for(const r of e)try{const e=await r();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const r of t)try{const t=await r();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:r}){const i=await E({name:e,arr:t,f:r});return(0,n.sortBy)(i,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const i=r(19851),n=r(40958),s=r(76790),o=r(42659),a=r(49769),l=r(31586),u=r(68708),c=r(42279),d=r(41583),h=r(22454),f=r(14121),m=r(50213),g=r(7282),p=r(34102),y=r(82647),v=r(25764),w=r(38836),S=r(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,r){const i=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-i)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-i;return r?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),r?.((0,d.toErr)(t),Date.now()-i),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),r=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),i=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",r.stats()],...i])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:r.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:(0,l.mapFinite)(r.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:r.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:{sumSec:(0,l.sigFigs)(r.sum/o.secondMs,3),...(0,u.omit)(r.stats(),"sum")}})),{})}}function _(e,t,r){return P.instance().time(e,t,r)}function E(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,i.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.isTest)()&&(0,p.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const r=Date.now(),i=t();return E(e,Date.now()-r),i},t.pushTime=E,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,r){return(0,i.lazy)((async()=>_(e,t)),r)}},42638:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(r(66261)),m=r(40958),g=r(55835),p=r(31586),y=r(42279),v=r(54993),w=r(89788),S=r(82647),b=r(15674),P=r(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){i.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,p.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:r,serialId:n}){const s=d(this,i,"m",l).call(this,{name:e,l:t,payload:r,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const r=t.map((t=>d(this,i,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(r)}serial(e,t,r){return this.enqueue({name:e,l:t,serialId:e,payload:r})}push(e,t,r){return d(this,i,"m",u).call(this,new P.Deferred(e,{payload:r}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),r=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,p.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=function({name:e,l:t,payload:r,serialId:i}){const n=new P.Deferred(e,{payload:r,serialId:i});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const r=Date.now();return this.lastWorkTs=r,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-r),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const r=new _(e);return()=>r.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:r}){return new _(e,(0,g.map)(r,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class r extends Error{}t.RedoableError=r},4867:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const i=r(40958),n=r(34546),s=r(41400),o=r(31586),a=r(83104),l=r(85556),u=r(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:r}){let a=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,r?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:r}){let l=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,r?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let r=e=>null;t.setTimeoutHandler=function(e){r=e},t.onTimeout=function({soft:e}={}){r(e)}},73614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const i=r(87997);t.setUnrefTimeout=function(e,t,...r){return(0,i.setTimeout)(e,Math.round(t),...r).unref()},t.setUnrefInterval=function(e,t,...r){return(0,i.setInterval)(e,Math.round(t),...r).unref()}},31562:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const i=r(38639),n=r(42659),s=r(41400),o=r(32639),a=r(31586),l=r(45255),u=r(95937);async function c(e,{timeoutMs:t,intervalMs:r,acceptable:i,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const i=r??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(i,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:i.isTrue,timeoutResult:!1})}},9727:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=i(r(1708)),s=r(45599),o=r(41400),a=r(50357),l=r(68708),u=r(48884),c=r(36638),d=r(44198),h=r(59958),f=r(96706),m=r(34102),g=r(19851),p=r(19043),y=r(66184),v=r(50213),w=r(7282),S=r(88158),b=r(45969),P=r(43334),_=r(28874),E=r(3790);function M(e){return C().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const C=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const r of t.names)e.add(r);for(const r of t.keys)e.add(r)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const T=["HOME","LANG","USER"],x=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],D=(0,g.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?T:x),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function k(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const r of(0,_.persistedSettings)()){const i=e?r.value:r.envValue;null==i||(0,a.eql)(i,r.defaultValue)||r.addToEnv(t)}return t}t.sanitizedEnv=(0,g.lazy)((()=>(0,l.filter)(n.default.env,(e=>M(e)||!(0,E.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=k,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:I({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function I({overrides:e,forceCLocale:r=!0,forWorker:i=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...D(),...r?(0,p.childProcLocale)():{},...k(i),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,E.isHiddenEnvKey)(e)?"(hidden)":t])),[r,i]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(r)),e.debug("non PS env:",(0,l.fromEntries)(i))}return n}t.childEnv=I},84777:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=i(r(31421)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(42659),c=r(98553),d=r(56409),h=r(31586),f=r(68708),m=r(51926),g=r(50213),p=r(7282),y=r(88158),v=r(79089),w=r(45255),S=r(22911),b=r(4867),P=r(73614),_=r(70025),E=r(57159),M=r(36868),C=r(66184),T=r(45643),x=r(95402),D=r(9727),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const r=e.pid;if(null==r||r<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(r===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(r===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+r+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,x.killPid)(r).catch((e=>{k().warn("endProcess(): kill("+r+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,p.isSingleSpecTests)())return!0;if(await(0,T.waitForPidExit)(r,t))return k().debug("endProcess(): exitted",O(e)),!0;{x.Pids.instance()?.onKill(r);const t=e.kill("SIGKILL");k().warn("endProcess("+r+") had to resort to SIGKILL",{killResult:t}),t||await(0,x.killPid)(r,!0).catch((e=>{k().warn("endProcess(): kill("+r+",true) failed: "+e)}))}return(0,T.waitForPidExit)(r,5e3)}function L(e,r,i,n=0){const o=new Date,a=[];return(0,v.niceable)(r,i)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,x.addPid)({pid:e.pid,cmd:r,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function F(e,t,r,i){const s=(0,D.spawnOptions)(i);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:r,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:r}),L(n.default.execFile(e,t,s),e,t,r)}async function A(e,t,r){const i=r.quiet??!1,n=r.ignoreStderr??!1,s=r.ignoreExitCode??!1,o=F(e,t,r.timeoutMs,(0,f.omit)(r,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===r.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],g=[],p=[],y=new S.Deferred(f);o.on("error",(e=>p.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>p.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>p.push(e))),o.stderr?.on("data",(e=>g.push(e))),o.stderr?.on("end",(()=>P.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:r.timeoutMs,halt:r.halt}),k().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt});const C=g.join("");(0,l.notBlank)(C)&&p.push(new Error(C)),!i&&(0,a.isNotEmpty)(p)&&k().warn(f+" resulted in errors:",p);const T=r.isIgnorableError??_.isIgnorableError,x=p.filter((e=>!0!==T(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:C}}catch(e){throw k().error("stdoutResult_() failed",e),await(0,x.killPid)(o.pid,!0),e}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,r,i){const s=(0,D.spawnOptions)(i);return k().debug("spawn()",{command:e,args:t,maxAgeMs:r}),L(n.default.spawn(e,t,s),e,t,r)},t.execFile=F,t.stdoutResult_=A,t.stdout_=async function(e,t,r){const i=await A(e,t,r);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(i.result),meta:{cmd:e,args:t,opts:r,result:i}})}},3790:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const i=r(22573),n=r(41400),s=r(19851),o=r(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,i.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},69554:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const s=r(6858),o=r(1708),a=r(37805),l=r(22573),u=r(55835),c=r(7282),d=r(19913),h=r(43334),f=r(41269),m=r(80061),g=r(94361);t.CLI=class{constructor(e,t,r){this.serviceName=e,this.args=t,this.additionalDescription=r,i.set(this,[]),(0,d.setServiceName)(e),(0,g.verifyUidGid)()}add(...e){return n(this,i,"f").push(...e),this}async parse(e=o.argv,t){let r=(0,m.addHelpFooter)(new s.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{r=r.arguments(e)}));for(const e of n(this,i,"f"))r=e.beforeParse(r);r.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":a.version)+")"),r.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,o.exit)(0)})),r.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=r.opts();for(const e of n(this,i,"f"))await(e.afterParse?.(d));return r}},i=new WeakMap},41269:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const i=r(1708),n=r(31586),s=r(51926),o=r(17344),a=r(37805),l=r(84542);function u(e,t){const r=t?.maxLineLen??(0,n.toInt)(i.env.maxLineLen)??i.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:r,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const i=r(1708),n=r(38639),s=r(17181),o=r(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,n.mapBoolean)(e.color,(e=>{i.env.PS_LOG_COLOR=String(e),o.Settings.logColor.envValue=e,(0,s.setupLogFormatter)()}))}}},94361:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const i=r(19851),n=r(40958),s=r(55835),o=r(31586),a=r(94174),l=r(44198),u=r(45969);function c(e,t,r){const i=(0,o.toGt0)((0,l.env)()[t]);return null==i||r.includes(i)?void 0:`WARNING: ${e} is running as ${r} but $${t}=${i}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,i.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},76596:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const i=r(51168),n=r(19851),s=r(22573),o=r(42659),a=r(55835),l=r(31586),u=r(68708),c=r(34666),d=r(50213),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,r){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=r}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const r=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),i=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(r,i)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),r=Date.now();return t<=r?0:t-r},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const i=r(22573),n=r(31586),s=r(54557),o=r(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,i.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,i.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const i=r(51168),n=r(40958),s=r(22573),o=r(42659),a=r(31586),l=r(51926),u=r(68852),c=r(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=i.Duration.fromISO(e);if(t.isValid)return t.toMillis();const r=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(r,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const r=(0,a.toFloat)(e);if(null!=r){if((0,s.blank)(t))return r;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*o.yearMs;case"weeks":case"week":case"w":return r*o.weekMs;case"days":case"day":case"d":return r*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return r*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return r*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return r*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return r;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,r=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const i=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const r=Math.floor(t/e.ms);t-=r*e.ms,r>0&&i.push(r+e.s)}return i.join(r)}},84248:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const i=r(50989);t.AutoVacuumModes=(0,i.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const i=r(50989);t.CheckpointTypes=(0,i.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const i=r(50989);t.RepairModes=(0,i.strEnum)("dump","recover")},34365:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const i=r(50989);t.SynchronousModes=(0,i.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(r(76760)),a=r(40958),l=r(22573),u=r(55835),c=r(72993),d=r(19851),h=r(97352),f=r(94174),m=r(44198),g=r(96706),p=r(8769),y=r(57159),v=r(70698),w=r(64680),S=r(29882),b=r(45969),P=r(43334),_=r(28874),E=r(41692),M=r(32774),C=r(80612),T=r(32551),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,g.getEnv)("TEMP"),(0,g.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const r of t)(0,l.blank)(r)||e.push({dir:(0,o.join)(r,".photostructure-cache"+x()),preexistingDir:r});return e}}function k(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:M.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(P.isWin?[(0,g.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,r=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return r.push(...D()),r}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,C.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,C.firstDir)({dirs:k(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,E.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(I)}));function I(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,p.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=I},46292:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const i=r(19851),n=r(45969),s=r(41692),o=r(32774),a=r(10924),l=r(84373),u=r(80612);t.configDir=(0,i.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const i=r(66430),n=r(45969),s=r(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,i.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=i(r(76760)),s=r(40958),o=r(72993),a=r(44198),l=r(96706),u=r(43334),c=r(80612),d=r(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const i=r(22573),n=r(96706),s=r(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,i.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const i=r(44652),n=r(40958),s=r(22573),o=r(66430);function a({dirs:e,desc:t}){for(const{dir:r,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(r)){if((0,o.isReadWriteableDirectorySync)(r))return r;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,i.mkdirpSync)(r),r}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const i=r(48161),n=r(76760),s=r(1708),o=r(19851),a=r(40958),l=r(68284),u=r(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,i.homedir)()}))},46296:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(55835),u=r(54993),c=r(72993),d=r(96706),h=r(45969),f=r(43334),m=r(32707),g=r(6707),p=r(49776),y=r(32774),v=r(80612),w=r(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,p.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,g.readTomlFileSync)((0,m.systemSettingsFile)()),r=(0,u.toS)(t?.logDir);return(0,a.notBlank)(r)?r:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const i=r(76760),n=r(19851),s=r(22573),o=r(44198),a=r(43334),l=r(24399),u=r(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,i.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const i=r(38639),n=r(7282),s=r(29325),o=r(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,i.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const i=r(38639),n=r(44198);t.doNotTrack=function(){return(0,i.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=i(r(73024)),s=r(76760),o=i(r(1708)),a=r(19851),l=r(40958),u=r(41400),c=r(68708),d=r(76850),h=r(7282),f=r(23560),m=r(32551),g=r(34102),p=r(53265),y=r(45969),v=r(59958),w=r(6012),S=r(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),r={...o.default.env};for(const i of e)try{const e=(0,d.debom)(n.default.readFileSync((0,p.resolve)(i))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,i]of(0,c.entries)(s))t.test(e)||(r[e]=i)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+i,e)}return r})),(0,u.later)((()=>{(0,g.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const i=r(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,i.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const i=r(50989);t.EnvKeys=(0,i.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const i=r(22573),n=r(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const r={};if((0,i.blank)(e))return r;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,i.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");r[t?e.toLowerCase():e]=o}}return r}},96706:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=i(r(1708)),s=r(19851),o=r(22573),a=r(38639),l=r(41400),u=r(40583),c=r(79840),d=r(83556),h=r(34102),f=r(44198),m=r(83373);function g(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=g,(0,l.later)((()=>{f.env.watchLater(g),(0,h.ee)().on("clearCache",g)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},98314:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const i=r(58587),n=r(19851),s=r(40958),o=r(22573),a=r(26905),l=r(96249),u=r(51926),c=r(23541),d=r(54993),h=r(89788),f=r(50213),m=r(81168),g=r(84542),p=r(41954),y=r(38835),v=r(70025),w=r(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,p.getErrorDescriptions)(e));const r=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,g.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(r)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const r=(0,s.uniqSubstrings)(b(e)),i=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(r.join(a.ErrorDelimiter)),i-o.length,n)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new i.Rate,t.fatalErrorRate=new i.Rate,t.internalErrorRate=new i.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const r=(0,d.toS)(t?.[e]);if((0,o.notBlank)(r))return r}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,r=256,i=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:r})+" at "+(0,a.shortStack)(e?.stack,i).join("; ")}},41954:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const i=r(40958),n=r(26905),s=r(55835),o=r(54993),a=r(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const r of e)(0,s.map)((0,n.errorErrno)(r),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(r),(e=>t.push(l[e]?.description)));return(0,i.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const i=r(40958),n=r(76790),s=r(50989),o=r(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,i.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const i=r(40958),n=r(38639),s=r(26905),o=r(54993),a=r(68852),l=r(73568),u=r(78656),c=r(98314),d=r(38835);function h(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const r=(0,o.toS)(e)+(0,i.compact)(t).join("");return h(r)+f(r).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const g=/Can't write [a-z\d]+ files/i,p=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const r=(0,c.errorToS)(e);return!g.test(r)&&(!!p.test(r)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const r=(0,c.errorToS)(e);return!(!r.includes("EBUSY")&&!r.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const r=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>r.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const i=r(22573),n=r(31586),s=r(68708),o=r(7282),a=r(23560),l=r(45608),u=r(34102),c=r(28874),d=r(98314),h=r(38835),f=r(70025),m=r(57159),g=r(5012);function p(e,t){try{if((0,i.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,g.stack)()),!1;const r=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===r.fatal,c=!0===r.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",r));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:r}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:r.toString(),status:r.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=p,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,r){return p(e+h.InternalErrorFlag,{cause:t,...r})}},57159:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const i=r(40958),n=r(22573),s=r(38639),o=r(26905),a=r(98553),l=r(68708),u=r(59455),c=r(41583),d=r(48884),h=r(81168),f=r(98314),m=r(38835),g=r(70025);t.toWrappedError=function(e,t){const r=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof p&&(null==t||(0,n.blank)(r.message)||e.message.includes(r.message)))return e;const i=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,r?.message);return new p(i??"(missing error message)",r)};class p extends Error{constructor(e,t={}){super(e),this.causes=(0,i.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const r=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??r.some(g.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(r.map(g.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(r.map(g.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(r.map(g.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,g.stripErrorFlags)(function(e,t){let r=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const i=t?.path;return(0,n.blank)(i)||(r=(0,h.dedupeNeedle)(r,i,"file")),(0,f.joinErrorMessages)([r[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...r.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new p(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=p},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=r(49769),a=r(55835),l=r(54993),u=r(22911),c=r(89788),d=r(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,i.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,i,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const r=this.target.emit(e,...t),o=s(this,i,"f").get(e);return null!=o&&(o.resolve(t),s(this,i,"f").delete(e)),r}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},i=new WeakMap,n=new WeakMap},34102:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const i=r(78474),n=r(19851),s=r(15197);t.ee=(0,n.lazy)((()=>{const e=new i.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=i(r(73024)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(65843),u=r(16287),c=r(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):p({stat:e,r:!0,w:!0,x:!0})}function g(e,t){return c.isWin?f(t,n.default.constants.R_OK):p({stat:e,r:!0,x:!0})}function p({stat:e,r:t=!1,w:r=!1,x:i=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(r&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!i||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=g,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const r of(0,l.selfAndAncestorG)(e)){const i=await(0,u.statMaybe)(r);if(null!=i){if(!i.isDirectory())return!1;if(t){if(!g(i,e))return!1}else if(t=!0,!m(i,e))return!1}}return!0},t.access=p},21144:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=i(r(76760)),s=r(19851),o=r(81168),a=r(57159),l=r(43334),u=r(88561),c=r(29882),d=r(65238),h=r(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const r=(0,c.parseNativePath)((0,h.resolve)(...e)),i=await m(r.dir);for(const e of await(0,d.readdir_)(i))if((0,o.equalsIgnoreCase)(e.basename,r.base))return n.default.join(i,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const i=r(73024),n=r(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,i.readdirSync)(e)}catch(e){return[]}}function l(e,t){const r=a(e);return t.every((e=>r.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,r){var i,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&l(t,e,r);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(r(44652)),g=c(r(73024)),p=r(51455),y=f(r(76760)),v=f(r(1708)),w=r(46466),S=f(r(57975)),b=f(r(38522)),P=r(19851),_=r(40958),E=r(5233),M=r(22573),C=r(42659),T=r(50357),x=r(96249),D=r(98553),k=r(55835),O=r(31586),I=r(68708),L=r(97790),F=r(39926),A=r(51926),N=r(59455),R=r(54993),j=r(48884),B=r(22911),V=r(99331),z=r(56519),W=r(56038),q=r(31562),U=r(76850),G=r(70025),H=r(34102),J=r(80875),$=r(50213),K=r(70417),Y=r(43334),Z=r(81168),X=r(96859),Q=r(65162),ee=r(94174),te=r(64660),re=r(21144),ie=r(84542),ne=r(89968),se=r(20197),oe=r(88561),ae=r(50597),le=r(33456),ue=r(29882),ce=r(78133),de=r(43899),he=r(65238),fe=r(53265),me=r(17217),ge=r(16287),pe=r(68284),ye=r(66003),ve=r(27794),we=r(73428),Se=r(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(i.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,$.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,i=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),r=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(r)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const r=(0,me.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,M.blank)(r))throw new Error("BaseFile.for(): empty nativePathOrFile");const i=be().get(r);if(null!=i)return i;const n=(0,fe.resolve)(r),s=new Pe(n,t);return be().set(r,s),be().set(n,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const r=[];for(const i of t)!0===await e(i)&&r.push(i);return r}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,i,"m",s).call(this)??await d(e=this.clearThisAndParent(),i,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const r of t)await r.visitDescendants(e),await e(r)}))}async descendants(e){const t=[];t.push(...(0,N.toA)(await this.childFiles(e)));const r=await this.childDirectories();if(null==r)return t;for(const i of r)t.push(...(0,N.toA)(await i.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const r=await d(this,n,"f").call(this)??[];for(const t of r)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const i of r)if(i.isDirectory()){const r=await this._directoryEntryChild(i).someDescendant(e,t-1);if(null!=r)return r}}descendantsSync(e){const t=this.directoryEntrySync(),r=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&r.push(this.forDirectoryEntry(t))})),r}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,re.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,r)=>this.join((0,R.toS)(e),(0,F.pad2)(t+1),(0,F.pad2)(r))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,r="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(r,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,r="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(r,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,r){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(r??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,ge.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,ge.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,C.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,ge.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>=(0,C.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(r=>Math.abs(r-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>(0,C.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,L.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,q.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*C.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,J.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,J.parseJSON)((0,g.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,g.readFileSync)(this.nativePath)}readFile_(){return(0,p.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return g.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,E.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,V.ending)()?1:3,timeoutMs:0,retryDelay:C.secondMs,errorIsRetriable:G.isRetriableError})}async gunzip(){return d(this,i,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,i,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,i,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return g.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return g.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const r=await this.children((async r=>!r.isNameHidden()&&t===r.size()&&r.nativePath!==e.nativePath));if((0,_.isEmpty)(r))return;const i=await e.sha();if(null!=i)for(const e of r.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===i)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),r=g.default.createReadStream(this.nativePath,{flags:"r"});return r.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),r.close()):t.maybeReject(e)})),r.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(r,(0,A.newlineRe)(),(i=>{const n=e.exec(i);null!=n&&(t.maybeResolve(n),r.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,r)=>{for(const i of e)for(const e of r)if((0,O.closeTo)(i,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),r=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&r.setTimeout(e.timeoutMs),_e)try{const i=(0,g.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(i,n)=>{try{const s=await e.f(i,(0,k.denull)(n));t(s)&&r.resolve(s)}catch(e){r.reject(e)}}));r.finally((()=>{i.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const i=setInterval((async()=>{try{const i=await e.f();t(i)&&r.resolve(i)}catch(e){r.reject(e)}}),e.intervalMs);e.persistent||i.unref(),r.finally((()=>{clearInterval(i)}))}return r}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const r=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([g.default.createReadStream(this.nativePath,{autoClose:!0}),t,g.default.createWriteStream(r.nativePath,{autoClose:!0})]),await this.unlink(),r}))},Pe.attrTTL=3*C.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},84542:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const i=r(40958),n=r(96249),s=r(51926),o=r(54993),a=r(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,i.compactBlanks)(l(...e))}},70698:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const i=r(76760),n=r(19851),s=r(50213),o=r(37805),a=r(29882),l=r(93854),u=r(17217),c=r(16287),d=r(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const r=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return r===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,i.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const r=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(r),await(0,d.writeTextfile_)((0,a.joinNativePath)([r,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(45969),u=r(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(r(44652)),l=o(r(73024)),u=r(76760),c=r(57975),d=r(19851),h=r(59455),f=r(50213),m=r(81168),g=r(34102),p=r(29882),y=r(65238),v=r(14427),w=r(17217),S=r(16287),b=r(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class E{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,p.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new E(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:r,base:i}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,p.parseNativePath)(e)},n=await a.stat(t);return new E(r,new P(i,n))}clear(){return(0,g.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return E.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,p.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,p.parseNativePath)(this.dir);return e.dir===this.dir?this:new E(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>E.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new E(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const r of t)r.isDirectory()&&await r.visitDescendants(e);for(const r of t)r.isFile()&&await e(r);for(const r of t)r.isDirectory()&&await e(r)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const r of t)r.isFile()&&e(r);for(const r of t)r.isDirectory()&&(r.visitDescendantsSync(e),e(r))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async r=>{!0===await e(r)&&t.push(r)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,g.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,g.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=E},20197:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=i(r(76760)),s=r(39926),o=r(29882),a=r(16287),l=r(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if(await(0,o.mkdirp_)(i.dir),!r.requireNumber&&await(0,a.isEmptyFile)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if(await(0,a.isEmptyFile)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)},t.ensureNewNativePathSync_=function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if((0,o.mkdirpSync_)(i.dir),!r.requireNumber&&(0,l.isEmptyFileSync)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if((0,l.isEmptyFileSync)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)}},88561:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=r(40958),a=r(22573),l=r(41400),u=r(68708),c=r(25764),d=r(38836),h=r(34102),f=r(80049),m=r(50213),g=r(88158),p=r(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:p.ShortCommandTimeoutMs,...e}),i.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,i,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,g.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,i=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const i=r(73024),n=r(22573),s=r(45599),o=r(96249),a=r(68708),l=r(54993),u=r(49047),c=r(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...r]of d)for(const i of r)e[i]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof i.Dirent?e.name:(0,l.toS)(e),r=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(r)?void 0:h()[r]??r}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const r of t)if(r===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const i=r(68708),n=r(17217),s=r(16287),o=r(68284);async function a(e){return(0,i.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,i.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},4001:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const i=r(22573),n=r(55835),s=r(31586),o=r(51926),a=r(54993),l=r(97352),u=r(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,i.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,r){if(t.ymdIsoRE.test(e))return e;let i=e;for(const e of r.aggressive?d:c){const t=i.match(e);if((0,s.gt0)(t?.index)){const e=i.slice(0,t.index).trim();e.length>0&&(i=e)}}return e===i?e:f(i,r)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),r=t.pop();if((0,i.blank)(r))return e;const n=(0,u.parsePosixPath)(r),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),r=h(t),i=(0,o.stripPrefix)(t.toLowerCase().normalize(),r);return(0,n.map)((0,l.extractInt)(i),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,g=/(?<=.{6})_cover$/i,p=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(g,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(p.exec(t),(e=>t=e[1].trim())),t}},14977:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=i(r(44652)),s=i(r(73024)),o=r(46466),a=i(r(38522)),l=r(49769),u=r(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=i(r(77598)),s=i(r(73024)),o=r(46466),a=r(19851),l=r(98553),u=r(68708),c=r(23467),d=r(80049),h=r(73913),f=r(50213),m=r(12089),g=r(37628),p=r(43624),y=r(17217),v=r(16287),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:r=!0}={}){const i=(0,y.toNativePath_)(e);if(r){const t=S().get(i);if(null!=t){if((0,c.eql)(t.stats,await(0,p.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:i,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:i,prior:t}),S().delete(i)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),r=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(r)),stats:(0,u.pick)(await(0,v.stat_)(r),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],r="sha512"){const i=n.default.createHash(r);return await(0,o.pipeline)([e,...t,i]),i.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,g.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},25675:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const i=r(22573),n=r(54993),s=r(7282),o=r(43334),a=r(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,i.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const i=r(57075),n=r(51926),s=r(54993);class o extends i.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,r){const i=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=i.pop();this._prior=o??"";let a=!1;for(const e of i)a||(a=!this.push(e));a?setTimeout(r,1):r()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=i(r(76760)),s=r(17217),o=r(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},29882:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(5233),u=r(22573),c=r(98553),d=r(39426),h=r(51926),f=r(48884),m=r(50213),g=r(81168),p=r(70025),y=r(43334),v=r(78133),w=r(53265),S=r(17217),b=r(16287),P=r(66430),_=r(5545);function E(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=E,t.containsHiddenPathname=function(e){return k(e).some(E)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!E(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return C((0,v.posix2native)(e))},t.extname=function(e){return C(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,g.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function C(e){const t=M.exec(e)?.groups,r=t?.ext2??"",i=s.default.parse(t?.path??e);return{...i,ext:(i.ext??"")+r,base:(i.base??"")+r}}function T(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),r=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(r))return!1;const i=e.acceptSelf??!1;return t===r?i:r.startsWith((0,g.ensureSuffix)(t,s.default.sep))}catch(r){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:r}),!1}}function D(e,t,r){if(null==t||null==r)return!1;const i=e(t),n=e(r);return null!=i&&null!=n&&(y.isLinux?i===n:(0,g.equalsIgnoreCase)(i,n))}function k(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&k(e).length===(y.isWin?1:0)}function I({p:e,maxLength:t}){const r=(0,S.toNativePath_)(e);if(r.length<=t)return r;const i=k(e),n=[],s=[i.pop()];for(;i.length>0;)if(n.length=t){i.unshift(n.pop());break}}else if(s.unshift(i.pop()),F([...n,...s]).length>=t){i.push(s.shift());break}return i.length>0&&n.push("…"),F([...n,...s])}function L(e){return e.startsWith("\\\\")}function F(e){return(0,h.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=C,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(S.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const r=(0,S.toNativePath_)(e),i=(0,S.toNativePath_)(t);if((0,u.blank)(r)||(0,u.blank)(i))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return r===i?"":(0,g.stripPrefix)((0,v.native2posix)(i).normalize(),(0,g.ensureSuffix)((0,v.native2posix)(r),"/").normalize()).normalize()},t.ellipsizePath=I,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:r=4,arrLength:i=e.length}){const n=[];for(const i of e.slice(0,r))n.push(I({p:i,maxLength:t}));return n.join(", ")+(i>r?`, and ${i-r} more…`:"")},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const r=C(e);return`${r.base}${t}${r.ext}`},t.isUNC=L,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(L(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(31586),u=r(51926),c=r(12168),d=r(59455),h=r(54993),f=r(50213),m=r(44198),g=r(96706),p=r(45969),y=r(43334),v=r(64660),w=r(21144),S=r(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const r=await(0,S.statMaybe)(e,"trace");return null!=r&&r.isFile()&&(0,l.gte)(r.size,t)&&(0,v.isStatRX)(r,e)}function E(){if(y.isWin){const e=(0,a.toNotBlank)((0,g.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,g.getEnv)("SystemDrive"))??"C:",r=(0,a.toNotBlank)((0,g.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(r,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,p.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...E()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:r}){const i=(0,o.uniq)((0,o.compactBlanks)([...M(),...(0,d.toA)(r)]));for(const r of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(r,".exe"):r;for(const t of i){const r=n.default.join(t,e);if(await _(r))return y.isLinux?r:(0,w.actualPath)(r)}}b().warn("Failed to find tool",{tool:e,dirs:i})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},78133:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=i(r(76760)),s=r(22573),o=r(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const r=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",i=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(i[0],t)&&i.unshift(),r+i.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(48884),u=r(50213),c=r(45969),d=r(29325),h=r(43334),f=r(65843),m=r(25675),g=r(53265);function p(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(n.default.join((0,g.execDir)(),"resources"),n.default.join((0,g.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,g.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const r of t){if((0,f.hasChildrenSync)(r,e))return r;for(const t of(0,f.ancestors)(r).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const i=n.default.join(r,"node_modules","photostructure");if((0,f.hasChildrenSync)(i,e))return i}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:p("bin"),Data:p("data"),ICC:p("data","icc"),Migrations:p("data","migrations"),Public:p("public"),Tools:p("tools"),Views:p("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const i=r(44652),n=r(19851),s=r(31586),o=r(50213),a=r(57902),l=r(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,i.readFile)(e)}catch(r){return void u().log(t,".readFileMaybe("+e+")",r)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const i=r(44652),n=r(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:r}){let s=-1;try{const n=r??(await(0,i.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,i.open)(e,"r"),await(0,i.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,i.close)}}},69428:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(r(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},32323:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const i=r(57075);class n extends i.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=i(r(51455)),s=r(76760),o=r(19851),a=r(76790),l=r(22573),u=r(42659),c=r(41400),d=r(31586),h=r(13538),f=r(83104),m=r(54127),g=r(50213),p=r(95937),y=r(34102),v=r(28874),w=r(63870),S=r(88561),b=r(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,g.mkLogger)("fs.Readdir")));async function _(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const E=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||E.prior()?.delete(e)}async function C(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await E().getOrSetAsync(e,(()=>async function(e){const r=Date.now()+2*(0,b.statTimeoutMs)(),i=T(e),n=await(0,h.thenOrTimeout)(i,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===f.Timeout&&(0,p.onTimeout)({soft:!1}),n!==f.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),E.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!E().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=E().get(e)},t.childDirectories_=async function(e){return(await C(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?C(e):T(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=C,t.readdirCached=function(e){return E().get(e)},t.readdirUncached_=T},53265:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=r(73024),s=i(r(76760)),o=r(40958),a=r(22573),l=r(45599),u=r(50213),c=r(43334),d=r(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function g(...e){for(const t of m()){const r=s.default.resolve(t,...e);if((0,n.existsSync)(r))return r}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?g(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=g},50274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const i=r(50989);t.SidecarExts=(0,i.strEnum)("xmp","mie","exv")},14427:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const i=r(22573),n=r(38639);t.isSimpleDirent=function(e){return null!=e&&(0,i.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=i(r(73024)),s=i(r(76760)),o=r(22573),a=r(98553),l=r(81168),u=r(43334),c=r(29882),d=r(53265),h=r(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function g(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=g,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(g(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const p=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(p)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),r=t.indexOf(s.default.sep);return r>0?t.slice(1,r):void 0}},t.findFileIndex=function(e,t){for(let r=0;r(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,p.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((r=>{y().log(t,"stat() failed",{error:r,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const r=S(e),i=S(t);if(r!==i)return"inconsistent file type: "+r+" ≠ "+i;for(const r of["size","mtime"]){const i=e[r],n=t[r],s=(0,u.diff)(b(i),b(n));if(null==s||s>1)return"unmatched "+r+": "+i+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const r=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=r&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(r)},t.isNonEmptyFile=async function(e,t=0){const r=await w(e);return null!=r&&r.isFile()&&r.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.access)({stat:r,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.isStatRWX)(r,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=i(r(73024)),s=r(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const r=o(e);return t.emptyIsNew?null==r:a(r)},t.isNonEmptyFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const i=r(28874);t.statTimeoutMs=function(){return i.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const i=r(22573),n=r(56409);t.onDataChunked=function(e,t,r){const i=new s(t,r,!0);return i.read(e),i.done};class s{constructor(e,t,r=!0){this.sep=e,this.onData=t,this.filterBlanks=r,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,i.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,i.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=i(r(57075)),s=r(41400),o=r(55835),a=r(68708),l=r(42279),u=r(99331),c=r(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((r,i)=>{!1===e.write(t,(e=>{e&&i(e)}))?e.once("drain",r):r()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:r,ea:i}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(i,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(r,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends n.default.Transform{constructor(e){super({transform:(e,t,r)=>{this.onProgress(this.bytes+=e.length),r(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=i(r(73024)),s=r(76760),o=r(22573),a=r(76596),l=r(64660),u=r(78133),c=r(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},27794:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=i(r(44652)),s=r(19851),o=r(22573),a=r(42659),l=r(31586),u=r(68708),c=r(13538),d=r(29882),h=r(17217),f=r(16287),m=r(41080);function g(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const r=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const i=(0,h.toNativePath_)(t.file);r&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(g(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),p=Math.round(g(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(i,new Date(p),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!r||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(i),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},5545:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=i(r(76760)),s=r(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const r=t.driveRe.exec(e)?.groups;return null==r?e:r.drive.toUpperCase()+(0,s.toS)(r.path??n.default.sep)}},58722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const i=r(57075),n=r(22911);class s extends i.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,r){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),r()}}t.WritableToBuffer=s},73428:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(51926),a=r(54993),l=r(34102),u=r(84542),c=r(29882);async function d(e,t){const r=s.default.dirname(e);await(0,c.mkdirp_)(r),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",r)}function h(e,t){const r=s.default.dirname(e);(0,c.mkdirpSync_)(r),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",r)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const r=(0,u.crlf)(...(0,o.wrap)(t));await d(e,r)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=i(r(73024)),s=r(76760),o=r(46466),a=r(38522),l=r(19851),u=r(40958),c=r(98553),d=r(80875),h=r(50213),f=r(57159),m=r(29882),g=r(57902),p=r(32323),y=r(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,r){const i=[],s=[n.default.createReadStream(e,{autoClose:!0,...r}).on("error",(e=>i.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>i.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>i.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(i))throw new f.WrappedError("zPipe("+e+") failed",{causes:i,path:e})}async function b(e,t){const r=new y.WritableToBuffer;return await S(e,r,t),await r.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const r=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new p.ReadableBuffer(r),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=g.LogLevels.warn){try{return await P(e)}catch(r){return void v().log(t,"readJsonGz("+e+"): failed",r)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,r=g.LogLevels.warn){try{await _(e,t)}catch(t){v().log(r,"outputJsonGz("+e+"): failed",t)}}},33866:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const i=r(50989);t.HealthCheckIds=(0,i.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},52086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const i=r(50989);t.CropStrategies=(0,i.strEnum)("center","entropy","attention")},48584:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const i=r(50989);t.SharpFailOns=(0,i.strEnum)("none","truncated","error","warning")},49794:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const i=r(57975),n=r(19851),s=r(40958),o=r(22573),a=r(54993),l=r(37975),u=r(7282),c=r(23560),d=r(28874),h=r(66184),f=r(93475),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function g(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=g,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=g(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,i.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:g(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:r,meta:i})}}},32105:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const i=r(19851),n=r(23560),s=r(66184),o=r(72210);class a{log(e,t,r,i){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:r,meta:i})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,i.lazy)((()=>new a))},14593:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const i=r(57975),n=r(22573),s=r(26905),o=r(55835),a=r(68708),l=r(13538),u=r(50213),c=r(97352),d=r(45255),h=r(76740),f=r(57159),m=r(57902),g=/logger|lazy/i;class p{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!g.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[i.inspect.custom](){return this.toLogJSON()}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const r=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(r),this.log(!0===r.ignorable?"warn":"error",".throw() "+r.message,{stack:r.stack,...t}),r}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let r;try{r=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const i=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:i,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(r,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const r of this.loggers())if(r.enabled(e,t??this.context))return!0;return!1}log(e,t,r){for(const i of this.loggers())i.log(e,this.context,t,r)}elapsed(e,t,r){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...r})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=p},89179:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const i=r(50213),n=r(43705);t.currentFileLogger=function(){return(0,i.rootLoggers)().find((e=>e instanceof n.LogWriter))}},28981:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const i=r(19851),n=r(51879);t.DefaultLogFormatter=(0,i.lazy)((()=>new n.PlaintextLogFormatter))},31256:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(41400),a=r(98553),l=r(55835),u=r(31586),c=r(68708),d=r(72993),h=r(23560),f=r(81168),m=r(98314),g=r(57902),p=r(93475),y=(0,i.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,r]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(r)}}}(0,o.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,g.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,p.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:r,meta:i})}}},51576:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=r(77030),o=r(19851),a=r(22573),l=r(42659),u=r(41400),c=r(98553),d=r(56409),h=r(31586),f=r(25764),m=r(38836),g=r(50213),p=r(409),y=r(28874),v=r(31256),w=r(28538),S=(0,o.lazy)((()=>(0,g.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),r=(0,h.toInt)(t);return(0,a.blank)(e)||!(0,h.gt0)(r)?void 0:{host:e,port:r}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),i.set(this,(0,p.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,i,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,r,s){if(this.enabled(e,t))try{const o=this.socket;null==o?n(this,i,"f").call(this):o.write(this.logFormatter.format(e,t,r,s)+b)}catch(i){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:r,meta:s,error:i})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}i=new WeakMap},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const i=r(76760),n=r(42659),s=r(28874);t.datedLogDir=function(e,t){return(0,i.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},4904:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const i=r(76790),n=r(31586),s=r(51926),o=r(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,i.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const i=r(19851),n=r(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,i.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,i.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,r){return(0,t.logFilter)().enabled(e)?r():void 0},t.isLogged=function(e,r){return(0,t.logFilter)().enabled(e,r)}},28538:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=r(19851),u=r(40958),c=r(22573),d=r(54993),h=r(28874),f=r(66184),m=r(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){i.add(this),this.setting=e,this.silent=!1,n.set(this,[]),s.set(this,(0,l.lazy)((()=>{a(this,n,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const r of t){const t=f.LogLevelRe.exec(r.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+r+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),r=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=r:a(this,n,"f").push({prefix:e,levelIndex:r})}}}))),e.watch((()=>a(this,s,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const r=(0,m.levelIndex)(e);if(null!=t){const e=a(this,i,"m",o).call(this,t);if(null!=e)return r<=e.levelIndex}return r<=this.defaultLevelIndex}highlight(e){const t=a(this,i,"m",o).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap,s=new WeakMap,i=new WeakSet,o=function(e){if(null==e||0===a(this,n,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return a(this,n,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const i=r(31586),n=r(50989),s=r(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,r){return(0,i.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(r))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const i=r(40958),n=r(68708),s=r(20214),o=r(51926),a=r(23541),l=r(48884),u=r(88158),c=r(98314),d=r(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(r,h=4){if(null==r)return null;if(h<0)return"…";if((0,o.isString)(r)||Buffer.isBuffer(r))return(0,o.ellipsize)(r.toString(),256,32);if((0,a.isError)(r))return(0,c.errorToVerbose)(r);if(Array.isArray(r)){const t=d.Settings.logContextLimit.valueOrDefault,i=Math.floor(t/2);return r.length<=t?r:[...r.slice(0,i).map((t=>e(t,h-1))),`… (${r.length} total entries)`,...r.slice(-i).map((t=>e(t,h-1)))]}if("object"==typeof r||"function"==typeof r){for(const t of["toLogJSON","toJSON"])if("function"==typeof r[t])return e(r[t](),h-1);if((0,s.isPromiseLike)(r))return t.PromisePlaceholder;if("…"in r)return r;const a=(0,u.mapNullEntries)(r,((t,r)=>e(r,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(r),(0,n.keys)(a));return(0,i.isNotEmpty)(c)&&(a["…"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return r}},24068:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const i=r(73024),n=r(76760),s=r(1708),o=r(87997),a=r(19851),l=r(22573),u=r(42659),c=r(49769),d=r(55835),h=r(34666),f=r(20214),m=r(7282),g=r(23560),p=r(54826),y=r(82328),v=r(22277),w=r(25764),S=r(38836),b=r(99331),P=r(42638),_=r(76596),E=r(98314),M=r(89968),C=r(29882),T=r(28874),x=r(28981),D=r(20839),k=r(21727),O=r(66184),I=r(57902),L=r(72210),F=r(98192);function A(e){const t=(0,x.DefaultLogFormatter)();for(const r of e)(0,p.consoleLog)(t.formatLogEntry(r))}t.DefaultLogEntryWriter=A;class N extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,T.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,p.consoleLog)("tailing "+e+"..."),await(0,C.mkdirp_)(e),this.root=await M.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,g.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,L.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),D.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,L.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,p.consoleLog)("LogTail(): watching "+e)));try{return(0,i.watch)(e,((t,r)=>{(0,l.notBlank)(r)&&this.watchListener(t,(0,n.join)(e,r))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,p.consoleError)("LogTail(): failed to read "+e+": "+(0,E.errorToS)(t))))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,_.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,k.datedLogDir)(this.root.nativePath);try{await(0,C.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,p.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,E.errorToS)(e))))}(0,b.ending)()||this.ended||e&&(0,p.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,L.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,L.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await M.DirectoryEntry.for(t);if(null==e)return;const r=e.size();if(null==r||r<=0)return;const i=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(i,r))return;await(0,f.thenMap)((0,F.readLogEntries)(e,{start:i,end:r}),(e=>(0,L.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,r)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,p.consoleError)("Failed to read "+t+": "+(0,E.errorToS)(e))))}}))}}t.LogTail=N,N.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new N))},72210:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const i=r(92322),n=r(82328),s=r(28981),o=r(20839),a=r(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new i.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const r of e)l?t.logEntries.add(r):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(r))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(r(73024)),f=r(76760),m=r(19851),g=r(42659),p=r(41400),y=r(98553),v=r(31586),w=r(409),S=r(23560),b=r(81168),P=r(78406),_=r(25764),E=r(20197),M=r(14977),C=r(36868),T=r(28874),x=r(32105),D=r(20839),k=r(21727),O=r(66184),I=r(93475),L=r(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,r,i){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:r,meta:i})}enabled(){return!0}end(){}async flush(){}};class F extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*D.DefaultLogFlushMs),rank:_.EndableRanks.logger,unref:!0,onEnd:()=>c(this,n,"f").call(this)}),i.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,g.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*g.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,i,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:x.ConsoleLogger.instance(),flushEveryMs:D.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,i,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,r,i){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,r,i);else{const n={ts:Date.now(),l:e,ctx:t,msg:r};null!=i&&(n.meta=(0,I.prepMeta)(i)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,L.recentLogEntries)()),(0,L.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=F,n=new WeakMap,i=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,i,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const r=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,r);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,i,"m",o).call(this,e,t),c(this,i,"m",u).call(this))},l=async function(){await c(this,i,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,E.ensureNewNativePath_)({nativePath:(0,f.join)((0,k.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),r=h.default.createWriteStream(t).on("error",c(this,i,"m",a).call(this,"file write stream"));this._logfile={stream:r,nativePath:t},this._nextForcedRotateTs=(0,g.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,C.endStream)(e.stream),T.Settings.logCompression.valueOrDefault&&(await(0,p.delay)(this.logOpts.flushEveryMs),await(0,M.gzip_)(e.nativePath))}catch(e){c(this,i,"m",o).call(this,"_closeCurrent()",e)}}},51879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(68708),a=r(54993),l=r(23560),u=r(81168),c=r(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,i.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:r,meta:i})}}},98192:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const i=r(22573),n=r(84542),s=r(4001),o=r(13047),a=r(4904);function l(e){if(!(0,i.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const r=(0,s.stripCopySuffixFromName)(e.name),i=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,n.splitLines)(a)){const t=l(e);null!=t&&i.push({...t,from:r})}return i},t.chunkToLogEntry=l},22662:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const i=r(19851),n=r(76790),s=r(68708),o=r(89788),a=r(57902);t.SentLogLevels=(0,i.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,i.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},17181:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const i=r(76760),n=r(41400),s=r(55835),o=r(37975),a=r(50213),l=r(27395),u=r(46296),c=r(96706),d=r(73428),h=r(28874),f=r(49794),m=r(32105),g=r(89179),p=r(28981),y=r(51576),v=r(66184),w=r(28538),S=r(24068),b=r(43705),P=r(51879);function _(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),E();const e=(0,u.logDir)();let t=(0,g.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,i.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new b.LogWriter(e));const r=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&r.push(m.ConsoleLogger.instance()),(0,s.map)((0,y.logBroadcaster)(),(e=>r.push(e))),a.rootLoggers.set(r),h.Settings.tailLogs.valueOrDefault&&S.LogTail.instance()}function E(){const e=h.Settings.logColor.valueOrDefault;(0,o.setColorEnabled)(e),p.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=_,t.setupLogFormatter=E,(0,n.later)((()=>{h.Settings.logStdout.watchLater(_),h.Settings.logDir.watchLater(_),h.Settings.tailLogs.watchLater(_),h.Settings.logColor.watchLater(E),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},36389:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=i(r(1708)),s=r(24068),o=r(40958),a=r(5670),l=r(69554),u=r(38790),c=r(46296);!async function(){const e=(0,c.logDir)(),t=await new l.CLI(a.ServiceNames.logtail,"[LOG_DIR]","Normally logtail watches all files in the default logging directory, "+e+". Specify LOG_DIR or set the PS_LOG_DIR environment variable to override this directory.").add(u.ColorArgs).parse();n.default.on("SIGINT",(()=>n.default.exit(0))),n.default.on("SIGTERM",(()=>n.default.exit(0)));const r=(0,o.compactBlanks)(t.args);new s.LogTail(r[0]??e)}()},82647:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=r(57975),a=r(40958),l=r(96249),u=r(55835),c=r(31586),d=r(68708),h=r(59455),f=r(48884),m=r(89788),g=r(22454),p=r(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const r=t.clone();return r.pushAll(e.samples),r}if(t.n<=t.maxSamples){const r=e.clone();return r.pushAll(t.samples),r}{const r=new y(Math.max(e.maxSamples,t.maxSamples));r._n=e.n+t.n,r._min=Math.min(e._min,t._min),r._max=Math.max(e._max,t._max),r._m=e._m*e.n/r.n+t._m*t.n/r.n,r._s=e._s*e.n/r.n+t._s*t.n/r.n;const i=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return r._samples.push(...i),r._weightedTotalAvg=(0,p.weightedAvg)([r._m,...i]),r}}constructor(e=20){i.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(i=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,p.min)([this._min,e.min]),this._max=(0,p.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),r={};return r.k=t(this.n),this.empty||(r.mean=t(this.avg),r.sum=t(this.sum),r.sd=t(this.stdDev),r.max=t(this.max),r.min=t(this.min)),r}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,i,"m",n).call(this,-1)}get p29(){return s(this,i,"m",n).call(this,-.5)}get p38(){return s(this,i,"m",n).call(this,-.25)}get p69(){return s(this,i,"m",n).call(this,.5)}get p84(){return s(this,i,"m",n).call(this,1)}get p98(){return s(this,i,"m",n).call(this,2)}get p99(){return s(this,i,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new g.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,p.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,p.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,p.avg)}get sampleSlope(){return(0,p.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,p.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const i=r(40958),n=r(55835),s=r(31586),o=r(30976),a=r(48884),l=r(70417);function u(e,t){const r=Math.pow(2,t),i=[];for(;e>0;)i.unshift(e%r),e=Math.floor(e/r);return i}t.concatBits=function(e,t){const r=Math.pow(2,t);return e.reduce(((e,t)=>e*r+(0,s.clamp)(0,r,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,r){return(0,n.map2)(e,t,((e,t)=>(0,i.sum)((0,a.zip)(u(e,r),u(t,r)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,r[t]=o):i[t]=o}return s}unzip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max));for(let n=0;n(r[e]+i[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,r){return!0!==r&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let r=0;rs?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const r=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,i.sum)(e,((r,i)=>t(r,i)?Math.pow(2,e.length-i-1):0))}},55222:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const i=r(77598),n=r(22573),s=r(55835),o=r(32639),a=r(88158),l=r(81168),u=BigInt(0);function c(e,t,r=0){if(!isFinite(t)||e<=1)return[];const i=[];if(0===t)i.unshift(0);else for(;t>0;)i.unshift(t%e),t=Math.floor(t/e);for(;i.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const r=e<0;return r&&(e=Math.abs(e),t--),(r?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],r=BigInt(this.base);let i=e;for(;i>u;)t.push(Number(i%r)),i/=r;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let r of e)for(t.forEach(((e,i)=>{r+=e<<8,t[i]=r%this.base,r=Math.floor(r/this.base)}));r>0;)t.push(r%this.base),r=Math.floor(r/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const r=BigInt(this.base);let i=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;i=i*r+BigInt(e)}return t?BigInt(-1)*i:i}randomChars(e){return this.encodeBuffer((0,i.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,r="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(r)}tokenEql(e,t,r){const i=this.normalizeToken(e),n=this.normalizeToken(t);return i.length>=r&&i===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const i=r(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,i.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},70417:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=r(40958),l=r(55835),u=r(31586),c=r(59455),d=r(22454),h=r(77377),f=r(82647);function m(e){let t;for(const r of e)null!=r&&(null==t||rt)&&(t=r);return t}function y(e,t){const r=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&r.incr(t);return r.topKeys(t)}function v(e,t){let r=0,i=0;for(const n of e){if(null!=n){const e=t(n,r);(0,u.isNumber)(e)&&(i+=e)}r++}return i}t.min=m,t.max=p,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,r)=>e-t[r]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const r of e)(0,u.isNumber)(r)&&(t+=r);return t},t.sumf=v;class w{constructor(){i.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,i,"f")/(s(this,i,"f")+1)+e/(s(this,i,"f")+1),"f"),o(this,i,(t=s(this,i,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const r of e)t.push(r);return t.mean}function b(e){const t=S(e);if(null==t)return;let r=0,i=0;for(const n of e)(0,u.isNumber)(n)&&(i++,r+=(n-t)*(n-t));return r/i}function P(e){let t=0;for(const r of e)t+=r*r;return Math.sqrt(t)}function _(e,t){let r=0;for(let i=0;i(1-t)*e+t*(r+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),r=S(t);if(null!=r){const e=(t.length-1)/2,i=v(t,((t,i)=>(t-r)*(i-e))),n=v(t,(e=>(e-r)**2));return 0===n?0:i/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let r;t=(0,u.clamp)(0,1,t);for(const i of e)r=null==r?i:r*t+i*(1-t);return r},t.centroid=function(e){const t=e[0].length,r=[];for(let i=0;ie[i]))));return r},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},45969:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const i=r(73024),n=r(38639),s=r(19851),o=r(59958),a=r(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,i.existsSync)("/.running-in-container"))))},29325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const i=r(76760),n=r(19851),s=r(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,i.join)("core","platform","IsPacked"))))},43334:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(22573),a=r(38639),l=r(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=i(r(73024)),s=r(19851),o=r(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const i=r(58587),n=r(59455),s=r(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(i.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,i.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=r(58587),d=u(r(31421)),h=u(r(1708)),f=r(40958),m=r(22573),g=r(42659),p=r(55835),y=r(31586),v=r(97790),w=r(59455),S=r(54993),b=r(54557),P=r(19851),_=r(50213),E=r(88158),M=r(409),C=r(78406),T=r(25764),x=r(99331),D=r(56519),k=r(46292),O=r(8769),I=r(83278),L=r(32144),F=r(29882),A=r(43334),N=r(24399),R=r(58261),j=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),B=10*g.secondMs;function V(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const r=(0,p.map)(t.start,(e=>e.getTime())),i=e.startTime;return(0,y.gt0)(r)&&(0,y.gt0)(i)&&Math.abs(r-i){const e=Date.now()-2*g.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,L.isJsonExt)(t)&&(0,F.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:g.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,r=e.force??A.isWin,i=await this.pidfiles(),n=await this.pids(i??[]);if((0,f.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,R.pidInfos)(n);if(null!=a){for(const n of i){const i=await n.readJson();if(null==i){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=i.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:i,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!V(i,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:i,pidEntry:u}),await n.unlink("debug"),s.push(i);continue}const c=(0,y.gt0)(i.timeoutMs)?i.startTime+i.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(i.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:i}),o.push(W(l,r,!1)),s.push({...i,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,r=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(r&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const r=a(this,i,"m",s).call(this,e.pid),n=(0,v.opt)((0,E.Try)((()=>(0,F.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await r.writeJson_(l),j().debug("addPid() wrote "+r,l),r}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,i,"m",s).call(this,e);return(0,D.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,g.ago)(g.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new C.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*g.minuteMs,rank:T.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=q,n=new WeakMap,o=new WeakMap,i=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},q.instance=(0,P.lazy)((()=>(0,p.map)((0,k.configDir)(),(e=>new q(I.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return q.instance()?.addPid_(e,t)}},58261:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=r(31421),s=r(48161),o=i(r(1708)),a=r(40958),l=r(22573),u=r(42659),c=r(31586),d=r(68708),h=r(59455),f=r(54993),m=r(48884),g=r(53507),p=r(19851),y=r(50213),v=r(84968),w=r(48963),S=r(56519),b=r(84777),P=r(8103),_=r(45879),E=r(43334),M=r(24399),C=r(45643),T=(0,p.lazy)((()=>(0,y.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){if(E.isLinux)return async function(e){const t=[];for(const r of e)t.push(z(await(0,_.readFileMaybe)("/proc/"+r+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,C.existingPids)(e),r=(await(0,m.collectBatchedAsync)(t,20,E.isWin?L:R)).filter((e=>x(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:r,meta:{pids:e}})}t.isProcEntry=x,t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,C.existingPids)(e),(t=>{const r=[o.default.pid,...t];return e.filter((e=>!r.includes(e)))}))},t.pidInfos=D;const k="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function L(e){if(M.PowerShell.instance().ended)return N(e);const t=[k,"-Id",I(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function N(e){const t=["process"];if((0,a.isNotEmpty)(e)){const r=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",r)}t.push("get",A.join(","));const r=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),i=(0,d.onlyReqValued)((0,g.parseFixed)(A,r.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return i.find((e=>e.pid===o.default.pid))||i.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),i}async function R(e){return t=(await(0,b.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,g.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=N;const j=(0,p.lazy)((()=>{try{if(E.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){T().warn("clk_tck failed",{error:e})}return 100})),B=(0,p.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),V=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function z(e){const t=V.exec((0,f.toS)(e))?.groups,r=(0,c.toInt)(t?.pid),i=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(r)&&!(0,l.blank)(i)&&(0,c.gt0)(n)?{pid:r,cmd:i,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},24399:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const i=r(58587),n=r(19851),s=r(22573),o=r(42659),a=r(41400),l=r(55835),u=r(13538),c=r(36557),d=r(14121),h=r(50213),f=r(7282),m=r(45255),g=r(81168),p=r(25764),y=r(38836),v=r(99331),w=r(56519),S=r(31562),b=r(84777),P=r(34102),_=r(43334),E=r(28874),M=r(63870),C="{ready}",T=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),p.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new i.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",E.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${C}"}`,...(0,s.mapNotBlankOr)(E.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:C,fail:"Error",exitCommand:"exit",maxProcs:E.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),p.EndableRanks.postdb),E.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(E.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,g.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const r=this.mockResults.get(e);return t(r.stdout,r.stderr,r.passed)}try{const r=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new i.Task(e,((r,i,n)=>t((0,l.map)(r,(t=>(0,g.stripPrefix)(t,e))),i,n)))));return this.logger.tap({msg:"execute()",result:r.result,meta:{elapsedMs:r.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,g.ensureSuffix)(e,T),((e,t,r)=>({stdout:e,stderr:t,passed:r})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const r=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,g.ellipsize)(t.stdout),after:(0,g.ellipsize)(r)}),JSON.parse(r)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,n.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const i=r(50989);t.AggregateTypes=(0,i.strEnum)("union","intersection")},71988:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const i=r(50989);t.AssetFileSortCriteria=(0,i.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const i=r(22573),n=r(38639),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(i.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const i=r(50989);t.ColorDistanceFunctions=(0,i.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const i=r(36507),n=r(22573),s=r(45599),o=r(50213),a=r(81168),l=r(98314),u=r(8769),c=r(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,i.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,r){try{return(0,n.blank)(t)?void 0:(0,i.Cron)(t,{name:e,unref:!0,protect:!0,catch:r=>(0,u.onError)(r,{name:e,crontab:t}),...r})}catch(r){return void d().warn("invalid cron",{name:e,crontab:t,error:r})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const i=r(70488),n=r(91655),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration})}get valueOrDefault(){return(0,i.decodeDuration)(super.valueOrDefault)}get value(){return(0,i.decodeDuration)(super.value)}set value(e){super.userValue=(0,i.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,i.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,i.decodeDuration)(this.defaultValue)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const i=r(22573),n=r(53265),s=r(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,i.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const i=r(51926),n=r(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,i.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=r(19851),a=r(40958),l=r(79666),u=r(50357),c=r(57924),d=r(98553),h=r(55835),f=r(68708),m=r(39926),g=r(46891),p=r(42279),y=r(59455),v=r(40583),w=r(81168),S=r(44198),b=r(96706),P=r(34102),_=r(28283),E=r(81075),M=r(98778),C=r(10357);t.settingsToObj=function(e){const t={};for(const r of e)r.hasValue()&&(t[r.name]=r.value);return t},t.Setting=class{constructor(e){i.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,i,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const r=this.opts.whyInvalid?.(e);return null!=r?s(this,i,"m",n).call(this,e??t)+": "+r:null==this.fromEnv(e)?s(this,i,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const r=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=r)return r}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const r=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(r)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return E.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,p.tot)(this.optsOverrides.defaultValue)??(0,p.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,p.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const r=e??(0,S.env)(),i=t??this.value;return null!=i&&(r[this.key]=this.toEnv(i)),null==e&&b.caseInsensitiveEnv.unset(),r}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const r=e??(0,S.env)(),i=this.toEnvValue(t);return null!=i&&(r[this.key]=i,null==e&&b.caseInsensitiveEnv.unset()),r}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const r of t.delete(e)??[])delete process.env[r];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],C.WrapComments);function r(e,r){(0,a.isEmpty)(r)||t.push(...(0,w.wrap)(["",(1===r.length?e:(0,g.pluralize)(e))+": "+(0,c.orList)(r.map((e=>(0,d.stringify)(e))))],C.WrapComments))}r("alias",this.opts.aliases),r("environment alias",this.altKeys);for(const[e,r]of(0,f.entries)(this.addToJSON())){const i=Array.isArray(r)?(0,c.orList)(r.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(r);t.push(...(0,w.wrap)(["",e+": "+i],C.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Example value:"],key:this.name,value:(0,p.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Default value:"],key:this.name,value:(0,p.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,p.tot)(this.fileValue)}),e}},i=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const i=r(50989);t.SettingCategories=(0,i.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const i=r(58587),n=r(51168),s=r(76760),o=r(19851),a=r(40958),l=r(76790),u=r(22573),c=r(42659),d=r(73722),h=r(68708),f=r(50989),m=r(12168),g=r(54993),p=r(37975),y=r(9092),v=r(40583),w=r(79840),S=r(7282),b=r(12801),P=r(4328),_=r(70488),E=r(84248),M=r(5531),C=r(99315),T=r(34365),x=r(34580),D=r(96706),k=r(50274),O=r(33866),I=r(52086),L=r(48584),F=r(45969),A=r(43334),N=r(24540),R=r(70379),j=r(71300),B=r(33209),V=r(48987),z=r(68268),W=r(61208),q=r(99023),U=r(30577),G=r(1485),H=r(19861),J=r(55111),$=r(30933),K=r(22859),Y=r(71988),Z=r(38483),X=r(90536),Q=r(75164),ee=r(10546),te=r(90967),re=r(67958),ie=r(55948),ne=r(57039),se=r(9945),oe=r(74589),ae=r(844),le=r(96093),ue=r(23561),ce=r(69005),de=r(87652),he=r(81075),fe=r(58305),me=r(57571),ge=r(72564),pe=r(80372),ye=r(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new pe.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new pe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new pe.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,p.noColor)()}),logContextLimit:new oe.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new pe.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>G.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:G.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>G.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new pe.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new pe.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,F.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new ge.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:J.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new i.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new pe.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:E.AutoVacuumModes,defaultValue:E.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:C.RepairModes,defaultValue:C.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,F.isDocker)()}),skipHealthCheckIds:new ge.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new pe.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new pe.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:U.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new pe.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,N.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new pe.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new pe.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,$.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:k.SidecarExts,defaultValue:k.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new pe.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ie.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:re.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,$.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:I.CropStrategies.attention,strEnum:I.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:L.SharpFailOns.truncated,strEnum:L.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>V.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:R.DateTagFormats.ym,strEnum:R.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:q.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,F.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,r]of(0,h.entries)(t.Settings))r._setName(e);function be(e){const r=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,F.isDocker)()&&r.unshift("/opt/photostructure/tools/bin"),r.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(r).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,D.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const r of(0,t.persistedSettings)()){for(const t of r.names)e.set(t,r);for(const t of r.keys)e.set(t,r)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,g.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const i=r(19851),n=r(31586),s=r(7282),o=r(49776),a=r(46292),l=r(32774),u=r(55086),c=r(46296),d=r(55939),h=r(96706),f=r(83278),m=r(92234),g=r(45969),p=r(60865),y=r(30933),v=r(15674),w=r(28874);t.setSettingsDefaults=(0,i.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,g.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=p.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const i=r(76760),n=r(40958),s=r(22573),o=r(98553),a=r(55835),l=r(59455),u=r(19851),c=r(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function h(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",i.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const r=t.split("|");for(const t of r)e.set(t,r)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const i=r(40958),n=r(98553),s=r(55835),o=r(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,i.uniq)(e)))),fromEnv:t=>{return r=t,n=e.strEnum,(0,i.compact)((0,o.splitStringArray)(r)?.map((e=>n.getCI(e))));var r,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const i=r(22573),n=r(81168),s=r(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,i.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const i=r(76760),n=r(55835),s=r(46292),o=r(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,i.join)(e,o.SettingsToml)))}},80496:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const i=r(50989);t.TagInferenceSettingValues=(0,i.strEnum)("never","always","auto")},6707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const i=r(90858),n=r(44652),s=r(22573),o=r(76850),a=r(50213),l=r(81168),u=r(84542),c=r(17217),d=r(68284),h=r(98778);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,i.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const i=r(22573),n=r(96249),s=r(98553),o=r(68708),a=r(51926);function l(e,t,r){if((0,i.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,i.blank)(r?.prefix)?[n]:(0,a.wrap)(n.split("\n"),r)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,i.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},65162:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const i=r(4001),n=r(81168);t.bname=function(e,t=!0){let r=(0,n.isString)(e)?e:e.name;return t&&(r=(0,i.stripCopySuffixFromName)(r)),r=(0,n.trimLeftPadding)((0,i.stripDSC)(r)),r.toLowerCase().normalize()}},70379:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const i=r(50989);t.DateTagFormats=(0,i.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},68268:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const i=r(50989);t.KeywordReparentingStrategies=(0,i.strEnum)("move","copy","retain")},61208:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const i=r(50989);t.NameTagFormats=(0,i.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const i=r(50989);t.NameTagOrders=(0,i.strEnum)("western","eastern")},60865:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const i=r(37805),n=r(30577);t.channel=function(){return(0,n.extractUpdateChannel)(i.version)},t.baseVersion=()=>[i.versionMajor,i.versionMinor,i.versionPatch].join("."),t.versionMajorMinor=i.versionMajor+"."+i.versionMinor},76280:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const i=r(38064),n=r(22573),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof i.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const r={loose:!0,includePrerelease:!0};if((0,i.satisfies)(e,t,r))return!0;const s=o(e);return null!=s&&(0,i.satisfies)(s,t,r)},t.toSemver=function(e){try{return e instanceof i.SemVer?e:(0,i.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const i=r(50989);t.UpdateChannels=(0,i.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const r of t.UpdateChannels.values)if(e.includes("-"+r))return r;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},1485:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const i=r(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,i.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69375:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const i=r(19851),n=r(22573),s=r(50213),o=r(9103),a=r(7282),l=r(29882),u=r(43334),c=r(28874),d=(0,i.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,g=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function p(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),r=t[0],i=t[t.length-1];return c.Settings.excludedRootDirectories.has(r)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(i)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===r&&!1===m?.test(e)?"LinuxRunRE":!0===g?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=p(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=p},63870:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const i=r(42659),n=r(12168),s=r(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/i.secondMs},55111:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const i=r(50989);t.HelmetPlugins=(0,i.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},30933:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=i(r(48161)),s=r(19851),o=r(42659),a=r(31586),l=r(50213),u=r(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),r=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??r)),meta:{availableParallelism:e,cpuInfoLength:r}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=i(r(48161)),s=r(19851),o=r(31586),a=r(12168),l=r(50213),u=r(45879),c=r(70417),d=r(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),r=(2*e+t)/3;if((0,d.isDocker)()){const i=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(i))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([i,r]),meta:{freemem:e,totalmem:t,cgroupMem:i}})}return h().tap({msg:"estimatedFreeMem() ",result:r,meta:{result:(0,a.fmtBytes)(r),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},15674:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const i=r(19851),n=r(42659),s=r(41400),o=r(31586),a=r(12168),l=r(50213),u=r(7282),c=r(34102),d=r(57902),h=r(28874),f=r(30933),m=r(58444),g=r(22751),p=(0,i.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,i.lazy)((()=>{const e=(0,o.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*a.MB;return p().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,r=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return p().tap({msg:"timeoutPenalization()",level:r>1?d.LogLevels.warn:d.LogLevels.debug,result:r,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,i.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const r=g.timeoutRate.prior()?.eventsPerMinute??0,i=w();if(1!==i){const e=t;t*=i,p().warn("Recent timeouts! Throttling down.",{penalization:i,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),p().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:i,timeoutsPerSecond:r,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,i.lazy)((function(){return(0,o.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const i=r(58587),n=r(87997),s=r(19851),o=r(42659),a=r(41400),l=r(50213),u=r(7282),c=r(45255),d=r(34102),h=r(976),f=r(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new i.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const g=(0,s.lazy)((()=>(0,n.setInterval)(p,o.minuteMs).unref()));function p(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),g()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),p()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const i=r(76790),n=r(22573),s=r(50357),o=r(98553),a=r(49769),l=r(34666),u=r(30976),c=r(42279),d=r(32639),h=r(59455),f=r(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function g(e){return null==e||0===(0,h.toA)(e).length}function p(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,r)=>e===t[r]))}function v(e,t){for(let r=0;r=e.length||r>=e.length)return e;const i=e[t];return e.splice(t,1),e.splice(r,0,i),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&(0,a.getOrSet)(r,e,(()=>i))}return[...r.values()]}function P(e,t,r=1,i=(e=>e)){const n=[];if(et;s-=r)n.push(i(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=g,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,r){return m(e)?t(e):(0,c.tot)(r)},t.toPrimitive=p,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let r=0;rt.includes(e)))},t.includesAll=function(e,t){if(g(e)||g(t))return!1;for(const r of t)if(!e.includes(r))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const r=(0,i.sortBy)(e,p),n=(0,i.sortBy)(t,p);return r.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const r of t)null==r||e.some((e=>(0,s.eql)(e,r)))||e.push(r);return e},t.pushUniqBy=function(e,t,r){const i=e.map(r);for(const n of t){const t=r(n);i.includes(t)||(e.push(n),i.push(t))}return e},t.insertAt=function(e,t,...r){return e.splice(t,0,...r),e},t.insertUniq=function(e,t,r){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let i=0;i0)return e.splice(i,0,t),e}return e.push(t),e},t.remove=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),r!==e.length},t.removeSame=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>e!==t)))),r!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const r of e)null==r||(0,s.eql)(t[t.length-1],r)||t.push(r);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const r=[];for(const e of(0,i.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))r.some((t=>t.includes(e)))||r.push(e);return(0,i.sortBy)(r,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&r.set(e,i)}return[...r.values()]},t.uniqBy2=function(e,t){const r=[];for(const i of e)null!=i&&r.every((e=>!t(i,e)))&&r.push(i);return r},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,r,i)=>e+(t(r,i)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,r,i)=>e+t(r,i)),0)},t.firstMatch=function(e,t){for(const r of S(t)){const t=e.exec(r);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let r=0;for(;e[r]===t[r];)r++;return r},t.anneal=function({array:e,expense:t,allowedDelta:r}){const i=Math.round(r);if(i<2)return e;for(let r=0;re)){return P(e,t,1,r)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,r,i=t.primitiveValueOfOrElse){const n=new Set(r.map(i));return e.filter((e=>!n.has(i(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const i=r(40958),n=r(36783),s=r(41801),o=r(98553),a=r(49769),l=r(55835),u=r(34666),c=r(59455);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const r=new Map;for(const i of e)(0,a.getOrSet)(r,(0,o.stringify)(t(i)),(()=>i));return f(r.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,l.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,i.compact)(e),i.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,r)=>0===r||t>=e[r-1]))},t.sortedBy=function(e,t){return e.every(((r,i)=>0===i||t(r)>=t(e[i-1])))},t.sortBy=f,t.deepSortBy=function e(t,r){return f(t,r).map((t=>(0,s.isIterable)(t)?e(t,r):t))},t.pushSorted=function(e,t,r){const i=e.findIndex((e=>r(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const i=r(32639);t.asPromise=async function(e){const t=await e;return(0,i.isFunction)(t)?t():t}},5233:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const i=r(41400),n=r(31586),s=r(13538),o=r(41583);t.retryOnReject_=async function(e,t){const r=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return r();const a=t.onRetryWaitUntil??(e=>(0,i.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await r()}catch(e){const r=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(r)||l>t.maxRetries)throw r;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},22573:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const i=r(55835),n=r(42279),s=r(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const r=(0,s.toS)(e);return a(r)?t(r):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const r=(0,s.toS)(e).trim();return r.length>0?r:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,r){return(0,i.orElse)(l(e,t),r)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function r(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function i(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const r=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(r)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=r,t.toBoolean=function(e){return!!r(e)||!i(e)&&void 0},t.toNotBoolean=function(e){return!r(e)&&(!!i(e)||void 0)},t.boolToInt=function(e){return r(e)?1:0},t.isFalse=i,t.isDisabled=function(e){return i(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>r(e)))},t.and=function(e){return e.every((e=>r(e)))},t.maybeAnd=function(e){let t;for(const r of e){if(!1===r)return!1;!0===r&&(t=!0)}return t},t.mapBoolean=function(e,t){return r(e)?t(!0):i(e)?t(!1):void 0},t.mapTrue=function(e,t){return r(e)?t():void 0}},79666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const i=r(98553);t.clone=function(e){return null==e?e:JSON.parse((0,i.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const i=r(40958),n=r(22573),s=r(30301),o=r(55835),a=r(31586),l=r(39926),u=r(51926),c=r(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function g(e){return e instanceof Date}function p(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=g,t.thisYear=function(){return(new Date).getFullYear()},t.ago=p,t.hence=function(e,t){return p(-e,t)},t.unixtime=function(e){const r=g(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(r/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,r={includeMs:!0}){const i=Math.floor(e/t.hourMs);e-=i*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(i)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(r.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const r=()=>{const e=t%100;return t=Math.floor(t/100),e},i=10*r(),n=r(),s=r(),o=r(),a=r(),l=r();return new Date(t,l-1,a,o,s,n,i)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,r="ago"){return e<1e3?"just now":(r=(0,n.blank)(r)?"":(0,u.ensurePrefix)(r," "),et.ms<=e)))){const s=Math.floor(e/i.ms);e-=s*i.ms,s>0&&(i.ms>=t.dayMs?r:n).push(s+i.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+r.join("")+((0,i.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=g(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const i=r(38639),n=r(73872);function s(e,t,r){if(null==r||y(e)||y(t))return null;const i=r.get(e)?.get(t);return"boolean"==typeof i?i:null}function o(e,t,r,i){if(null==r||y(e)||y(t))return;let n=r.get(e);null!=n?n.set(t,i):(n=new WeakMap,n.set(t,i),r.set(e,n))}function a(e,t,r,i){if(null!=r?.comparator)return u(e,t,r,i);const n=l(e,t);return null!==n?n:u(e,t,r)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,r,i){r??(r={});const u=!1===r.memoize?void 0:r.memoize??(r.memoize=new WeakMap),d=r?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const r=d(e,t,i);if(!1===r||!0===r)return o(e,t,u,r),r;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,r,i){switch(r){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return g(e,t,["name","message","code"],i);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,i);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,r){return c(h(e),h(t),r)}(e,t,i);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),i);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),i);case"Set":case"Map":return function(e,t,r){if(e.size!==t.size)return!1;if(0===e.size)return!0;const i=[],n=[];return e.forEach((function(e,t){i.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(i.sort(),n.sort(),r)}(e,t,i);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return p(e,t,i)}}(e,t,y,r);return o(e,t,u,v),v}function c(e,t,r){const i=e.length;if(i!==t.length)return!1;if(0===i)return!0;let n=-1;for(;++n{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,r,i=!1;const n=function(){if(i){if(null!=r)throw r;return t}try{return i=!0,t=e()}catch(e){throw r=e,e}};return n.prior=()=>t,n.hasPrior=()=>i,n}},41400:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const i=r(42659),n=r(35556),s=r(31586),o=r(68708);function a(e,t=!0){return new Promise((r=>{if(e<=0)r();else{const s=setTimeout((()=>r()),Math.ceil(e+.5));e>i.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const r=Math.max(1,Math.ceil(t)),s=n.isNode&&r<=1?setImmediate(e):setTimeout(e,r);return n.isBrowser||t<=i.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},50357:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const i=r(12487),n=r(68708),s=r(34666),o=r(32639);function a(e,t){return(0,i.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const r of(0,n.keys)(e))if(!a(e[r],t[r]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,r){if(null==e||null==t)return e===t;if(null!=r){const i=d.get(r);if(null!=i)return i(e,t)??null}for(const r of c){const i=r(e,t);if(null!=i)return i}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(31586),a=r(68708),l=r(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const r=[];for(const t of e)null!=t&&(t instanceof Error?r.push(u(t),c(t),t?.message):r.push((0,l.toS)(t)));return(0,i.uniq)((0,i.compactBlankish)((0,s.flatten)((0,i.compact)(r).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const r=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,i.isEmpty)(r)?["(missing stack)"]:r}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},96249:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const i=r(59455);t.flatten=function(e,t=[]){for(const r of(0,i.toA)(e))if(null!=r)for(const e of(0,i.toA)(r))null!=e&&t.push(e);return t}},57924:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const i=r(40958);function n(e,t){return null==(e=(0,i.uniq)((0,i.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},73722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const i=r(50989);t.FitSizes=(0,i.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,i.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const i=r(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,r){if((0,i.lt0)(t))return[...e].slice(t,r);const n=e[Symbol.iterator]();if((0,i.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,r){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(r))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],r=[];return function e(i,n){if((0,isFunction_1.isFunction)(i))return;let s,o,a,l=toJSON(i);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(i===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let i=0;t.Latch=class{constructor(e=i++){this.id=e,this[r]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},r=Symbol.toStringTag},30301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const i=r(40958),n=r(50357),s=r(31586),o=r(65812);t.lazy=function(e,t){let r,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return r=Date.now(),async function(e,r){if((0,i.isEmpty)(l))return;const s=await e,a=await r;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==r||(0,s.gt0)(t)&&r+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,r){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const i=r();return null!=i&&e.set(t,i),i}},t.deleteIf=function(e,t){for(const[r,i]of e.entries())t(r,i)&&e.delete(r)}},55835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const i=r(42279),n=r(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,r){return null==e||null==t?void 0:r(e,t)}function a(e,t){return null!=e?e:(0,i.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,r,i){return null==e||null==t||null==r?void 0:i(e,t,r)},t.orElse=a,t.mapOr=function(e,t,r){return null!=e?t(e):(0,i.tot)(r)},t.map2Or=function(e,t,r,i){return a(o(e,t,r),i)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const i=r(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,i.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const i=r(40958),n=r(76790),s=r(50357),o=r(98553),a=r(49769),l=r(55835),u=r(51926),c=r(59455);class d{static fromJSON(e){const t=new d;for(const[r,i]of Object.entries(e))t.add(r,...i);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,i.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const r=(0,a.getOrSet)(this.store,e,(()=>[]));return r.push(...t),r}addUniq(e,...t){return(0,i.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const r=this.store.get(e);if(null==r)return!1;{const i=r.filter((e=>!(0,s.eql)(e,t)));return 0===i.length?this.store.delete(e):this.store.set(e,i),r.length!==i.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,i.uniq)(t))){for(const t of this.keys()){const r=this.store.get(t),n=null==r?[]:e(t,r);(0,i.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,i.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield[t,r])}()}tuples(){const e=this;return function*(){for(const[t,r]of e.store.entries())for(const e of(0,c.toA)(r))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[r,n]of this.store.entries()){const s=(0,i.findIndexes)(n,(t=>!e(r,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(r)}return t}inverse(){const e=new d;for(const[t,r]of this.store.entries())for(const i of r)e.add(i,t);return e}findKeyByTuple(e){for(const[t,r]of this.tuples())if(e(t,r))return t}filterKeysByTuple(e){const t=[];for(const[r,i]of this.entries())i.some((t=>e(r,t)))&&t.push(r);return t}toJSON(){const e={};for(const[t,r]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=r;return e}}function h(e,t){const r=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>r.add(t,e))))),r}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const r=h(e,t);return(0,n.sortBy)((0,c.toA)(r.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const r=globalThis;t.isBrowser="object"==typeof r?.window&&"object"==typeof r?.document,t.isNode="string"==typeof r?.process?.versions?.node},31586:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const i=r(76790),n=r(22573),s=r(42279),o=r(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,r)=>a(t)&&a(r)&&e(t,r);function f(e,r,n){return!(null==n||!a(n))&&([e,r]=(0,i.sort)([e,r]),(0,t.lte)(e,n)&&(0,t.gte)(r,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function p(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return p(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const r=Math.pow(10,t);return P(e*r)/r}function E(e,t,r){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${r})`);return a(r)?rt?t:r:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,r=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(r>=1)return!1;const i=(0===t?1e-5:t)*(1-r);return f(t-i,t+i,e)},t.within=f,t.max_=function(...e){let t;for(const r of e)a(r)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const r=y(e);return null==r?void 0:t(r)},t.mapFloat=function(e,t){const r=v(e);return null==r?void 0:t(r)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,r){return b(e,(e=>b(t,(t=>r(e,t)))))},t.mapNumericOr=function(e,t,r){return a(e)?t(e):r},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const r=t-P(Math.ceil(Math.log10(Math.abs(e)))),i=Math.pow(10,Math.abs(r));return r<0?P(e/i)*i:P(e*i)/i},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!w(e))return[];const r=Math.round(e);return r<=0?[]:[...Array(r)].map(((e,r)=>t(r)))},t.pct=function(e,t){return E(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const r=Math.round(e??-1);return null==t||f(0,t,r)?r+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const r of e){if(!a(r))return;t+=r}return t}},68708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(32639),a=r(55835),l=r(31586),u=r(34666),c=r(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function g(e){return h(e).map((t=>e[t]))}function p(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const r of e)if(null!=r&&Array.isArray(r)){const[e,i]=r;null!=e&&void 0!==i&&("object"!=typeof t&&(t={}),t[e]=i)}return t}function v(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>null!=e)))return e;const r=t.filter((([,e])=>null!=e));return(0,i.isEmpty)(r)?void 0:y(r)}function w(e,t,r={}){return y((0,i.compact)((0,n.sort)(h(e)).map((r=>t(r,e[r])))).filter((([e,t])=>null!=e&&void 0!==t)),r)}function S(...e){const t=(0,i.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const r=t.filter(d);if(t.length!==r.length)return t;const n={};for(const e of(0,i.uniq)((0,i.flatMap)(r,h)))n[e]=S(...r.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const r=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(r.test(t))return{key:t,value:e[t]}}function P(e){return g(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const r=v(e);return m(r)?t(r):void 0},t.values=g,t.entries=p,t.fromEntries=y,t.assignFields=function(e,t,r){if(null==t)return e;for(const[i,n]of p(t))!0!==r?.omitKeys?.includes(i)&&(null==n&&!0!==r?.assignNullish||(e[i]=n));return e},t.assignUndefinedFields=function(e,t,...r){if(null==t)return e;for(const i of r){const r=t[i];void 0!==r&&void 0===e[i]&&(e[i]=r)}return e},t.assignAllFields=function(e,t){for(const[r,i]of p(t??{}))e[r]=i;return e},t.definedValues=function(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>void 0!==e)))return e;const r=t.filter((([,e])=>void 0!==e));return(0,i.isEmpty)(r)?void 0:y(r)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,i.compact)(t.map(e));{const r=(0,i.compact)(p(t).map((([t,r])=>(0,a.map)(e(r),(e=>[t,e])))));return 0===r.length?void 0:y(r)}}},t.compactBlankValues=function(e){if(null==e)return;const t=p(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,i.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickCompact=function(e,...t){if(null==e)return;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickNonBlank=function(e,...t){if(null==e)return e;const r={};for(const i of t){const t=e[i];(0,s.notBlank)(t)&&(r[i]=t)}return r},t.pickFirst=function(e,t,r=a.defined){if(null!=e)for(const i of t)if(r(e[i]))return e[i]},t.pickDeep=function e(t,...r){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...r)));const i={};function n(e,t){if(null==t)return;const r=i[e];i[e]=null==r?t:S(r,t)}for(const i of r){const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const i of h(t))((0,l.toInt)(i)??-1)>=0&&n(i,e(t[i],...r));return i},t.pluck=b,t.pluckDeep=function e(t,r){if(null==t||(0,s.blank)(r))return;if(Array.isArray(t)){const n=(0,i.compact)(t.map((t=>e(t,r))));return(0,i.isEmpty)(n)?void 0:{key:n[0].key,value:(0,i.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(r,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const r=p(e).filter((([e])=>!t.includes(e)));return(0,i.isEmpty)(r)?void 0:y(r)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(p(e).filter((([e,r])=>t(e,r))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,i.uniq)(t)},t.maybeCall=function(e,t,...r){const i=e?.[t];return(0,o.isFunction)(i)?i.bind(e)(...r):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const r=t.toLowerCase().normalize();for(const t of h(e))if(r===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const r=w(t,((t,r)=>[t,e(r)])),i=g(r);return 1===i.length?i[0]:r}},97790:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(r||(r={})),t.None=r;class i{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new i(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,r){return s(e).flatMap((e=>s(t).flatMap((t=>r(this.a,e,t)))))}zip3(e,t,r,i){return s(e).flatMap((e=>s(t).flatMap((t=>s(r).flatMap((r=>i(this.a,e,t,r)))))))}}function n(e){return e instanceof i||e===t.None}function s(e){return n(e)?e:null!=e?new i(e):t.None}t.Some=i,t.isOpt=n,t.opt=s},39926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const i=r(31586),n=r(54993),s={};function o(e,t){if(t<1)return"";if(!(0,i.gte)(s[e]?.length,t)){let r=s[e]??e;for(;r.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const i=r(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,i.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const i=r(40958),n=r(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,r){return o(e)?t(e):r()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,r){if(null==e&&null==r)return 0;if(null==e)return-1;if(null==r)return 1;const i=typeof e,s=typeof r;if(!("string"!==i&&"symbol"!==i||"string"!==s&&"symbol"!==s)){const i=(0,n.toS)(e),s=(0,n.toS)(r),o=i.localeCompare(s);return i[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(r)?u(e,r):i!==s?a.indexOf(i)-a.indexOf(s):e>r?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const i=r(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const r=await e;return null==r?void 0:t(r)},t.thenCollect=async function(e,t){const r=[];for(const n of(0,i.toA)(await e))if(null!=n){const e=await n;if(null!=e){const i=await t(e);null!=i&&r.push(i)}}return r},t.thenTap=async function(e,t=console.dir.bind(console)){const r=await e;return await t(r),r},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:r}){const i=await e;return t(i)?r(i):void 0}},57153:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const i=r(50989);t.PromiseStates=(0,i.strEnum)("pending","resolved","rejected")},30976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const i=r(40958),n=r(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,r){return null==r||0===r.length?s(e,t):a(e,t,1,r)[0]}function a(e,t,r,i){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(i??[]);if(t===e&&0===n&&0===o.size&&1===r)return[e];const a=n-o.size;if(r>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:r,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const r=Math.floor(Math.random()*(e+1));e!==r&&([t[e],t[r]]=[t[r],t[e]])}return t},t.sample=function(e,t){const r=[];for(const i of a(0,e.length,t))r.push(e[i]);return r},t.pickWeightedRandom=function(e){if((0,i.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let r=l(0,(0,i.sum)(t,(e=>e.priority)));return t.find((e=>(r-=e.priority,r<=0)))}},5670:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const i=r(50989);t.ServiceNames=(0,i.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const r=e.indexOf(t);return-1===r?[e]:[e.slice(0,r),e.slice(r+t.length)]}},50989:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const i=r(68708),n=r(42279);t.strEnum=function(...e){const t=Object.freeze(e),r=(0,i.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?r[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const r=o(e),i=o(t);return null==r||null==i?void 0:r>i?1:r{const r=o(e);return null==r?void 0:t[r]}}}},51926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const i=r(40958),n=r(17586),s=r(22573),o=r(96249),a=r(41801),l=r(31586),u=r(59455),c=r(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,r){if(d(e))return t<0&&(t+=e.length),e.slice(t,r);{const i=f();return null!=i?(0,a.sliceIterable)(i.segment(e),t,r).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,r).join("")}}function g(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function p(e,t){const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.startsWith(i)?r.slice(i.length):r}function y(e,t){if(null==t)return e;const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.endsWith(i)?r.slice(0,-i.length):r}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,r){null==r&&(r=e.length);for(let i=r;i>=0;i--)if(m(e,i).startsWith(t))return i;return-1}function b(e,t,{normalize:r=!0}={}){if(null==e||null==t)return!1;const i=(0,c.toS)(e),n=(0,c.toS)(t);return i.length===n.length&&(i===n||i.toLowerCase()===n.toLowerCase()||"function"==typeof i.localeCompare&&0===(r?i.normalize():i).localeCompare(r?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,i.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,r){return d(e)?e.slice(t,null==r?void 0:t+r):m(e,t,null==r?void 0:t+r)},t.charArr=g,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=p,t.stripPrefixes=function e(t,r){if(null==t)return"";const i=(0,c.toS)(t);for(const t of r)if(null!=t&&t.length>0&&i.startsWith(t))return e(i.slice(t.length),r);return i},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:r}){return y(p(e,t),r)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:r}){return w(v(e,t),r)},t.ellipsize=function(e,t=80,r=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),r=(0,l.clamp)(0,t-1,(0,l.round)(r));const i=g(e);return i.length<=t?i.join(""):i.slice(0,t-1-r).join("")+"…"+(r>0?i.slice(-r).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,r){const i=r?.maxLineLen??80,n=r?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const i=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(i.map((t=>e(t,r))))}if((t=v((0,c.toS)(t),n).trim()).length<=i)return[t];const s=S(t," ",i);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),r)];{const i=t.indexOf(" ",n.length+1);return i>0&&i{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const i=r(42659),n=r(68708),s=r(42279),o=r(83104),a=r(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,r=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(r,i)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,r(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,r(t))}catch(e){n&&(n=!1,i(e))}finally{clearTimeout(s)}}))}async function c(e,t,r=!0){const n=await u(e,t,r);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,r=!0){return u(e,t,r).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,r=!0){const i=t-Date.now();return i<=0?o.Timeout:u(e,i,r)},t.thenOrOnTimeout=async function(e,t,r){return t<=0?e:new Promise((async(i,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{i(await r())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),i(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,r=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(n)+")");return c(e,n,r)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:r,unref:i=!0}){if(null==e)return(0,s.tot)(r);const n=await u(e,t,i);return n===o.Timeout?(0,s.tot)(r):n}},42279:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const i=r(32639);t.tot=function(e){return(0,i.isFunction)(e)?e():e},t.tol=async function(e){return(0,i.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class r extends Error{}t.TimeoutError=r},12168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const i=r(22573),n=r(30301),s=r(31586),o=r(46891),a=r(50989),l=r(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let r=0;for(const i of e)(0,s.isNumber)(i)&&(r+=i/t.MB);return(0,s.round)(r)},t.fmt=c,t.fmtToInt=function(e){return(0,i.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const r=Math.floor(Math.log10(e)),i=Math.floor(r/3),n=Math.pow(10,3*i),o=d[i];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,r=3){return f(e*t.MB,r)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const r=Math.floor(Math.log2(e)),i=Math.floor(r/10),n=Math.pow(2,10*i),o=h[i];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,r){return null==e?"":(0,i.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(r??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,r){return r??(r=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:r}}},65812:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const i=r(68708);t.setUnrefTimeout=function(e,t){const r=setTimeout(e,t);return(0,i.maybeCall)(r,"unref")??r}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const i=r(41801),n=r(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,i.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const i=r(40958),n=r(23541),s=r(59455),o=r(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,i.compact)((0,s.toA)(e).map(a))}},54993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const i=r(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,i.stringify)(e)}}t.toStr=s},90858:e=>{e.exports=require("@iarna/toml")},58587:e=>{e.exports=require("batch-cluster")},6858:e=>{e.exports=require("commander")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},38064:e=>{e.exports=require("semver")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},77030:e=>{e.exports=require("node:net")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}var __webpack_exports__={},exports;exports=__webpack_exports__,Object.defineProperty(exports,"__esModule",{value:!0}),__webpack_require__(36389),module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/main.js b/bin/main.js index 5d45297..46acf9b 100755 --- a/bin/main.js +++ b/bin/main.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:n}=i(60308),{decode:s}=i(47859),o=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:a,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new n("unsupported PASETO version");if("local"!==a&&"public"!==a)throw new n("unsupported PASETO purpose");const d={footer:u?s(u):void 0,payload:void 0,version:i,purpose:a};if("local"===a)return d;const f="v1"===i?256:"v3"===i?96:64;let h;try{h=s(l).subarray(0,-f)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?o(h):h,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:n,jti:s,kid:o,notBefore:a,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(a))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.issuer must be a string");c.iss=n}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.kid must be a string");c.kid=o}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.jti must be a string");c.jti=s}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),n=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:s,subject:o,issuer:a,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const f=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.issuer must be a string");if(d.iss!==a)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.subject must be a string");if(d.sub!==o)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const h=l?n(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>f+h)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>f+h)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=f-h)throw new r("token is expired")}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+n(s){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),n=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!n(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),n=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,n),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:n}=i(60308),s=i(10968),{decode:o}=i(47859),a=i(40816);e.exports={post:function(e,t,i,r,n,o,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:n,footer:o?.length?o:void 0,version:e,purpose:l}:n}const u=a(n);return s(i,u),r?{payload:u,footer:o?.length?o:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new n(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:s="",length:a}=t.slice(e.length).split(".");try{r(a<=2),i=o(i),s=o(s)}catch{throw new n("token is not a PASETO formatted value")}return{raw:i,f:s}}}},56463:(e,t,i)=>{const r=i(76982),n=i(92460),s=i(70761),o=i(29534),{PasetoDecryptionFailed:a}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=n.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),f=Buffer.from("paseto-auth-key-for-aead"),h=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:n.promisify(r.sign),verify:n.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const n="v1.local.",a=m(e,r.randomBytes(32)).subarray(0,32),l=a.subarray(0,16),[u,h]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,f,32).then(Buffer.from)]),p=await g(e,u,a.subarray(16)),y=s(n,a,p,t),v=m(y,h);return o(n,t,a,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),n=e.subarray(-48),o=e.subarray(32,-48),u=r.subarray(0,16),[h,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,f,32).then(Buffer.from)]),g=s("v1.local.",r,o,t),v=m(g,p);if(!l(n,v))throw new a("decryption failed");const w=await y(o,h,r.subarray(16));if(!w)throw new a("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,n){const a="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,h,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,h,Buffer.concat([f,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),S=s(a,l,w,t,n),b=m(S,p);return o(a,t,l,w,b)},"v3.local-decrypt":async function(e,t,i,r){const n=e.subarray(0,32),o=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,h,Buffer.concat([d,n]),48).then(Buffer.from),c("sha384",i,h,Buffer.concat([f,n]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),S=s("v3.local.",n,u,t,r),b=m(S,g);if(!l(o,b))throw new a("decryption failed");const P=await y(u,v,w);if(!P)throw new a("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:n}=i(75162);n||(n=e=>null!=e&&e instanceof r),e.exports=n},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,n=Buffer.allocUnsafe(8);return n.writeUInt32LE(t,4),n.writeUInt32LE(i,0),n}},85223:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const n=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*n);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*n);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(n*t);case"day":case"days":case"d":return Math.round(864e5*n);case"week":case"weeks":case"w":return Math.round(6048e5*n);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*n)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let n=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(n+=`.${r(t)}`),n}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:n}=i(64770),s=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return n(s(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),n=i(70761),s=i(29534);e.exports=async function(e,t,i,o,a,l,u){const c=n(u,e,t,i,l),d=await r(o,c,a);return s(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),n=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!n(t))try{t=r(t)}catch{}if(!n(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),n=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(n(e,i),n(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:n}=i(56463),s=i(70761),{pre:o}=i(88965);e.exports=async function(e,t,i,a,l,u,c){const{raw:d,f}=o(e,t),h=d.subarray(0,-a),m=d.subarray(-a),p=s(c,e,h,f,u);if(!await n(i,p,l,m))throw new r("invalid signature");return{m:h,footer:f.length?f:void 0}}},91227:(e,t,i)=>{const r=i(60308),n=i(79665),s=i(56120),o=i(50015),a=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:n,V2:s,V3:o,V4:a,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),n=i(495).bind(void 0,"v1.local"),{pre:s,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:a=!1,...l}={}){const{raw:u,f:c}=s("v1.local.",e),d=(t=n(t)).export(),f=await r(u,c,d);return o("v1",a,l,i,f,c,"local")}},21472:(e,t,i)=>{const r=i(83561),n=i(495).bind(void 0,"v1.local"),s=i(1658),{"v1.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=n(t);const u=r(i),c=t.export();return o(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),n=i(77256),s=i(21472),o=i(39324),a=i(70866);e.exports={sign:r,verify:n,encrypt:s,decrypt:o,generateKey:a}},70866:(e,t,i)=>{const r=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:s}=i(60308),o=n(r.generateKeyPair),a=n(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await a("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await o("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new s("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPrivateKey:s}=i(76982),o=i(83561),a=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=a(e,c),f=o(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=s(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,f,"sha384",{key:t,padding:r,saltLength:n})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPublicKey:s}=i(76982),o=i(49826),a=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!a(e)||"private"===e.type)try{e=s(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:f}=await o("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:n});return l("v1",u,c,i,d,f,"public")}},56120:(e,t,i)=>{const r=i(88451),n=i(859),{generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}=i(62827);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}},62827:(e,t,i)=>{const r=i(64770),n=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:o}=i(60308),a=i(70981),l=s(n.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${f(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${f(r).toString("base64url")}`}:t}throw new o(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=n.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return n.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!a(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function f(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!a(t))try{t=n.createPrivateKey(t)}catch{}if(!a(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!a(t)||"private"===t.type)try{t=n.createPublicKey(t)}catch{}if(!a(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:f}},88451:(e,t,i)=>{const r=i(83561),n=i(1658),s=i(92366),{_checkPrivateKey:o}=i(62827),a=o.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=a(t);const u=r(i);return s("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:n}=i(62827),{post:s}=i(88965),o=n.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,...a}={}){t=o(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return s("v2",n,a,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),n=i(495).bind(void 0,"v3.local"),s=i(80608),{pre:o,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f}=o("v3.local.",e);t=n(t);const h=s(u),m=t.export(),p=await r(d,f,m,h);return a("v3",l,c,i,p,f,"local")}},43406:(e,t,i)=>{const r=i(83561),n=i(495).bind(void 0,"v3.local"),s=i(1658),o=i(80608),{"v3.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=s(e,u);t=n(t);const d=r(i),f=o(l),h=t.export();return a(c,d,h,f)}},50015:(e,t,i)=>{const r=i(42438),n=i(65466),s=i(43406),o=i(18582),{generateKey:a,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:n,encrypt:s,decrypt:o,generateKey:a,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:s}=i(60308),o=i(70981),a=i(82115),l=n(r.generateKeyPair),u=n(r.generateKey);function c(e){if(!o(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return a(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new s("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),n=i(83561),s=i(1658),o=i(80608),a=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...f}={}){const h=s(e,f),m=n(i),p=o(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),a("v3.public.",h,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),n=i(80608),s=i(49826),o=i(70981),{bytesToKeyObject:a}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...f}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=a(e)}catch{}if(!o(e)||"private"===e.type)try{e=r(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const h=n(d),{m,footer:p}=await s("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},h,l(t));return u("v3",c,f,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),n=i(77933),{generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}=i(24961);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:n,_generateKey:s,_keyObjectToBytes:o,bytesToKeyObject:a}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:n,bytesToKeyObject:a,generateKey:async function(...e){return s("v4",...e)},keyObjectToBytes:function(...e){return o("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),n=i(1658),s=i(80608),o=i(92366),{_checkPrivateKey:a}=i(24961),l=a.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:a,...u}={}){const c=n(e,u),d=s(a);t=l(t);const f=r(i);return o("v4.public.",c,f,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),n=i(49826),{_checkPublicKey:s}=i(24961),{post:o}=i(88965),a=s.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,assertion:l,...u}={}){t=a(t);const c=r(l),{m:d,footer:f}=await n("v4.public.",e,void 0,64,t,c);return o("v4",s,u,i,d,f,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),n=i(22573),s=i(38639);function o(){return(0,s.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,n.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),n=i(7282),s=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),n=i(36783),s=i(76790),o=i(22573),a=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),f=i(34666),h=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const n=new Set(t.map(i));return e.filter((e=>n.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,f.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,f.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return T(e,t,i).index}function T(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let r=0;re.slice(i,i+t)))}async function D(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,h.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,h.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,h.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let n=0;for(const s of e)(t(s,n++)?i:r).push(s);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=T(e??[],t,f.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=x,t.collectBatched=function(e,t,i){const n=[];for(const s of x((0,r.compact)((0,h.toA)(e)),t))n.push(...(0,r.compact)(i(s)));return n},t.collectBatchedAsync=async function(e,t,i){const n=[];for(const s of x((0,r.compact)((0,h.toA)(e)),t))n.push(...(0,r.compact)(await i(s)));return n},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await D(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+n;if(re+1),1));return(0,h.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=i(77988),l=o(i(1708)),u=i(19851),c=i(42659),d=i(55835),f=i(31586),h=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),S=i(99331),b=i(95937),P=i(98314),M=i(38835),_=i(70025),E=i(8769),T=i(43334),x=i(95402),D=i(28874),k=i(63870);class C extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,r,"m",n).call(this)),i,"worker"===e?(0,k.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const o=t;o.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,x.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new h.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+M.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,i,r)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,f.gt0)(e?.pid)&&x.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,_.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,E.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,r=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(T.isWin?3:1)*c.minuteMs,maxTasksPerProcess:D.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:D.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:D.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,k.commandTimeoutMs)(),taskTimeoutMillis:D.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class f{constructor(e){if(r.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,r,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,r,"m",a).call(this,0,(e=>{var t,i;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(i=u(this,s,"f"),--i),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const i=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=f},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of n)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,r.toS)(e)},t.bufferStartsWith=o},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(40958),a=i(23838),l=s(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,n=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(r=e,n=o)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),n=i(31586),s=i(68708),o=i(54993),a=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,n]of this.m.entries()){const s=e(r);t.fill(s,i,i+n),i+=n}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),n=i(72993),s=i(45969),o=i(43334);t.EditionType=(0,r.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),n=i(55835),s=i(68708);var o=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.omit)(e,...i),(0,s.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,n.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),n=i(19851),s=i(95696);t.examples=(0,n.lazy)((()=>s.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),n=i(65843),s=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,n.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),n=i(40958),s=i(55835),o=i(31586),a=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),f=i(54993),h=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new h.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(i=l(this,n,"f"),++i),"f"),c.promise):(u(this,r,(o=l(this,r,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(a=l(this,r,"f"),++a),"f"),c}get(e){var t,i;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,f.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(r=l(this,a,"f"),++r),"f")})),r.promise}},r=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class f{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const h=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,r).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new f(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,a=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(a,r.index);(0,s.blank)(l)||(h().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),f=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==f)this.skippedHeaders.push(m),h().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:f});else{const e=(0,n.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=f}a=t.lastIndex}const l=(0,n.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),n=i(20014),s=i(55222),o=i(97352),a=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,o.within)(-90,90,e)&&0!==e}function c(e){return(0,o.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function f(e,t,i=a){return(0,r.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=a){return f(e?.lat,e?.lon,t)},t.geohash=f,t.geohashNumericShort=function(e,t){return m(e,t,30)};const h=new n.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=a){return d(e,t)?h.zip([t,e],l(i)):void 0}function p(e,t=a){return h.unzip(e,l(t))?.reverse()}function g(e,t=a){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=a){return(0,r.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,n=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,o=Math.sin(n/2)*Math.sin(n/2)+Math.cos(i)*Math.cos(r)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),n=i(98553);var s=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,n.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,r.readFile)(e)).toString())}},57206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(77988),n=i(51168),s=i(45599),o=i(98553),a=i(68708),l=i(24689),u=i(21330),c=i(57159),d=i(28544),f=(0,s.defer)((()=>{n.DateTime.prototype.toJSON=function(){return(0,a.compactValues)({_ctor:n.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),h={name:n.DateTime.name,fromJSON:e=>n.DateTime.fromMillis(e.ts,(0,a.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{f(),(0,o.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,h,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},19851:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(57975),a=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new f(e,t)};class f extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,r,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(42659),a=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),f=i(44198),h=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,f.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,n.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*o.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,h.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),n=i(1708),s=i(45599),o=i(68708),a=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),f=i(37805),h=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,s.defer)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:f.version,StartTs:d.StartTs,argv:n.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,o.pick)(n.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:n.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,h.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),n=i(32105),s=i(14593);t.rootLoggers=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),n=i(55835),s=i(59455),o=i(48884);function a(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,r.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,n.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),n=i(54557);t.memoize=function(e,t){let i=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,r.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,r.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),n=i(31586),s=i(12168),o=i(70417);function a(){const e=(0,r.memoryUsage)();return(0,o.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=a,t.memoryUsageMb=function(){return(0,n.sigFigs)(a()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,n.sigFigs)(l()/s.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=r(i(1708)),s=i(38639),o=i(54993),a=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(55835),a=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function f(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=f,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=r&&r>0&&null!=n&&n>0?i(r,n):void 0};const h=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(h.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function p(e){return(0,a.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const n=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),n=i(42659),s=i(96249),o=i(55835),a=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),f=i(81168);function h(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,n]of(0,l.entries)(e)){const e=t(r,n);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=h,t.tryEach=function(e,t){[...e].forEach((e=>h((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const n of t)r[n]=i(n,e[n]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let n=0;for(const s of(0,l.keys)(e))if(r[s]=t(s,e[s]),n++,(0,a.gt)(n,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,s.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),n=i(73024),s=i(48161),o=i(19851),a=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),f=i(48884),h=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,o.lazy)((()=>(0,h.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,n.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const T={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},x={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),n=t[i];return(0,c.isString)(n)?n:n?.[r]}const k=(0,o.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,a.mapNotBlankOr)(function(e=k()){return D(e,T)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,x);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,f.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=r(i(48161)),s=i(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(72993),n=i(50213),s=i(23560),o=i(43334);let a=!o.isElectron;t.setShortProcessNames=function(e){a=e},t.setProcessTitle=function(){try{const e=[a?r.SimpleShortAppName:r.SimpleAppName];(0,s.isMainService)()&&o.isElectron||e.push((0,s.serviceName)());const t=e.join(o.isElectron?" ":"-");i(85949).title=t}catch(e){(0,n.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},92782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),n=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,n.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,n.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),n=i(56409),s=i(31586),o=i(22911),a=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,f,h=!1,m=0;t=Math.ceil(t);const p=[];function g(){return h||m>Date.now()}function y(){if(null!=f){const e=f;f=void 0,w(...e)}}async function v(...r){h=!0,m=Date.now()+(0,s.max_)(t,i);const n=d=new o.Deferred(c);(0,s.gt0)(i)&&n.setTimeout(i);try{n.resolve(await e(...r))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{h=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return n.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return f=e,(0,r.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{f=void 0},w.donePromise=()=>{if(!h)return Promise.resolve();const e=new n.Latch;return p.push(e),e},w.force=async(...e)=>(f=void 0,h&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:h,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),n=i(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(n,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(s(t))}const n=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,r||(r=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,n.toS)(t));return new RegExp(i,t??(r?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=r(i(48161)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),f=i(51926),h=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),S=i(24399),b=i(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,f.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return n.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(h.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=r(i(1708)),s=i(19851),o=i(40958),a=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||f(e)},t.isMainService=d,t.isWebService=f,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=h,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||f()||((0,u.isTest)()||p())&&!h()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!f()&&!d()&&!h()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function n(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=n(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=n(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),n=i(57150),s=i(7282),o=i(23560),a=i(17181);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,a.setupLogger)(),(0,n.logStartup)())}},28850:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const a=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends a.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),n.set(this,void 0),s(this,r,e,"f")}_call(){return(0,l.time)(o(this,r,"f")+(null==o(this,n,"f")?"(local)":"(remote)"),null==o(this,n,"f")?this.impl():o(this,n,"f").call(this))}setShim(e){s(this,n,e,"f")}hasShim(){return null!=o(this,n,"f")}clearShim(){s(this,n,void 0,"f")}}r=new WeakMap,n=new WeakMap},12089:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),f=i(54993),h=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends h.ExtensibleFunction{constructor(e,t,i,o){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",o).call(this,e),(()=>u(this,r,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,r=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,f.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=i(76790),o=i(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return n(this,r,"f")[Symbol.iterator]()}get length(){return n(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=n(this,r,"f").length-1;for(;t<=i;){const s=t+Math.floor((i-t)/2),o=this.valueOf(n(this,r,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:i=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...n(this,r,"f")];const o=t=>t<0||t>n(this,r,"f").length-1?null:(i??this.diff)(n(this,r,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const f=[];for(;f.lengththis.valueOf(e)))}shift(){return n(this,r,"f").shift()}at(e){return(0,o.at)(n(this,r,"f"),e)}toA(){return[...n(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,r,"f").length-1){const e=[...n(this,r,"f")];return n(this,r,"f").length=0,e}return n(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),n=i(82328),s=i(84542),o=i(95705),a=i(28874);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),n=i(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=r(i(1708)),s=i(22573),o=i(98553),a=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function f(e,t){return h({obj:e,ready:t,stream:n.default.stdout})}function h({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);r.write(n+"\n"),(0,a.isWorkerService)()&&null!=i&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=f,t.stderrWrite=function(e){return h({obj:e,stream:n.default.stdout})},t.writeTTY=h,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);f(t)},t.stdoutWriteMigration=function(e){return f({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>f({shutdownSync:!0}),restartSync:()=>f({restartSync:!0}),forceRestartSync:()=>f({forceRestartSync:!0}),rebuildLibrary:()=>f({rebuildLibrary:!0}),shutdown:()=>f({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(55835),a=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),f=i(54993),h=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,f.toS)(e),t=(0,f.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,f.toS)(e).indexOf((0,f.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const n=t.indexOf(i,r);return-1===n?0:1+e(t,i,n+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(f.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,a.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,f.toS)(e),t=(0,f.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,f.toS)(e),n=(0,f.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(r.slice(-n.length),n,i)?r.slice(0,-n.length):r},t.gist=function(e,t=80,i=80){const r=(0,f.toS)(e),n=r.length-(t+i);return n<=0?r:r.slice(0,t).trim()+" …(+"+n+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,f.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,f.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,f.toS)(e))},t.capitalize=function(e){return e=(0,f.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),n=t.indexOf(r);if(n>=0)return{index:n,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,h.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,f.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,f.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const T=/^['‘’].*['‘’]$/,x=/^["“”„«»〃].*["“”„«»〃]$/;function D(e,t){const i=k(e,t);return(0,h.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,i.push(e.substring(s,n.index)),r.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,f.toS)(e).trim(),T.test(e)||x.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),n=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,f.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,f.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,n.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(f.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,s.blank)(r))for(const e of r.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>r.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function n(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=r(i(77598)),s=i(73913),o=i(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,r=224){return i.encodeBuffer(a(e,r)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(31586),a=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),f=i(88158),h=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,n="";for(let s=0;s=r&&(r=i.get(s,o),n=(0,l.substr)(e,s-r+1,r)));return n}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),n=t.normalize();return e!==r||t!==n?y(r,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,f.firstThunk)((()=>i===r?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,h.intersection)(e,t),n=[];return i.forEach((i=>{const s=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,o.times)(s,(()=>n.push(i)))})),n}function b(e,t,i){const n=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,n))-i((0,l.strslice)(t,n))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,r,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,r,(e=>c.RadixAlphaNum.decode(e)))}function T(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const n=(0,o.mapNumericOr)(e.charCodeAt(r),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(r),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=T,t.paddedPositionalDiff=function(e,t,i=8){return T((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),n=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,n.sortedKeys)(e))}},75387:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const h=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",n.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){f(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),f(this,a,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const n=t();return null!=n&&this.set(e,n),n}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,h.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,n,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,n,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,r,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,r,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,r,"m",n).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,r,"m",n).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,r,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,r,"m",s).call(this),[...this.delegate.keys()]}[(r=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,r,"m",n).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=r(i(48161)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),f=i(45255),h=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,h.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:f.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),n=i(55835),s=i(31586),o=i(97790),a=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(i))return;const[o,a,u,c,d,f,h]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,f,h/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,r,"f")&&clearTimeout(s(this,r,"f")),o(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,n=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const n=r(i(87997)),s=i(31586);t.debounce=function(e,t){let i,r=[];const o=(0,s.gt0)(t)?(...s)=>{r=s,null!=i&&n.default.clearTimeout(i),i=n.default.setTimeout((()=>{e(...r)}),t)}:e;return o.reset=()=>{null!=i&&n.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},22911:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f,h,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),S=i(45599),b=i(26905),P=i(55835),M=i(31586),_=i(68708),E=i(20214),T=i(57153),x=i(85556),D=i(50213),k=i(70025),C=i(95937),O="TIMEOUT",I=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,M.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const n=i[r];if(n.isSettled){if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield n.value}}if(i.every((e=>e.name===O)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,T.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),f.set(this,void 0),h.set(this,void 0),this.id=(g(i=n,n,(y=p(i,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,h,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,h=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,f,"f")&&(v.default.clearTimeout(p(this,f,"f")),g(this,f,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,M.gt0)(e)&&(g(this,f,v.default.setTimeout((()=>{this.isPending&&(this.reject(new x.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,f,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===T.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==T.PromiseStates.pending}get isResolved(){return p(this,a,"f")===T.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===T.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,a,T.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,T.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,n=F,m=function(e){if(p(this,a,"f")===T.PromiseStates.pending){(0,P.map)(p(this,f,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),n=i(40958),s=i(42659),o=i(23838),a=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),f=i(25764),h=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,a.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return f.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,h.setEnding)(!0),w();for(const t of f.EndableRanks.values){const i=g.get(t)??[];(0,n.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,h.setEnding)(!0),Promise.all((0,n.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of f.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),f=i(55835),h=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,h.toInt)(e)??0,t=(0,h.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",o).call(this);const f=()=>{u(this,r,"a",l)&&(0,h.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,h.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,a,"f").call(this),f())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):f(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){(0,f.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,f.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),f=i(25764),h=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=f.EndableRanks.first,o){this.endTimeoutMs=o,r.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,h.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){o(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,n=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,r.isTest)()?e:e||n}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=r(i(1708)),s=i(22573),o=i(45599),a=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),f=i(28874),h=i(27395),m=i(99331),p=i(56038),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{f.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,h.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(45599),h=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,f.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new S(e,t,i,r)};class S extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,r,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,h.eql)(e?.value??await(e?.promise),i))for(const e of c(this,a,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(i=c(this,s,"f"),++i),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),n=i(80049);t.memoizeAsync=function(e,t){let i=0;const s=new n.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,r.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},22781:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),n.set(this,!1),s.set(this,!1)}_call(){return o(this,n,"f")?(a(this,s,!0,"f"),!0===this.undefinedIfBusy?void 0:o(this,r,"f")):(a(this,n,!0,"f"),a(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{a(this,n,!1,"f"),!0===this.runLaterIfBusy&&o(this,s,"f")&&(a(this,s,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return o(this,n,"f")}prior(){return o(this,r,"f")}async force(){return await o(this,r,"f"),this._call()}}r=new WeakMap,n=new WeakMap,s=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),n=i(76790),s=i(38639),o=i(42659),a=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),f=i(32639),h=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var S=i(20214);async function b(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:n}){const s=[];for(const o of(0,r.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(i(o),n):i(o));null!=e&&s.push([e,o])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function _({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,r.compact)(await e);if((0,r.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(i,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,f=await u.enqueueAll(i,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(f).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,i){const r=[];for(const n of(0,p.batches)((0,h.toA)(await e),t)){const e=await b(n);r.push(...await b(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,h.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,h.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,h.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,h.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s}){return(await _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:n,timeoutMs:s}){return(await _({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,n=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(n??r)}catch{}if(null!=n)throw n;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const n=await t;return null!=n?i(r,n):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const n=await t(r);return null==n?i():n},t.thenMap2Or=async function(e,t,i,r){const n=await e;if(null==n)return r();const s=await t;if(null==s)return r();const o=await i(n,s);return null==o?r():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await _({name:e,arr:t,f:i});return(0,n.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(42659),a=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),f=i(22454),h=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),S=i(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new f.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-r;return i?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new h.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},42638:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const h=f(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),S=i(82647),b=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new h.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:n}){const s=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const n=new P.Deferred(e,{payload:i,serialId:r});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),n=i(34546),s=i(41400),o=i(31586),a=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let a=!0;return Promise.race((0,r.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),n=i(42659),s=i(41400),o=i(32639),a=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let f=!1;const h=null==t?void 0:t+Date.now();let m=1;for(;null==h||Date.now()t/2&&!f&&(f=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(r,d),m++}}return f||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=r(i(1708)),s=i(45599),o=i(41400),a=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),f=i(59958),h=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),S=i(88158),b=i(45969),P=i(43334),M=i(28874),_=i(3790);function E(e){return T().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const T=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(M.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(f.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>E(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,M.allSettings)())t.watchLater(e)}));const x=["HOME","LANG","USER"],D=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],k=(0,p.lazy)((()=>{const e=(0,h.caseInsensitiveEnv)().pick(...P.isPosix?x:D),t=(0,h.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,M.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[f.PS_IS_CHILD_PROCESS]="1",t[f.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[f.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,M.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,a.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(n.default.env,(e=>E(e)||!(0,_.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:I({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function I({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...k(),...i?(0,g.childProcLocale)():{},...C(r),...e??{}});for(const e of(0,M.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,_.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>E(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return n}t.childEnv=I},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=r(i(31421)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),f=i(31586),h=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),S=i(22911),b=i(4867),P=i(73614),M=i(70025),_=i(57159),E=i(36868),T=i(66184),x=i(45643),D=i(95402),k=i(9727),C=(0,o.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function O(e){return(0,h.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,E.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,D.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,x.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",O(e)),!0;{D.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,D.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,x.waitForPidExit)(i,5e3)}function F(e,i,r,n=0){const o=new Date,a=[];return(0,v.niceable)(i,r)&&a.push((0,P.setUnrefTimeout)((()=>{(0,f.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,f.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,f.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,f.gt0)(e.pid))return(0,D.addPid)({pid:e.pid,cmd:i,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,r){const s=(0,k.spawnOptions)(r);return(0,T.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(n.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const r=i.quiet??!1,n=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,h.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,h=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new S.Deferred(h);o.on("error",(e=>g.push(e))),o.on("exit",(e=>{(0,f.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,f.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,E.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>g.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>g.push(e))),o.stderr?.on("data",(e=>p.push(e))),o.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:h}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:h,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const T=p.join("");(0,l.notBlank)(T)&&g.push(new Error(T)),!r&&(0,a.isNotEmpty)(g)&&C().warn(h+" resulted in errors:",g);const x=i.isIgnorableError??M.isIgnorableError,D=g.filter((e=>!0!==x(e)));if(D.length>0)throw 1===D.length?D[0]:new _.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!s&&0!==y.value)throw new Error(h+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:T}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,D.killPid)(o.pid,!0),e}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const s=(0,k.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(n.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const r=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},86335:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(77598),u=a(i(1708)),c=i(19851),d=i(40958),f=i(22573),h=i(50268),m=i(68708),p=i(5670),g=i(50989),y=i(12168),v=i(59455),w=i(41583),S=i(54993),b=i(80875),P=i(50213),M=i(81168),_=i(27395),E=i(25764),T=i(59958),x=i(70025),D=i(83278),k=i(85021),C=i(29325),O=i(43334),I=i(28874),F=i(84777),L=i(55534),A=i(85100),R=i(34330),N=(0,c.lazy)((()=>(0,P.mkLogger)("child.ChildService")));async function j(e){const t=(0,M.ensureSuffix)(e,".js"),i=D.BaseFile.projectRoot(),r=D.BaseFile.for(u.default.cwd()),n=(0,C.isPacked)()?[i.join("bin",t),O.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];(0,C.isPacked)()||(O.isElectron?(n.push(r.join("dist","app",t)),n.push(i.join("src","desktop","dist","library",t))):n.push(i.join("src","library","dist","library",t)));for(const e of n)if(null!=e&&!0===await e.isNonEmptyFile((0,C.isPacked)()?y.KB:128))return N().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:C.isPacked,paths:n.map(S.toS)}});return N().throw("Failed to find path to "+e,{paths:n,fatal:!0})}t.pathToService=j,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=(0,g.strEnum)(...p.ServiceNames.pick("web","sync"));class B{static async mk_(e,t={}){const i=t.pathToService??await j(e);if((0,f.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,v.toA)(t.nodeArgs),new B(e,i,t)}constructor(e,t,i){var a,l;r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,A.serviceExitTimeoutMs)(e),this.logger=(0,P.mkLogger)(this.name);const c=[...(0,v.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&c.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale","forWorker"),this.spawnOpts.forceCLocale=!1,(l=(a=this.spawnOpts).env??(a.env={}))[T.UV_THREADPOOL_SIZE]??(l[T.UV_THREADPOOL_SIZE]=(0,S.toS)(("web"===e?I.Settings.webUvThreads:I.Settings.syncUvThreads).valueOrDefault)),this.wc=new R.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&await(this.opts.onPreRestart?.()),this.restartCount++,(0,F.spawn)(u.default.execPath,c,-1,this.spawnOpts)),endableRank:E.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:o(this,r,"m",s).bind(this),onStderr:o(this,r,"m",n).bind(this),onError:this.opts.onError??(e=>!1===(0,x.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:L.ServiceExitCommand,...i}),(0,_.addEndable)(E.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(k.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(L.ServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,M.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,w.toErr)(i)),this.write(e,t-1)}}}t.ChildService=B,r=new WeakSet,n=function(e){const t=(0,b.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},s=function(e){if(!(0,f.blank)(e))try{const t=(0,b.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,h.isHealthCheckSummary)(t)){const e="failed"===t.state||"error"===t.level;this.logger.log(e?"error":"info",".onStdout(): health check summary",t),e&&this.wc.onError(this.name+".onStdout()",t,e)}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),n=i(41400),s=i(19851),o=i(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},85100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(23560),n=i(28874),s=i(45255);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?n.Settings.syncExitTimeoutMs.valueOrDefault:s.ShortCommandTimeoutMs}},34330:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),f=i(19851),h=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),S=i(25764),b=i(99331),P=i(42638),M=i(38835),_=i(8769),E=i(57159),T=i(66003),x=i(50213),D=i(45643),k=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new O({name:(0,h.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,f.lazy)((()=>(0,x.mkLogger)("WatchedChild("+(0,h.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),n.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,n,"f")||o||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,r,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,n,"f")}async end(){return c(this,n,!0,"f"),u(this,r,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,n,"f")}),!u(this,n,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",s).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=O,n=new WeakMap,r=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,n,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",o).call(this,e)},o=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",s).call(this),!this._stopped&&!u(this,n,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,n,"f")}),this._stopped||u(this,n,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,T.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,n,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(53916)),a=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),f=i(4001),h=i(95696);function m(e){return(0,f.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,a.toNativePath_)(e);const i=h.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),n=i.sibling(r);if(n.isSelfOrDescendantOf((0,l.examples)()))return o.join("$examples",n.posixPathFrom((0,l.examples)()));const s=(0,d.originalsDir)();if(n.isSelfOrDescendantOf(s))return o.join("$library",n.posixPathFrom(s));const f=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=f?o.join("$library",n.posixPathFrom(f)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const s=i(6858),o=i(1708),a=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),f=i(43334),h=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return n(this,r,"f").push(...e),this}async parse(e=o.argv,t){let i=(0,m.addHelpFooter)(new s.Command).description((0,m.cliWrap)(h.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of n(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":a.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,o.exit)(0)})),i.parse(e,t??{from:f.isMainElectron?"electron":"node"});const d=i.opts();for(const e of n(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),n=i(31586),s=i(51926),o=i(17344),a=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,n.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const n=r(i(1708)),s=i(22573),o=i(38639);t.isDaemon=function(e){return(0,o.isTrue)(n.default.env.__is_daemon)||(0,o.isTrue)(e?.daemon)||!(0,s.blank)(e?.pidfile)}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),n=i(40958),s=i(55835),o=i(31586),a=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,o.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},43380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(28874),n=i(2858),s=i(22573),o=i(38639),a=i(46292);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,o.isTrue)(e.writeSettings)){const e=await(0,n.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,a.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,s.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,n.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),n=i(19851),s=i(22573),o=i(42659),a=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),f=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function h(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=h,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?h(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),n=i(19851),s=i(55835),o=i(31586),a=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,n.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),f=["year","month","day","hour","minute","second","millisecond"];class h{static fromISO(e,t){const i=d().exec((0,a.toS)(e).trim()),r=i?.groups;return null==r?void 0:h.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,o.toInt)(r.index),(0,o.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,o.clamp)(1,1e3,(0,o.toInt)(r,{defaultValue:1})),i=(0,o.clamp)(0,r-1,(0,o.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const n=e.toMillis(),s=(t.toMillis()-n)/(r+1)*(i+1),a=e.plus({milliseconds:s});return null==a?void 0:new h(e,a,t,i,r)}constructor(e,t,i,r=0,n=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=n,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=f.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new h(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=h},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),n=i(51168),s=i(19851),o=i(76790),a=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),f=i(51926),h=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),v=i(21330),w=i(928),S=i(54261),b=i(73389),P=i(51275),M=(0,s.lazy)((()=>(0,h.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function T(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function x(e){try{if(null==e||(0,f.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?n.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),r=T(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[n,s]=(0,o.sortBy)([k(e,i),k(t,r)],(e=>e?.start));return null!=n&&null!=s&&null!=n&&null!=s&&(n.start===s.start||n.end>=Math.min(s.start,s.end))}function O(e,t){return(0,a.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=T,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?n.DateTime.fromObject(e):x(e)},t.datedToDateTime=x,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(O(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=D(e)),r??(r=D(t)),C(e,t,i,r))return!0;const n=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==n&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=n&&(t=(0,v.setZone)(t,n)??t),C(e,t,i,r)},t.isoToDated=O,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof n.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),n=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,n.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),n=i(31586),s=i(54557),o=i(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),n=i(40958),s=i(22573),o=i(42659),a=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const f=(0,n.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),h=(0,a.lt0)(f[0])?[f[0],...f.slice(1).map((e=>-e))]:f;return(0,c.sum)(h)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),n=i(51168),s=i(19851),o=i(22573),a=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),f=i(68852),h=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:n,month:s,day:o,hour:c,minute:f,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==n||null==s||null==o)return;if(!h.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==f))return;const g=(0,a.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return b({year:n,month:s,day:o,hour:c??0,minute:f??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=n.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,o.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,o.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,o.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,f.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,f.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,a.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),n=i(22573),s=i(42659),o=i(49769),a=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),f=i(66649),h=i(98725),m=i(88600);t.recent=function(e,t=5*s.secondMs){return(0,c.isRecentMs)((0,f.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,n.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,n.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,o.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,f.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,a.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,h.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const s=i(77988),o=i(51168),a=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),f=i(31586),h=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),v=i(79842),w=i(66649),S=i(98247),b=i(98725),P=i(928),M=i(54261),_=i(73389),E=i(89724),T=i(17415),x=i(88600),D=i(51275);function k(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,x.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(b.ISO_YMD_RE.exec(e)?.groups??b.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,f.toGt0)(e?.year);if(null==e||null==t||tk(e))).join("-")}toLocal(){return(0,E.datedToLocal)(this)}toDateTime(){return o.DateTime.fromObject((0,h.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,h.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,h.pick)(e.plus({month:1}),"year","month"):(0,h.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function O(e,t){if(e instanceof s.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,M.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,T.zoneToTzOffsetMinutes)((0,w.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(n=>(0,d.map)((0,P.getDay)(e),(s=>(0,d.map)((0,P.getHour)(e),(o=>(0,S.dateObjectToExifDateTime)({year:r,month:n,day:s,hour:o,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,f.round)(e/15),n=Math.abs(r),s=Math.floor(n/60),o=Math.floor(Math.abs(n%60));return`${t?"UTC":""}${i}${k(s)}:${k(o)}`},t.toExifDateTime=O,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof s.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,M.hasTime)(e)||(i??(0,v.datedToPrecisionMs)(e))>=c.dayMs?L(e):O(e,(0,D.getZoneName)(e))?.toISOString({includeOffset:t})};const I="yyyy:MM:dd HH:mm:ss.SSS",F=I+"ZZ";function L(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>k(e))).join(t)}function A(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(w.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,f.isNumber)(t)?o.DateTime.fromMillis(t):(0,v.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,D.hasZone)(t)?F:I):void 0},t.datedToYMD=L,t.toFuzzyDate=A,t.sameDay=function(e,t){return(0,f.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,f.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,w.datedToMillis)(e)||null==(0,w.datedToMillis)(t))return;const[n,s]=[e,t].map((e=>(0,w.datedToMillis)(e))).sort(),a=(s-n)/(r+1),l=(0,D.getZoneName)(e),u=l===(0,D.getZoneName)(t)?l:void 0,c=o.DateTime.fromMillis(n+a*i,{zone:u});return[e,t].some((e=>!(0,M.hasTime)(e)))?A(c):c},t.setZone=function(e,t,i){const r={...(0,h.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,D.hasZone)(e)},n=(0,T.normalizeZone)(t);return null!=e&&null!=n&&(0,M.hasTime)(e)?e instanceof y.DateInterval?e.setZone(n,r):O(e)?.setZone(n,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,f.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,v.datedToDateTime)(e);if(null==i)return;const r=(0,D.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const a=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),f=i(49769),h=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),v=i(68852),w=i(4001),S=i(28874),b=i(24689),P=i(79842),M=i(66649),_=i(98247),E=i(21330),T=i(54261),x=i(73389),D=i(16400),k=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,h.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=F({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,x.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0};const O=new Map;function I(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const n=(0,f.getOrSet)(O,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:n?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function F({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:n=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:o}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>a.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(n(e))for(const e of s){const t=o(e);if(null!=t&&(0,k.isValidDate)(t))return t}}t.parseDated=F;class L{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>o(this,r,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>o(this,r,"m",s).call(this))),o(this,r,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=F({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,r=new WeakSet,n=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");o(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),o(this,r,"m",n).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),o(this,r,"m",n).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),o(this,r,"m",n).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),o(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),o(this,r,"m",n).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),o(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE]),o(this,r,"m",n).call(this,[e,t.seps,t.yearRE]),o(this,r,"m",n).call(this,[t.yearRE,t.seps,e]),o(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,h.toInt)(t.year),month:(0,h.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,h.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),n=i(31586),s=i(54261);function o(e){return e instanceof Date?e.getMinutes():e?.minute}function a(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=o,t.getSecond=a,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,n.gt0)(o(e))||(0,n.gt0)(a(e))||(0,n.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(a(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),n=i(31586),s=i(68708);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,n.gt0)(t.hour)||(0,n.gt0)(t.minute)||(0,n.gt0)(t.second)||(0,n.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),n=i(19851),s=i(42659),o=i(55835),a=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),f=i(74417),h=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,n.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,o.map)((0,c.isoToDated)(e),w)}function w(e){return(0,a.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,a.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},n=10*r(),s=r(),o=r(),l=(0,a.toGt0)(r()),u=(0,a.toGt0)(r()),c=(0,a.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:o,second:s,millisecond:n,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):h.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),n=i(76790),s=i(31586),o=i(9092),a=(0,r.lazy)((()=>{const e=new o.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(n=>{const s=r.format(new Date(2017,n));e.set(s,n+1),"short"===i&&"en-US"===t&&e.set(s+".",n+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:a().get(e)},t.monthNames=function(){return(0,n.sort)([...a().keys()])}},42499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(51168),n=i(19851),s=i(19043),o=i(28874);t.setupLuxon=(0,n.lazy)((async()=>{r.Settings.throwOnInvalid=!1,o.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,s.locale)()}))},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),n=i(51168),s=i(19851),o=i(22573),a=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),f=i(54993),h=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,h.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,a.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-±+−])/,T=/[-−]/,x=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:O((0,t.TimezoneOffsetRE)().exec(e))}function O(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,o.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=T.test((0,f.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,n=null==t?void 0:i*(60*t+r);return v(n)?n:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,x,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=O;const I=/\b(?(?:Etc\/)?GMT)\b/,F=(0,s.lazy)((()=>(0,m.concatRegexp)([I,E,D,m.RegExpOptional.from(k)])));function L(e){return O(F().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,o.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),n=i(19851),s=i(40958),o=i(22573),a=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),f=i(28874),h=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),v=(0,n.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),w=(0,n.lazy)((()=>(0,s.compact)(f.Settings.badDates.values.map((e=>(0,h.isoToDated)(e)))))),S=(0,n.lazy)((()=>(0,s.compact)(w().map((e=>(0,p.datedToISO)(e)))))),b=(0,n.lazy)((()=>(0,s.compact)(w().map((e=>(0,y.datedToLocal)(e)))))),P=(0,n.lazy)((()=>(0,s.compact)(w().map((e=>(0,m.datedToMillis)(e))))));function M(e){if(null==e)return!1;const t=E(e);return v().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return M(e)?e:void 0},t.isValidDate=M;const _=String(new Date("bad"));function E(e){try{if(!(0,h.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===_)return _;const t=(0,s.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const n=[];if((0,l.isNumber)(e)||n.push("year is not a number"),(0,l.lt)(e,f.Settings.minValidYear.valueOrDefault)&&n.push("year is less than "+f.Settings.minValidYear.key),(0,u.gt)(e,T())&&n.push("year is in the future"),null==t&&null!=i&&n.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&n.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&n.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const s=r.DateTime.fromObject({year:e,month:t,day:i});s.isValid||n.push(s.invalidExplanation??"not valid")}return(0,s.compact)(n)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=f.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+f.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):b().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):S().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,o.toNotBlank)((0,s.uniq)((0,s.compactBlanks)(t)).join("; "))}catch(t){return v().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=E;const T=(0,n.lazy)((()=>r.DateTime.now().plus({milliseconds:f.Settings.maxValidFutureMs.valueOrDefault}).year),a.dayMs);t.mapValidDate=function(e,t){return M(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==E({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),n=i(31586),s=i(24689),o=i(73389);t.hasZone=function(e){return null!=e&&!(0,n.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,o.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,o.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),n=i(7311);function s(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(n.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(76760)),a=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),f=i(97352),h=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),S=i(29882),b=i(45969),P=i(43334),M=i(28874),_=i(41692),E=i(32774),T=i(80612),x=i(32551),D=(0,d.lazy)((()=>(0,f.mapGte0)((0,h.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function C(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:E.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:E.DefaultDockerLibraryDir},...k()]);const e=(0,a.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,x.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,x.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,x.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,T.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,T.firstDir)({dirs:C(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),M.Settings.cacheDir.watchLater(I)}));function I(){M.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=M.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=I},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),n=i(45969),s=i(41692),o=i(32774),a=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},79960:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(19851),n=i(22573),s=i(50213),o=i(45255),a=i(84777),l=i(16287),u=i(57902),c=i(43334),d=(0,r.lazy)((()=>(0,s.mkLogger)("dir.DefaultApplePhotosLibrary"))),f=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,a.stdout_)("defaults",f,{timeoutMs:o.ShortCommandTimeoutMs});if((0,n.blank)(e))return void d().warn(`"defaults ${f.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),n=i(45969),s=i(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=r(i(76760)),s=i(40958),o=i(72993),a=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function f(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:f(),desc:"config"})},t.desktopConfigDirs=f},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),n=i(96706),s=i(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),n=i(40958),s=i(22573),o=i(66430);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),n=i(76760),s=i(1708),o=i(19851),a=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),n=i(49776),s=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,n.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),n=i(54993),s=i(29882),o=i(28874);function a(e){return(0,r.toNotBlank)((0,n.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),n=i(55835),s=i(37805),o=i(15056),a=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),f=i(28874),h=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,h.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,h.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,h.originalsDir)(e))}async function S(e){return y(w(e),!1)}function b(e){return u.PosixFile.forMaybe((0,h.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(f.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,n.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=r(i(76760)),s=i(19851),o=i(40958),a=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),f=i(45969),h=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function S(){return(0,f.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:h.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(44198),a=i(43334),l=i(24399),u=i(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),n=i(7282),s=i(29325),o=i(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,r.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),n=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=r(i(73024)),s=i(76760),o=r(i(1708)),a=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),f=i(7282),h=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),S=i(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,f.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),i={...o.default.env};for(const r of e)try{const e=(0,d.debom)(n.default.readFileSync((0,g.resolve)(r))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(s))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,h.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),n=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,r.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=r(i(1708)),s=i(19851),o=i(22573),a=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),f=i(34102),h=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=p,(0,l.later)((()=>{h.env.watchLater(p),(0,f.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,a.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),n=i(19851),s=i(40958),o=i(22573),a=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),f=i(89788),h=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),r=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),r-o.length,n)+o.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,h.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new f.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,o.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),n=i(26905),s=i(55835),o=i(54993),a=i(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,n.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),n=i(76790),s=i(50989),o=i(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},68301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(19851),n=i(42659),s=i(75240),o=i(55835),a=i(31586),l=i(68708),u=i(59455),c=i(54993),d=i(50213),f=i(45255),h=i(37628),m=i(99331),p=i(46292),g=i(38835),y=i(32144),v=i(29882),w=i(95696),S=i(55222),b=i(28874),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*n.secondMs)).join((0,h.shortStringSha)(e.message,8,S.GeoRadix)+".json")}async eventsFrom(e=new Date,t=n.dayMs){const i=e.getTime(),r=i-t,o=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,a.within)(r,o,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,s.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),n=b.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=n,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:n,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:f.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,o.map)((0,p.configDir)(),(e=>new _(w.PosixFile.for(e).join("events"))))))},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),n=i(38639),s=i(26905),o=i(54993),a=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function f(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function h(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,r.compact)(t).join("");return f(i)+h(i).join("")},t.stripErrorFlags=f,t.extractErrorFlags=h,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),n=i(31586),s=i(68708),o=i(7282),a=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),f=i(38835),h=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,h.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===i.fatal,c=!0===i.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const f=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===f?"error":"warn","onError()",{event:f,error:i}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+f.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),n=i(22573),s=i(38639),o=i(26905),a=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),f=i(81168),h=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,n.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,n.firstNotBlank)((0,f.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,f.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,h.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,n.blank)(r)||(i=(0,f.dedupeNeedle)(i,r,"file")),(0,h.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,f.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(49769),a=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,r,"f").get(e);return null!=o&&(o.resolve(t),s(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,n=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),n=i(19851),s=i(15197);t.ee=(0,n.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=r(i(73024)),s=r(i(1708)),o=i(19851),a=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),f=(0,o.lazy)((()=>s.default.getgroups?.()));function h(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?h(t,n.default.constants.R_OK|n.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?h(t,n.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:f()??[],l=0===o,u=l||e.uid===o,h=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(h?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(h?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(h?8:0)|1)&e.mode))}t.canAccessSync=h,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=r(i(76760)),s=i(19851),o=i(81168),a=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),f=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,f.resolve)(...e)}};const h=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,f.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:h().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,f.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,o.equalsIgnoreCase)(e.basename,i.base))return n.default.join(r,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),n=i(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=h(i(76760)),v=h(i(1708)),w=i(46466),S=h(i(57975)),b=h(i(38522)),P=i(19851),M=i(40958),_=i(5233),E=i(22573),T=i(42659),x=i(50357),D=i(96249),k=i(98553),C=i(55835),O=i(31586),I=i(68708),F=i(97790),L=i(39926),A=i(51926),R=i(59455),N=i(54993),j=i(48884),B=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),H=i(76850),G=i(70025),q=i(34102),$=i(80875),J=i(50213),K=i(70417),Z=i(43334),Y=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),ne=i(89968),se=i(20197),oe=i(88561),ae=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),fe=i(65238),he=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),Se=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,r=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const n=(0,he.resolve)(i),s=new Pe(n,t);return be().set(i,s),be().set(n,s),s}static clear(e){(0,q.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,q.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),f(this,o,void 0,"f"),this}clearThisAndParent(){return(0,q.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",s).call(this)??await d(e=this.clearThisAndParent(),r,"m",s).call(e)}async children_(e){const t=await(0,fe.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,n,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,x.eql)(["."],e)||e.every(E.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&f(this,o,void 0,"f"),f(this,o,d(this,o,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&f(this,o,void 0,"f"),f(this,o,d(this,o,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,T.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>=(0,T.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>(0,T.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*T.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,H.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:T.secondMs,errorIsRetriable:G.isRetriableError})}async gunzip(){return d(this,r,"m",a).call(this,(0,Y.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,r,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,r,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,A.newlineRe)(),(r=>{const n=e.exec(r);null!=n&&(t.maybeResolve(n),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,O.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),Me)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,n)=>{try{const s=await e.f(r,(0,C.denull)(n));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,s=async function(){const e=(await(0,fe.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*T.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let Me=!0;t.useFsWatch=function(e){Me=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),n=i(88840),s=i(14036),o=i(29882);function a(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,o.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=a,t.isBrowserExtension=a(n.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=a(n.ExtTypes.Video),t.isAssetFileExtension=a(n.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),n=i(96249),s=i(51926),o=i(54993),a=i(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),n=i(19851),s=i(50213),o=i(37805),a=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const f=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function h(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return f().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return h((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=h,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=r(i(76760)),s=r(i(1708)),o=i(19851),a=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44652)),l=o(i(73024)),u=i(76760),c=i(57975),d=i(19851),f=i(59455),h=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),S=i(16287),b=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,h.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},n=await a.stat(t);return new _(i,new P(r,n))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,f.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,f.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=r(i(76760)),s=i(39926),o=i(29882),a=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(r.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},88561:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(40958),a=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),f=i(34102),h=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends h.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,f.ee)().on("fileChanged",(e=>s(this,r,"m",n).call(this,e))),(0,f.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),n=i(22573),s=i(45599),o=i(96249),a=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],f=(0,s.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),h=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=h.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(i)?void 0:f()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),n=i(17217),s=i(16287),o=i(68284);async function a(e){return(0,r.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),n=i(19851),s=i(22573),o=i(50213),a=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),f=i(95696),h=i(93854),m=i(16287),p=(0,n.lazy)((()=>(0,o.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,h.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const n=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),o=(0,l.normalizeExt)(f.PosixFile.for(e))??(0,c.mimetypeExt)(n);return(0,s.blank)(n)||(0,s.blank)(o)?void 0:{ext:o,mime:n}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new a.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),f=i(38836),h=i(43624);class m extends f.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,n.set(this,[]),s.set(this,void 0),o.set(this,void 0),l(this,o,(0,h.fileStatsSync)(e),"f"),l(this,s,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",a).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,n,"f").push(e)}close(){u(this,s,"f").close()}}t.FileWatcher=m,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(e){const t=await(0,h.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,o,"f"),t)){l(this,o,t,"f");for(const t of u(this,n,"f"))t(e,this.nativePath)}}},73209:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f,h,m,p,g,y,v,w,S=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const M=i(58587),_=P(i(44652)),E=i(87997),T=i(40958),x=i(17586),D=i(42659),k=i(50357),C=i(75240),O=i(55835),I=i(31586),F=i(30976),L=i(13538),A=i(54993),R=i(7282),N=i(68852),j=i(23560),B=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),H=i(55222),G=i(63870),q=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(q.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return b(this,n,Math.max(Date.now(),S(this,n,"f",s)+1),"f",s),(0,T.compactBlanks)([H.TokenRadix.encode(S(this,n,"f",s)),j.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return n.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,I.toInt)(J.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return S(this,n,"f",a).find((t=>t.opts.file===e.file))??new n(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>S(this,r,"m",w).call(this)),e.endableRank??B.EndableRanks.postdb,(0,G.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=n,n,(i=S(t,n,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),f.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(S(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,q.fsLockFileBasename)(n.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await S(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,q.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+S(this,l,"f")),this.staleMs=(0,I.round)(this.opts.timeoutMs/(0,F.randomFloat)(2,4)),S(n,n,"f",a).push(this)}get acquired(){return S(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await S(this,r,"m",h).call(this,e)??S(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,x.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==S(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:D.secondMs);b(this,c,setInterval((()=>S(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=S(this,c,"f")&&(clearInterval(S(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(S(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),b(this,u,!1,"f"),(0,O.map)(S(this,d,"f"),(e=>(0,E.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?S(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>S(this,r,"m",v).call(this)),(0,I.toGt0)(this.staleMs)??D.secondMs),"f"),S(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(S(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,L.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,n=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,r=new WeakSet,h=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,I.gt0)(this.staleMs)&&Date.now()>S(this,f,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await S(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,f,Date.now(),"f");const e=[],t=await S(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,I.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,q.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;n.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=n.pidFromBasename(i[0]);if((0,I.gt0)(t)&&!(0,M.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),S(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await S(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await S(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,T.filterInPlace)(S(n,n,"f",a),(e=>S(e,l,"f")!==S(this,l,"f")))},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),n=i(51926),s=i(54993),o=i(17217);function a(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,n.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,n.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&a((0,o.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),n=i(55835),s=i(31586),o=i(51926),a=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function f(e,t={aggressive:!0}){return h((0,r.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function h(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,s.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:h(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const n=(0,u.parsePosixPath)(i),s=f(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=f,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=f(t),r=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,n.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const n=r(i(73024)),s=i(57075),o=i(46466),a=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends s.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,a.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,o.pipeline)([n.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=r(i(44652)),s=r(i(73024)),o=i(46466),a=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=r(i(77598)),s=r(i(73024)),o=i(46466),a=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),f=i(73913),h=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,a.lazy)((()=>(0,h.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=S().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),S().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=n.default.createHash(i);return await(0,o.pipeline)([e,...t,r]),r.digest().subarray(0,f.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(f.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),n=i(42659),s=i(55835),o=i(31586),a=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),f=i(63870),h=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*n.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,f.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*n.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),n=i(54993),s=i(7282),o=i(43334),a=i(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,f=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function h(e){return null!=f?.exec((0,n.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":h(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=h,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),n=i(55835),s=i(57159),o=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,n.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,o.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new s.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),n=i(51926),s=i(54993);class o extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=r.pop();this._prior=o??"";let a=!1;for(const e of r)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=r(i(76760)),s=i(17217),o=i(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const o=s(i(76760)),a=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),f=i(68852),h=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),S=i(88561),b=i(65238),P=i(16287),M=(0,a.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),_="NoMedia",E=new RegExp("(?:^|["+(0,l.uniq)([(0,f.escapeRegExp)(o.default.sep),"/"]).join("")+"])\\.?"+_+"$","im"),T=Object.freeze(["."+_,_]),x=Object.freeze((0,u.flatten)(T.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function D(e){return null!=E.exec(e)}t.isNoMediaName=D;const k=(0,a.lazy)((()=>new S.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=v.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return D(i.base)||await(0,w.isCachedirTagFile)(i)?k().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await k().getOrSetAsync(i.nativePath,(()=>O(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function O(e){if(D(e.base))return k().set(e.parent().nativePath,e.nativePath),M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,b.readdirCached)(e.nativePath);if(null!=t)return F(e.nativePath,t);const i=new h.Abortable,r=await Promise.race([I(e.nativePath,i),(0,b.readdir)(e.nativePath).then((t=>F(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,w.isCachedirTagDirectory)(e)?M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function I(e,t){for(const i of g.isCaseSensitiveFs?x:T){if(!0===t?.aborted)return null;const r=o.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return M().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function F(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(D(r.basename))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,o.join)(e,r.basename))});if(r.basename===w.CACHEDIR_TAG){const t=(0,o.join)(e,r.basename);if(await(0,w.isCachedirTagFile)(t))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=O,t._dirHasNoMediaChild=I},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=r(i(44652)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),f=i(51926),h=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),S=i(17217),b=i(16287),P=i(66430),M=i(5545);function _(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return C(e).some(_)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return T((0,v.posix2native)(e))},t.extname=function(e){return T(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const E=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function T(e){const t=E.exec(e)?.groups,i=t?.ext2??"",r=s.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function x(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,f.splitLast)(t.dir,s.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),i=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const r=e(t),n=e(i);return null!=r&&null!=n&&(y.isLinux?r===n:(0,p.equalsIgnoreCase)(r,n))}function C(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function I({p:e,maxLength:t}){const i=(0,S.toNativePath_)(e);if(i.length<=t)return i;const r=C(e),n=[],s=[r.pop()];for(;r.length>0;)if(n.length=t){r.unshift(n.pop());break}}else if(s.unshift(r.pop()),L([...n,...s]).length>=t){r.push(s.shift());break}return r.length>0&&n.push("…"),L([...n,...s])}function F(e){return e.startsWith("\\\\")}function L(e){return(0,f.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=T,t.parentBasename=x,t.grandParentBasename=function(e){return x(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return k(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(S.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,S.toNativePath_)(e),r=(0,S.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,v.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=I,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const n=[];for(const r of e.slice(0,i))n.push(I({p:r,maxLength:t}));return n.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=T(e);return`${i.base}${t}${i.ext}`},t.isUNC=F,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(F(e)||null!=e.match(M.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=L,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:L(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=r(i(76760)),s=i(19851),o=i(40958),a=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),f=i(54993),h=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),S=i(16287),b=(0,s.lazy)((()=>(0,h.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(i,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,f.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=n.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,n,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),f=c(i(73024)),h=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),S=i(22573),b=i(42659),P=i(26905),M=i(75240),_=i(55835),E=i(31586),T=i(68708),x=i(13538),D=i(89937),k=i(12168),C=i(54993),O=i(48884),I=i(50213),F=i(45255),L=i(81168),A=i(56519),R=i(56038),N=i(31562),j=i(84777),B=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),H=i(43334),G=i(33847),q=i(24399),$=i(28874),J=i(79915),K=i(45200),Z=i(34238),Y=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),ne=i(73209),se=i(48313),oe=i(29882),ae=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),fe=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class he extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return he.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?he.for(e):void 0}static for(e,t){if(e instanceof he)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=fe().get(e);if(null!=t)return t}const i=(0,ae.toNativePath_)(e),r=new he(i,t);return(0,L.isString)(e)&&fe().set(e,r),fe().set(i,r),r}static forPosix(e){return he.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>he.for(e)))}for(e,t){return he.for(e,t)}forDirectoryEntry(e){return he.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,oe.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,oe.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?he.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>he.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,T.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:n,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:o,minSizeBytes:i,timeoutMs:n,dirty:l})}return a&&r?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*n,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:n,dirty:s=!1}){return await this.parent().mkdirp_(),(0,ne.withLock_)({file:this,skipFsLock:r,timeoutMs:n,dirty:s},(async()=>{const r=this.wip();try{await r.unlink("trace");const s=await(0,x.thenOrTimeoutError)(e(r),n);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",n).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,f.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,oe.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,oe.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=he,r=new WeakSet,n=async function(e){let t,i=e;const r=e.wip();try{const n=await this.stat_();if(null==n)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(n.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await h.default.copyFile(this.nativePath,r.nativePath,f.default.constants.COPYFILE_FICLONE),n.size>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},n.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,E.approximates)(n.size,await r.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:n.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:n.birthtimeMs,mtimeMs:n.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,n.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${n.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),n=r?.size;return null==r||null==n?this.pflog().throw("Can't copy missing files"):(n>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},n,(()=>e.clear().size()))),H.isWin?await q.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,q.pwshQuote)(this.nativePath)} -Destination ${(0,q.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=r(i(76760)),s=i(22573),o=i(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const i=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",r=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=r(i(76760)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),f=i(43334),h=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),f.isElectron&&t.push(n.default.join((0,p.execDir)(),"resources"),n.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,p.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,h.hasChildrenSync)(i,e))return i;for(const t of(0,h.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,h.hasChildrenSync)(t,e))return t;const r=n.default.join(i,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!f.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),n=i(19851),s=i(31586),o=i(50213),a=i(57902),l=i(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),n=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const n=i??(await(0,r.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await(0,r.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),n=i(84542);t.readLines_=async function(e){return(0,n.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class n extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=r(i(51455)),s=i(76760),o=i(19851),a=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),f=i(13538),h=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),S=i(88561),b=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function M(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=M;const _=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function E(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function T(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=x(e),n=await(0,f.thenOrTimeout)(r,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===h.Timeout&&(0,g.onTimeout)({soft:!1}),n!==h.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=E,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),M()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?M():E(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){E(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await T(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?T(e):x(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=T,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=x},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=i(73024),s=r(i(76760)),o=i(40958),a=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),f=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),h=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=s.default.resolve(t,...e);if((0,n.existsSync)(i))return i}f().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(h).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),n=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=r(i(73024)),s=r(i(76760)),o=i(22573),a=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),f=i(14427);function h(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof n.default.Dirent?e.name:h(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=h,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return h(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(h(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=h.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],n=t[i],s=(0,u.diff)(b(r),b(n));if(null==s||s>1)return"unmatched "+i+": "+r+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=h.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??h.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=h.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=h.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=h.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=r(i(73024)),s=i(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const i=o(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=o(e);return t.emptyIsNew?null==i:a(i)},t.isNonEmptyFileSync=function(e,t=0){const i=o(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),n=i(56409);t.onDataChunked=function(e,t,i){const r=new s(t,i,!0);return r.read(e),r.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=r(i(57075)),s=i(41400),o=i(55835),a=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends n.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=r(i(73024)),s=i(76760),o=i(22573),a=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f,h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),v=i(19851),w=i(40958),S=i(22573),b=i(42659),P=i(98553),M=i(31586),_=i(68708),E=i(50989),T=i(51926),x=i(85556),D=i(54993),k=i(89788),C=i(23467),O=i(7282),I=i(23560),F=i(77377),L=i(71567),A=i(73568),R=i(25764),N=i(38836),j=i(99331),B=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),H=i(5012),G=i(32144),q=i(95696),$=i(36868),J=i(57902),K=i(28874),Z=i(84542),Y=i(73428);t.AssetFileSyncStates=(0,E.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,E.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,F.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,E.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,E.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const X={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,_.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??q.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,E.strEnum)(...(0,_.keys)(new class{constructor(e,t,i,r,n,s,o,a,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=n,this.elapsedMs=s,this.details=o,this.url=a,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,v.lazy)((()=>(0,Y.writeTextfile_)(re().nativePath,(0,T.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(X)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=b.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,G.isCsvExt)(e)&&(0,M.gte)(e.mtimeMs(),t)))},t.syncReport=(0,v.lazy)((()=>new ne));class ne extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>h(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),n.set(this,void 0),s.set(this,void 0),o.set(this,void 0),a.set(this,0),l.set(this,0),this.outputFiles=new k.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return h(this,n,"f")?.nativePath}get rowCount(){return h(this,l,"f")}onProgress(e){if(null==e||(0,S.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,H.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,D.toS)(e.path),state:e.state,details:(0,D.toS)(e.details).trim().replace(/\r?\n/g,"; ")},n={ts:t,at:new Date(t).toISOString(),...i,...(0,_.pick)(e,"from","elapsedMs","url")};(0,_.isEmptyObj)(e.meta)||(n.meta=(0,P.stringify)(e.meta)),(0,O.isTest)()&&process.stdout.write((0,P.stringify)(e)+Z.Newline),h(this,r,"m",u).call(this,n)}}maybeSystemData(e){(0,I.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const n=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const s=await r(),o=s.state??(null!=s.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return o===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:s}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-n,...s,state:o}),s}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,j.ending)()||r instanceof A.AbortError?t.SyncFileStates.canceled:r instanceof x.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,j.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-n}),r}}get output(){return h(this,s,"f")??h(this,r,"m",f).call(this)}async flushClose(){return h(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=h(this,s,"f");return m(this,s,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:h(this,n,"f")}}t.SyncReport=ne,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=h(this,o,"f");if(m(this,o,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,a,(t=h(this,a,"f"),t++,t),"f");null!=i&&(0===h(this,a,"f")?h(this,r,"m",c).call(this,i):(h(this,r,"m",c).call(this,{...i,details:(0,w.compactBlanks)([i.details,`(repeated ${h(this,a,"f")+1} times)`]).join(" ")}),m(this,a,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Z.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=h(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:h(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},f=function(){return m(this,n,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,B.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(h(this,n,"f").nativePath),this.logger.info("Opening new report: "+h(this,n,"f")),(0,O.isTest)()&&(0,L.stdoutWrite)({syncReport:h(this,n,"f").nativePath},!1),m(this,s,(0,g.createWriteStream)(h(this,n,"f").nativePath),"f"),h(this,s,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Z.Newline),h(this,s,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const n=r(i(48161)),s=i(19851),o=i(55835),a=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),f=i(8103),h=i(43899);function m(){return(0,o.map)(h.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,o.map)(m(),(e=>e.join(c.platformName+"-"+n.default.arch())))}async function g(e){if(c.isWin&&(e=(0,a.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,f.pathIfExists)(m()?.join("bin",e))),(()=>(0,f.pathIfExists)(m()?.join(e))),(()=>(0,f.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,f.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=r(i(44652)),s=i(19851),o=i(22573),a=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),f=i(17217),h=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const r=(0,f.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,f.dirname)(t.file));const a=(0,s.lazy)((()=>(0,h.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),n=i(41400),s=i(55835),o=i(92782),a=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),f=i(87128),h=i(95696);function m(){return(0,o.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends f.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:a.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,s.map)(h.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,s.map)((0,l.configDir)(),(e=>new p(h.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,n.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const o=s(i(51455)),a=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,a.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await o.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=r(i(76760)),s=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??n.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),n=i(45255),s=i(17217);t.WipTimeoutMs=n.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const o=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(o,"")},t.isWip=function(e){return o.test((0,s.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),n=i(22911);class s extends r.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=r(i(44652)),s=r(i(76760)),o=i(51926),a=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function f(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=f,t.writeTextSync_=function(e,...t){return f(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=r(i(73024)),s=i(76760),o=i(46466),a=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),f=i(50213),h=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,f.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const r=[],s=[n.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>r.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(r))throw new h.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},19652:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const o=i(51455),a=s(i(22915)),l=i(40958),u=i(82950),c=i(22573),d=i(45599),f=i(12168),h=i(50213),m=i(79960),p=i(32551),g=i(98314),y=(0,d.defer)((()=>(0,h.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,p.homeDir)(),a.getHomeFolder(),a.getPicturesFolder(),a.getVideosFolder(),a.getDesktopFolder(),await(0,m.defaultApplePhotosLibrary)()]).sort(),t=new Map,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,o.readdir)(e,{withFileTypes:!0})}catch(i){if(["ENOTDIR","ENOENT"].includes(i?.code))continue;t.set(e,i)}const r=0===t.size?{level:"ok",msg:["Default media directories are OK","The following directories are readable:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Error reading "+(0,f.plur)(t.size,"media directory")+":",(0,u.li)([...t.entries()].map((([e,t])=>(0,u.tt)(e)+":"+(0,g.errorToS)(t,{maxLen:80}))))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},87408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(63870),n=i(18454),s=i(89035),o=i(82638);t.getStatusSummary=async function(e={}){return(0,o.summarizeHealthChecks)({healthChecks:[...n.HealthCheck.allCritical(),(0,s.memoryHealthCheck)()],errors:n.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},18454:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f,h,m,p,g,y,v,w,S,b,P,M=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},_=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const E=i(19851),T=i(40958),x=i(76790),D=i(22573),k=i(41400),C=i(50357),O=i(26905),I=i(50268),F=i(55835),L=i(68708),A=i(30976),R=i(51926),N=i(13538),j=i(42279),B=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),H=i(50213),G=i(69591),q=i(22911),$=i(99331),J=i(5916),K=i(42638),Z=i(77740),Y=i(98314),X=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),ne=i(21525),se=i(82638),oe=(0,E.lazy)((()=>(0,H.mkLogger)("health.HealthCheck")));class ae{static traceLater_(e,t){const i=new q.Deferred(e);i.catch((t=>{M(this,n,"f",l).push(e+": failed: "+(0,Y.errorToS)(t)),this.onResultChange()})),M(this,n,"m",a).call(this).push(i);try{return i.observe((0,j.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return M(this,n,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){M(this,n,"f",l).push((0,R.isString)(e)?e:(0,Y.errorToS)(e)),this.onResultChange()}static lastErrors(){return M(this,n,"f",l).toA()}static addLoadingMsg(e){M(this,n,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,T.compact)((0,B.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return oe().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:M(this,n,"f",f).entriesByCountDesc()}),(0,F.map)((0,V.leastBy)(e,(e=>[M(this,n,"f",f).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=M(this,n,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,F.map)(e,(e=>M(this,n,"f",f).incr(e.msg))),oe().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,n.reset()}static findById(e){return M(this,n,"f",h).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,I.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=M(this,n,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=n.summary();if(e.pendingCount>0){const t=await Promise.all(n.testResultsCritical());e=n.summaryFromResults(t),oe().info("awaitSettled(): summary result",{summary:e,results:t})}return oe().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){n.summary.unset()}static reset(){if((0,$.ending)())oe().warn("Rejecting reset() when ending()",(0,O.shortStack)());else{this.onResultChange(),M(this,n,"f",l).clear(),M(this,n,"f",d).clear(),M(this,n,"f",f).clear(),M(this,n,"f",c).clear(),this.summary.clear(),_(this,n,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new n(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return M(this,n,"f",h).push(i),this.all.unset(),i}constructor(e,t,i,s,a,l,u,c,d,f,h,m,b,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=s,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=f,this.errorLinks=h,this.onReset=m,this.ttlMs=b,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),w.set(this,(0,E.lazy)((async()=>{await M(this,p,"f").prior(),(0,C.eql)(M(this,g,"f"),M(this,r,"m",v).call(this))||(this.onReset?.(),await this.refresh(),M(this,w,"f").unset())}))),this.refresh=(0,E.lazy)((()=>new q.Deferred("refresh").observe((async()=>{await M(this,p,"f").prior();const e=M(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,H.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[I.HealthCheckSections.ordinal(this.section),l??999,this.id],_(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>M(n,n,"f",o).enqueue({name:this.id,l:()=>M(this,r,"m",S).call(this,a)}),ttlMs:b}),"f"),this.isCritical&&M(this,p,"f").watchLater({onChange:n.onCriticalResult,onError:n.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>M(this,w,"f").call(this)))}isStale(){return M(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return M(this,p,"f").settledCount()}reset(){return M(this,p,"f").unset(),this.onReset?.(),_(this,g,{starting:!0},"f"),this}setTTL(e){M(this,p,"f").setTTL(e)}result(){return M(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return M(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return M(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??M(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,T.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,T.isNotEmpty)(i)&&(r.links=(0,T.uniqBy)(i)),(0,T.isNotEmpty)(t)&&(r.buttons=(0,T.uniqBy)(t)),r}t.HealthCheck=ae,n=ae,p=new WeakMap,g=new WeakMap,y=new WeakMap,w=new WeakMap,r=new WeakSet,a=function(){return(0,T.filterInPlace)(M(this,n,"f",s),(e=>!e.isPending)),M(this,n,"f",s)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=oe().tap({level:"warn",msg:"#summary()",result:(0,se.summarizeHealthChecksSync)({errors:M(this,n,"f",l),skipPending:M(this,n,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&_(this,n,!0,"f",u),i.state!==M(this,n,"f",c).last?.state&&M(this,n,"f",c).push({state:i.state,ts:Date.now()}),i},v=function(){return(0,L.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},S=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();oe().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,O.shortStack)()}),_(this,g,M(this,r,"m",v).call(this),"f");try{if((0,Z.getDevEnvFlag)("PS_SLOMO")&&await(0,k.delay)((0,A.randomInt)(.3*i,.7*i)),this.isSkipped())return M(this,r,"m",b).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const n=await(0,N.thenOrTimeoutError)(e(),i);return M(this,r,"m",b).call(this,{test:n,elapsedMs:Date.now()-t})}catch(e){return M(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},b=function({test:e,src:t="#toResult",elapsedMs:i}){var r,s;const o=n.normalizeMsg(e.msg),a=e.level??((0,z.toS)(o).toLowerCase().includes("error")?"error":(0,z.toS)(o).toLowerCase().includes("warn")?"warn":"ok"),l=(0,T.compact)([...e?.links??("ok"===a||"pending"===a?this.okLinks:"warn"===a?this.warnLinks:"no-library"===a?this.noLibraryLinks:"error"===a?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:a,msg:o,elapsedMs:i,...le(l)};return u.runCount=(_(this,y,(s=M(this,y,"f"),r=s++,s),"f"),r),(0,$.ending)()?u:this.logger.tap({level:ne.HealthCheckLevelToLogLevel[a],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const n=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,D.toNotBlank)((0,Y.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,X.isFatalError)(e)&&n.toLowerCase().includes("warn")?"warn":"error"),M(this,r,"m",b).call(this,{test:{msg:n,level:t},src:"#toErrorResult",elapsedMs:i})},s={value:[]},o={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},f={value:new U.CountingSet},h={value:[]},ae.all=(0,E.lazy)((()=>Object.freeze((0,x.sortBy)(M(n,n,"f",h),(e=>e.sortBy))))),ae.onCriticalResult=(0,G.debounce)((()=>{oe().info("onCriticalResult()",n.summary.refresh())}),250),ae.summary=(0,E.lazy)((()=>M(n,n,"m",m).call(n))),ae.resetDebounced=(0,G.debounce)((()=>n.reset()),50)},85021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),n=i(50268),s=i(459),o=i(23560),a=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,o.isPermaService)(t)&&(e===n.HealthCheckLevels.error||(0,o.isLibraryRequiredService)(t)&&e===n.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,a.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),n=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,n.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const n=r(i(48161)),s=i(19851),o=i(82950),a=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),f=i(23560),h=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,f.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,o.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return n.default.totalmem()h.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:h.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(h.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*h.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:h.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:h.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),a.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:a.minuteMs,later:async()=>g()})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),n=i(42659),s=i(45599),o=i(41400),a=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),f=i(23560),h=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const n=new Map;for(const e of t??[])n.set(e.id,e);if(null!=e)for await(const t of h.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))n.set(t.id,t);return[...n.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:f.serviceName.prior()??process.title}})));function S(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),s=i.length,o=i.map((e=>e.id)),c=t.length-s,d=0===s,f=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(f.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:o,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",f.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const n=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(n)){const e=t.filter((e=>!n.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+n.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:o,pendingCount:s,settledCount:c,linkIds:n.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,a.flatten)([...n,...e].map((e=>e.msg[0])))])},meta:{checks:n.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:o,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,n.fmtDateShort)(Date.now())]}})}(0,o.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),n=i(33374),s=i(31586),o=i(21605),a=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,n.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,a.toS)(e).split(/[x×]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:o.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),n=i(31586),s=i(50213),o=i(56519),a=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,n.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,o.thenMap)((0,a.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),n=i(41400),s=i(54993),o=i(19851),a=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),f=i(78330),h=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),v=(0,o.lazy)((()=>(0,a.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,o.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,f.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,h.hasPacman)()&&(i=(await(0,h.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,n.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),n=i(22573),s=i(42659),o=i(41400),a=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),f=i(28874),h=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,n.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:f.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,o.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,h.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(f.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:f.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(a.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),n=i(54993),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&s.test((0,n.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),n=i(19851),s=i(42659),o=i(59455),a=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),f=i(46199),h=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),S=(0,n.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,n.lazy)((()=>(b(),g.PosixFile.for((0,h.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,n.lazy)((()=>{h.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const n=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const s=n.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,f.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+r);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:o}),o}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const n=await P(e,t,i);return await n.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),n}catch(r){return S().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),n=i(33374),s=i(31586),o=i(34666),a=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,a.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,o.lt)((0,s.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,a.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,n.maybeDimSwap)(e.dimensions,e.rotation),(0,n.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),n=i(31586),s=i(80049),o=i(50213),a=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),f=(0,r.lazy)((()=>(0,o.mkLogger)("img.RawInfo"))),h=(0,r.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:a.ShortCommandTimeoutMs})));async function m(e){return h().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,s,o]=e.split("\t"),a=(0,n.toGt0)(s),l=(0,n.toGt0)(o);return null==a||null==l?f().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):f().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:a,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>h.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?h.prior()?.clear():h.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{f().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const n=r(i(9288)),s=i(19851),o=i(41400),a=i(50213),l=i(28874),u=i(15674),c=(0,s.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function d(e,t){return(0,n.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,s.lazy)((()=>{n.default.simd(l.Settings.enableSIMD.valueOrDefault),n.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),n.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,o.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),n=i(40958),s=i(41400),o=i(50213),a=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,o.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:f().test(t)||!d().test(t),meta:{err:e,allow:f().test(t),block:d().test(t),validationErrorAllowlist:f().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,a.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),f=(0,r.lazy)((()=>(0,a.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>f.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),n=i(40958),s=i(38639),o=i(42659),a=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),f=i(7282),h=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),v=i(56038),w=i(31562),S=i(98314),b=i(34102),P=i(88561),M=i(95696),_=i(17217),E=i(74128),T=i(31843),x=i(70417),D=i(33847),k=i(28874),C=i(94678),O=i(43207),I=i(47783),F=i(16170),L=i(95141),A=i(1078),R=i(63870),N=i(89782),j=i(13940),B=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,f.isProd)()&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,B.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,a.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,T.lerp2d)(e,{x:76800,y:k.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:k.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:o.minuteMs})));async function H(e){return await(0,t.isVideoSupported)()?M.PosixFile.for(await(0,t._extractVideoFrame_)((0,_.toNativePath_)(e))):void 0}async function G(e,t){const i=V("extractVideoFrame",e),r=M.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,B.isFFmpegSupported)())return i.throw("no video implementation");const n=await(0,j.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+n+")");const a=await r.mtimeMs();if(null==a)return i.throw("null mtime");const l=await(0,I.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,L.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,A.extractSizeInfoFromTags)(l,u)?.dimensions,d=await n.stat(),f=null==d?void 0:await(0,N.dimensions)(n);if(null!=d&&d.mtimeMs>a&&null!=f&&(null==c||f.height===c.height&&f.width===c.width))return i.debug("prior dest, "+n+" seems reasonable",{srcDim:c,destDim:f}),n.nativePath;const h=(0,O.extractDurationSec)(l),m=Math.min(h??0,k.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:h}),await n.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,B.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*o.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,I.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),n.nativePath}async function q(){return k.Settings.transcodeVideos.valueOrDefault&&await(0,B.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await q())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,I.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,F.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const s=(0,O.extractDurationSec)(i);if(!(0,c.gt)(s,k.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const o=(0,n.compactBlanks)([i.AudioFormat]),a=o.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,n.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(a&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:o,isSafeAudioCodec:a,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=H,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>G(e)}),t.__extractVideoFrame_=G,t.isVideoTranscodingSupported=q,t.needsTranscoding=$;const J=new g.TTLMap(o.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await q())return;const s=Date.now(),o=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return o.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void o.info("no transcoding needed");const a=await e.size();if(!(0,u.gt0)(a))return o.throw("source is empty or cannot read");const d=await(0,I.readTags)(e),f=(0,A.extractSizeInfoFromTags)(d),m=(0,O.extractDurationSec)(d);if(null==d||null==f||null==m)return o.throw("failed: missing video metadata",{sizeInfo:f,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return o.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,I.readRawTags)(t),r=await(0,I.readRawTags)(e),n=(0,O.extractDurationSec)(r),s=(0,O.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(n,s,1.5),meta:{srcDurationSec:n,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,i))return o.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),n=k.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,n))return r.throw("invalid width: "+s,{ignorable:!0});const o=i.ImageHeight;if(null!=o&&!(0,u.gte)(o,n))return r.throw("invalid height: "+o,{ignorable:!0});const a=(0,C.extractBitrateKbps)(i)??k.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,h.mapGt0)(s,(e=>(0,h.mapGt0)(o,(i=>(0,u.clamp)(0,a,(0,t.bitrateKps)(e*i)))))),c={width:s,height:o,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,v.time)("video.transcode:"+e,(async()=>{const t=K(a,g.videoBitrateKbps,m);return await i.applyWip_({fn_:a=>async function(a){o.info("starting...",{destWip:a});const f=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),h={src:e,dest:a,halt:r.halt,...g},m=k.Settings.transcodeMaxDim.valueOrDefault,p=(0,x.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?o.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(h.width=(0,u.roundEven)(e.width),h.height=(0,u.roundEven)(e.height),o.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await f.observe((0,B.ffmpegTranscode_)(h));0!==t.code&&o.throw((0,n.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,E.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-s})}catch(t){throw(0,E.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,S.errorToS)(t),elapsedMs:Date.now()-s}),o.error("transcode failed",{error:t}),t}}(a),skipFsLock:!1,timeoutMs:0}),i}))),o.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await H(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,B.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),n=i(22573),s=i(38639),o=i(42659),a=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),f=i(56519),h=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),v=i(84258),w=i(28874),S=i(76280),b=i(63870),P=i(19769),M=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function _(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:w.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=_;const E=/ffmpeg version n?(?\S+)/i,T=(0,u.lazy)((async()=>{const e=await _();if(null==e)return void M().info("failed to find ffmpeg in $PATH",{ffmpegPath:w.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,b.commandTimeoutMs)(),ignoreStderr:!0}),i=E.exec(t.result)?.[1];return M().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function x(){T.unset(),t.ffmpegVersionDescription.unset()}function D(e){const t=e?.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault;return(0,n.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function k(e){const t=[...w.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(w.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function O(e){const t=w.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,f.thenMapOr)(T(),(e=>"version "+e),(()=>"(not found)")))),(0,a.later)((()=>{(0,g.ee)().on("clearCache",x),(0,g.ee)().on("clearToolCache",x)})),t.ffmpegVersion_=async function(){return await T.prior()??T.refresh()},t.isFFmpegSupported=async function(){return null!=await T()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:o.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,h.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*o.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=k,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...k(t),...O(t),...D(t),"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){M().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,v.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return M().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return M().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await _(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),n=i(84777),s=i(8103),o=i(43334),a=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>o.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,n.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(a.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},42042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(22573),n=i(28874),s=i(81674);t.getEmail=async function(){const e=n.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,s.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),n=i(40958),s=i(42659),o=i(34666),a=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,a.intersection)(this._sids,this._l.uids),t=(0,n.uniq)(e.map(c.getScheme)),i=(0,n.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,o=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+s.dayMs,Date.now());return this.meta[(0,u.k)().o]=o,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,o&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,o.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),n=i(22573),s=i(38639),o=i(45599),a=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),f=i(79114),h=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),v=i(50213),w=i(56519),S=i(76596),b=i(46292),P=i(87290),M=i(77740),_=i(34102),E=i(83278),T=i(28874),x=i(37692),D=i(71706),k=i(83950),C=i(72042),O=i(33603),I=i(48132);t.k=(0,y.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const F=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function L(e){const i=await(0,C.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,S.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const n=(0,S.utcIsoToTs)(i[(0,t.k)().r]);if(null==n)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(n),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function A(e,i,r,s){try{return(0,n.blank)(e)||e===(0,t.k)().f?void 0:k.L.for({str:e,l:await L(e),sids:null!=s?s:await(0,O.sids)({timeoutMs:r}),src:i})}catch(i){return F().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await A((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,I.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function j(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=L,t.v=A,t.vok=async function(e,t,i){if((0,n.blank)(e))return;const r=await A(e,t,i);return(0,s.isTrue)(r?.ok)&&r instanceof k.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,O.sids)({timeoutMs:I.UserTimeoutMs}),i=(0,u.map)((0,b.configDir)(),(e=>E.BaseFile.for(e))),n=(s=(0,l.flatten)((await(0,w.someOrTimeout)([()=>function(e){return A(T.Settings[(0,t.k)().L].value,"Settings",I.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:I.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(s.filter((e=>null!=e&&((0,h.isError)(e)&&F().warn((0,t.k)().d+": ",e),null!=e&&!(0,h.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var s;return F().tap({msg:(0,t.k)().d+"()",result:n})})),(0,a.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset())),x.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=j,t.l=async function(){try{return await j()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await j()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),n=i(19851),s=i(22573),o=i(71706);t.l=(0,n.lazy)((()=>(0,o.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const n=(0,s.notBlankOr)(i.k,(0,t.l)().d),o=(0,t.l)().o.find((e=>e.k===n));if(null==o)throw new Error("Unknown key");return r.V2.verify(e,o)}},84194:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const s=i(40958),o=i(76790),a=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),f=i(19851),h=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,o.sortBy)((0,s.uniq)(e.filter(b)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,a.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,h.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const S=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function b(e){return null!=e&&null!=S().exec(e)}t.isValidUid=b,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,f.lazy)((()=>{const e=new d.CountingSet;for(const t of n(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return n(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||n(this,r,"f").has(t)||(n(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),n=i(22573),s=i(42659),o=i(45599),a=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),f=i(50213),h=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),v=i(45879),w=i(70854),S=i(57902),b=i(72308),P=i(43334),M=i(24399),_=i(7014),E=i(30933),T=i(71706),x=i(84194);t.k=(0,o.defer)((()=>(0,T.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const D=(0,o.defer)((()=>(0,f.mkLogger)((0,t.k)().n)));async function k(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=k;const C=(0,o.defer)((()=>(0,m.thenMap)(k(),(e=>(0,x.toUID)(x.S.lc,e.join(",")))))),O=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,S.LogLevels.trace))))).map(d.toS).filter((e=>(0,n.notBlank)(e)&&null==e.match(O)))}async function F(){return P.isLinux?(await I("lm")).map((e=>(0,x.toUID)(x.S.lm,e))):void 0}async function L(){return P.isLinux?(await I("lp")).map((e=>(0,x.toUID)(x.S.lp,e))):void 0}async function A(){return P.isLinux?(await I("lb")).map((e=>(0,x.toUID)(x.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*s.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,x.toUID)(e,t)))}catch(e){return void D().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function j(){return P.isWin?(0,x.toUID)(x.S.wm,await N()):void 0}t.win_machineGuid_=N;const B=(0,o.defer)((()=>(0,x.toUID)(x.S.cm,(0,E.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,x.toUID)(x.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,x.toUID)(x.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,x.toUID)(x.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,b.networkMacAddresses)().map((e=>(0,x.toUID)(x.S.nm,e)))}async function H(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,x.toUID)(x.S.vl,e.uuid)))}const G=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[B,C,R,V,W,z,F,L,A,j,U,H],r=(0,a.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)G.add(e);return D().tap({msg:"sids()",result:(0,x.sortUids)([...G,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,h.isTest)())for(const t of e)G.add(t)},t.clearSids=function(){(0,h.isTest)()&&G.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},34474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(40958),n=i(42659),s=i(41400),o=i(96249),a=i(68708),l=i(34666),u=i(20214),c=i(71371),d=i(50213),f=i(42638),h=i(31562),m=i(98314),p=i(89968),g=i(28874),y=i(4904),v=i(57902),w=i(89241),S=i(83954);function b(e=10*n.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=b,t.allRecentLogEntries=async function(e=50){(0,S.writeRecentLogEntries)();const t=(0,a.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-n.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(b(),(e=>(0,f.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const o=[],a=new w.LogReader(e,(e=>o.push(e)));for(await(0,h.untilTrue)((()=>a.ready()),{timeoutMs:10*n.secondMs});!a.complete()&&!a.hasErrors();){const e=a.shift();null==e?await(0,s.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(o)&&(p.warn("Read error(s) for "+e,o),o.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-n.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,o.flatten)((0,a.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),n=i(19851),s=i(40958),o=i(22573),a=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),f=i(66184),h=i(93475),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,h.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,f.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),n=i(23560),s=i(66184),o=i(72210);class a{log(e,t,i,r){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,r.lazy)((()=>new a))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),n=i(22573),s=i(26905),o=i(55835),a=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),f=i(76740),h=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new f.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,h.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),n=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof n.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),n=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new n.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(41400),a=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),f=i(23560),h=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,f.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,o.later)((()=>f.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,h.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(77030),o=i(19851),a=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),f=i(31586),h=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),S=(0,o.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,f.toInt)(t);return(0,a.blank)(e)||!(0,f.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),h.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const o=this.socket;null==o?n(this,r,"f").call(this):o.write(this.logFormatter.format(e,t,i,s)+b)}catch(r){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),n=i(42659),s=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),n=i(31586),s=i(51926),o=i(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),n=i(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),f=i(28874),h=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=f.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,n.set(this,[]),s.set(this,(0,l.lazy)((()=>{a(this,n,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=h.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:a(this,n,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>a(this,s,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=a(this,r,"m",o).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=a(this,r,"m",o).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap,s=new WeakMap,r=new WeakSet,o=function(e){if(null==e||0===a(this,n,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return a(this,n,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),n=i(50989),s=i(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),n=i(68708),s=i(20214),o=i(51926),a=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,f=4){if(null==i)return null;if(f<0)return"…";if((0,o.isString)(i)||Buffer.isBuffer(i))return(0,o.ellipsize)(i.toString(),256,32);if((0,a.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,f-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,f-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),f-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const a=(0,u.mapNullEntries)(i,((t,i)=>e(i,f-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(i),(0,n.keys)(a));return(0,r.isNotEmpty)(c)&&(a["…"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return i}},89241:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),f=i(38522),h=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),v=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),n.set(this,!1),s.set(this,!1),o.set(this,!1),this.from=(0,h.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,f.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,f.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,o,!0,"f")})),this.stream.on("data",c(this,r,"m",a).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,n,!0,"f")})),this.stream.on("end",(()=>{u(this,n,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,o,"f"),ended:c(this,n,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,o,"f")}get ended(){return c(this,n,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e){if(null===e)u(this,n,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),n=i(76760),s=i(1708),o=i(87997),a=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),f=i(34666),h=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),S=i(38836),b=i(99331),P=i(42638),M=i(76596),_=i(98314),E=i(89968),T=i(29882),x=i(28874),D=i(28981),k=i(20839),C=i(21727),O=i(66184),I=i(57902),F=i(72210),L=i(98192);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class R extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,x.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,T.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,F.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,F.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,n.join)(e,i))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,_.errorToS)(t))))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,h.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,T.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,_.errorToS)(e))))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,F.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,F.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,f.gte)(r,i))return;await(0,h.thenMap)((0,L.readLogEntries)(e,{start:r,end:i}),(e=>(0,F.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),n=i(82328),s=i(28981),o=i(20839),a=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const f=d(i(73024)),h=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),S=i(23560),b=i(81168),P=i(78406),M=i(25764),_=i(20197),E=i(14977),T=i(36868),x=i(28874),D=i(32105),k=i(20839),C=i(21727),O=i(66184),I=i(93475),F=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger,unref:!0,onEnd:()=>c(this,n,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const n={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(n.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,F.recentLogEntries)()),(0,F.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,n=new WeakMap,r=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,i);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,r,"m",o).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,h.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=f.default.createWriteStream(t).on("error",c(this,r,"m",a).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,T.endStream)(e.stream),x.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,r,"m",o).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),n=i(40958),s=i(55835),o=i(68708),a=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),n=i(84542),s=i(4001),o=i(13047),a=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),r=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,n.splitLines)(a)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),n=i(76790),s=i(68708),o=i(89788),a=i(57902);t.SentLogLevels=(0,r.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),n=i(41400),s=i(55835),o=i(37975),a=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),f=i(28874),h=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),S=i(24068),b=i(43705),P=i(51879);function M(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),_();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new b.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||f.Settings.logStdout.valueOrDefault||f.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,s.map)((0,y.logBroadcaster)(),(e=>i.push(e))),a.rootLoggers.set(i),f.Settings.tailLogs.valueOrDefault&&S.LogTail.instance()}function _(){const e=f.Settings.logColor.valueOrDefault;(0,o.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new h.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=M,t.setupLogFormatter=_,(0,n.later)((()=>{f.Settings.logStdout.watchLater(M),f.Settings.logDir.watchLater(M),f.Settings.tailLogs.watchLater(M),f.Settings.logColor.watchLater(_),f.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},83954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(89179);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},82647:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(57975),a=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),f=i(59455),h=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,h.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,f.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,f.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,r,"m",n).call(this,-1)}get p29(){return s(this,r,"m",n).call(this,-.5)}get p38(){return s(this,r,"m",n).call(this,-.25)}get p69(){return s(this,r,"m",n).call(this,.5)}get p84(){return s(this,r,"m",n).call(this,1)}get p98(){return s(this,r,"m",n).call(this,2)}get p99(){return s(this,r,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),n=i(55835),s=i(31586),o=i(30976),a=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,n.map2)(e,t,((e,t)=>(0,r.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):r[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let n=0;n(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function f(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=f(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=f,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function n(e,t,i=.5){return(1-i)*e+i*t}t.lerp=n,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,r.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return n(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),n=i(22573),s=i(55835),o=i(32639),a=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),n=this.normalizeToken(t);return r.length>=i&&r===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),n=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,n.toS)(e)}},17921:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),n=i(65713);function s(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,n.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),f=i(77377),h=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,r,"f")/(s(this,r,"f")+1)+e/(s(this,r,"f")+1),"f"),o(this,r,(t=s(this,r,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,u.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),n=v(t,(e=>(e-i)**2));return 0===n?0:r/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new h.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,f.intersection)(e,t).size/(0,f.union)(e,t).size,void 0)}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const n=r(i(48161)),s=i(19851),o=i(22573),a=i(41400),l=i(81168),u=i(28874);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??n.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??n.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),n=i(17344),s=i(96175),o=i(37805),a=i(81674),l=i(28874);function u(){return r.SimpleAppName+o.version}async function c(){return u()+" ("+(0,s.osFullName)()+") "+(0,n.EditionType)().toLowerCase()+"/"+await(0,a.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),n=i(19851),s=i(40958),o=i(22573),a=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),f=i(81168);function h(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),a.minuteMs),t.networkMacAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),a.minuteMs),t.myExternalIpAddresses=h,t.myExternalIp4Addresses=function(){return h().filter((e=>!e.includes(":")))};const m=(0,n.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,o.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,o.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,f.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),n=i(19851),s=i(22573),o=i(42659),a=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),f=i(50213),h=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),S=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==S.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=b.exec(e)}function M(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=M,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=M(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const _=(0,n.lazy)((()=>(0,f.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=M(e)?r.promises.reverse(e):r.promises.resolve4(e),5*o.secondMs);if(t===c.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),n=i(42659),s=i(31586),o=i(97790),a=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),f=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*n.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),n=i(22573),s=i(45599),o=i(59455),a=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),f=i(63870),h=(0,s.defer)((()=>(0,a.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,o.toA)(await async function(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return h().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(h().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),n=i(38639),s=i(19851),o=i(59958),a=i(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),n=i(19851),s=i(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),n=i(50213),s=i(84777),o=i(68284),a=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,n.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,o.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,a.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=r(i(48161)),s=r(i(1708)),o=i(22573),a=i(38639),l=i(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=r(i(73024)),s=i(19851),o=i(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),n=i(59455),s=i(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),f=u(i(1708)),h=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),S=i(54993),b=i(54557),P=i(19851),M=i(50213),_=i(88158),E=i(409),T=i(78406),x=i(25764),D=i(99331),k=i(56519),C=i(46292),O=i(8769),I=i(83278),F=i(32144),L=i(29882),A=i(43334),R=i(24399),N=i(58261),j=(0,P.lazy)((()=>(0,M.mkLogger)("proc.Pids"))),B=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,F.isJsonExt)(t)&&(0,L.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,E.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??A.isWin,r=await this.pidfiles(),n=await this.pids(r??[]);if((0,h.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,N.pidInfos)(n);if(null!=a){for(const n of r){const r=await n.readJson();if(null==r){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:r,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!z(r,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:r,pidEntry:u}),await n.unlink("debug"),s.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:r}),o.push(W(l,i,!1)),s.push({...r,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(i&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const i=a(this,r,"m",s).call(this,e.pid),n=(0,v.opt)((0,_.Try)((()=>(0,L.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await i.writeJson_(l),j().debug("addPid() wrote "+i,l),i}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==f.default.pid}))}async pids(e=this.pidfiles()){return(0,h.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,r,"m",s).call(this,e);return(0,k.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new T.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:x.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=U,n=new WeakMap,o=new WeakMap,r=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new U(I.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=i(31421),s=i(48161),o=r(i(1708)),a=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),f=i(59455),h=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),S=i(56519),b=i(84777),P=i(8103),M=i(45879),_=i(43334),E=i(24399),T=i(45643),x=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function k(e){if(_.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,M.readFileMaybe)("/proc/"+i+"/stat")));return x().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,T.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?F:N)).filter((e=>D(e)&&t.includes(e.pid)));return x().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=D,t.pidInfo=async function(e){return(0,S.thenMap)(k([e]),(t=>(0,f.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,T.existingPids)(e),(t=>{const i=[o.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=k;const C="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function F(e){if(E.PowerShell.instance().ended)return R(e);const t=[C,"-Id",I(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(E.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const L={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,L),r=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,h.toS)(e.CommandLine)}))));return r.find((e=>e.pid===o.default.pid))||r.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),r}async function N(e){return t=(await(0,b.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...L,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,h.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const j=(0,g.lazy)((()=>{try{if(_.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){x().warn("clk_tck failed",{error:e})}return 100})),B=(0,g.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,h.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(n)?{pid:i,cmd:r,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),n=i(22573),s=i(31586),o=i(29882),a=i(97352);t.progressEvtToS=function(e){const t=(0,n.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,n.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),n=i(42659),s=i(31586),o=i(12089),a=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new a.TTLMap(15*n.secondMs))),t.recentDone=(0,r.lazy)((()=>new a.TTLMap(2*n.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),n=i(31586),s=i(409),o=i(78406),a=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class f extends o.EndableInterval{constructor(e,t,i,n=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:n,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=n,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,n.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,n.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=f},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),n=i(19851),s=i(22573),o=i(42659),a=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),f=i(50213),h=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),S=i(31562),b=i(84777),P=i(34102),M=i(43334),_=i(28874),E=i(63870),T="{ready}",x=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,f.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${T}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:T,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,x),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,h.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,n)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,n)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,x),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,n.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),n=i(38639),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),n=i(31586),s=i(97790),o=i(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(97790),o=i(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(r.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),n=i(22573),s=i(45599),o=i(50213),a=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function f(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function h(e,t,i){try{return(0,n.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:f,...e})}cron(e){return h(this.name,this.value,e)??h(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),n=i(91655),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},86941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(19851),n=i(59455),s=i(72993),o=i(46292),a=i(95696),l=i(50213),u=i(83179),c=i(28874),d=i(2858),f=i(84438),h=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),s=await t.resolve_();if(null==r||null==s||s.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:s?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+s.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(f.SettingsToml);if(await e.isNonEmptyFile()){const t=s.join(f.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=s.join("licenses");for(const r of(0,n.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const o=s.join("old");try{const e=await r.renameYMDHMS_({subdir:o.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+o,e)}}t.mergeUserDataDirs_=async function(){const e=(0,o.configDir)();if(null==e)return;const t=a.PosixFile.for(e);for(const e of[t.join((0,s.AppName)()),t.join((0,s.AppName)().toLowerCase()),t.parent().join((0,s.AppName)().toLowerCase())])try{await m(e,t)}catch(i){h().error("Failed to merge "+e+" and "+t,i)}h().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),n=i(22573),s=i(38639),o=i(42659),a=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),f=i(67958),h=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){M(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&_()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,n.blank)(m.Settings.assetPathnameFormat.value)&&(0,n.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*o.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const S=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],b={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function M(e){for(const t of S)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:b;for(const[e,i]of(0,a.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:h.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:f.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function _(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=M,t.disableExternalNetworkRequests=_},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),n=i(53265),s=i(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class n extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),n=i(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=i(19851),a=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),f=i(55835),h=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),S=i(44198),b=i(96706),P=i(34102),M=i(28283),_=i(81075),E=i(98778),T=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,r,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?s(this,r,"m",n).call(this,e??t)+": "+i:null==this.fromEnv(e)?s(this,r,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,f.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,M.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(M.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return _.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,f.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,S.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&b.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,S.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&b.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,f.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],T.WrapComments);function i(e,i){(0,a.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],T.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,h.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+r],T.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,f.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,E.wrapTomlToLines)({lines:e,wrap:T.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,E.wrapTomlToLines)({lines:e,wrap:T.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,E.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),n=i(51168),s=i(76760),o=i(19851),a=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),f=i(68708),h=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),S=i(7282),b=i(12801),P=i(4328),M=i(70488),_=i(84248),E=i(5531),T=i(99315),x=i(34365),D=i(34580),k=i(96706),C=i(50274),O=i(33866),I=i(52086),F=i(48584),L=i(45969),A=i(43334),R=i(24540),N=i(70379),j=i(71300),B=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),H=i(30577),G=i(1485),q=i(19861),$=i(55111),J=i(30933),K=i(22859),Z=i(71988),Y=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),ne=i(57039),se=i(9945),oe=i(74589),ae=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),fe=i(81075),he=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:fe.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:fe.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Y.BooleanSetting({category:fe.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:fe.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:fe.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Y.BooleanSetting({category:fe.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Y.BooleanSetting({category:fe.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new he.StringArraySetting({aliases:["scanPath"],category:fe.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new he.StringArraySetting({category:fe.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:fe.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:fe.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:fe.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:fe.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:fe.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:fe.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:fe.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new ge.StringSetting({category:fe.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:fe.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Y.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:fe.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new oe.IntegerSetting({category:fe.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:fe.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:fe.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Y.BooleanSetting({category:fe.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Y.BooleanSetting({category:fe.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:fe.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:fe.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new he.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:fe.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new he.StringArraySetting({category:fe.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>G.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new he.StringArraySetting({aliases:["ignoredMountpoints"],category:fe.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:G.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new he.StringArraySetting({category:fe.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>G.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Y.BooleanSetting({category:fe.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new he.StringArraySetting({category:fe.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:fe.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new he.StringArraySetting({category:fe.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new he.StringArraySetting({category:fe.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Y.BooleanSetting({category:fe.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Y.BooleanSetting({category:fe.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Y.BooleanSetting({category:fe.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new he.StringArraySetting({category:fe.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:fe.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:fe.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:fe.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:fe.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Y.BooleanSetting({category:fe.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:fe.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Y.BooleanSetting({category:fe.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,L.isDocker)()}),cspReportOnly:new Y.BooleanSetting({category:fe.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Y.BooleanSetting({category:fe.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:fe.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:fe.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new Y.BooleanSetting({category:fe.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,M.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:fe.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:fe.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:fe.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:fe.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:fe.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:fe.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:fe.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:fe.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:fe.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Y.BooleanSetting({category:fe.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:fe.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:fe.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:fe.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:E.CheckpointTypes,defaultValue:E.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:fe.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:x.SynchronousModes,defaultValue:x.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:fe.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:T.RepairModes,defaultValue:T.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:fe.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:fe.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:fe.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Y.BooleanSetting({category:fe.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Y.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:fe.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,L.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:fe.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:fe.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new he.StringArraySetting({category:fe.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:fe.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:fe.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Y.BooleanSetting({aliases:["transcodeVideo"],category:fe.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:fe.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:fe.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new he.StringArraySetting({category:fe.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new he.StringArraySetting({category:fe.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new he.StringArraySetting({category:fe.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Y.BooleanSetting({category:fe.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Y.BooleanSetting({category:fe.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Y.BooleanSetting({category:fe.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Y.BooleanSetting({category:fe.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new he.StringArraySetting({category:fe.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:fe.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:fe.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:fe.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new he.StringArraySetting({category:fe.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:fe.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:fe.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new he.StringArraySetting({category:fe.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Y.BooleanSetting({category:fe.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Y.BooleanSetting({category:fe.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Y.BooleanSetting({category:fe.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Y.BooleanSetting({category:fe.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:fe.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:H.UpdateChannels}),autoUpdateCheck:new Y.BooleanSetting({category:fe.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Y.BooleanSetting({category:fe.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Y.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:fe.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new de.OptionalStringSetting({category:fe.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Y.BooleanSetting({category:fe.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:fe.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:fe.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new he.StringArraySetting({category:fe.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:fe.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Y.BooleanSetting({category:fe.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Y.BooleanSetting({category:fe.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:fe.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:fe.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Y.BooleanSetting({aliases:["syncLibraryFirst"],category:fe.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Y.BooleanSetting({aliases:["syncLibraryLast"],category:fe.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new he.StringArraySetting({category:fe.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:fe.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:fe.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:fe.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:fe.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Y.BooleanSetting({category:fe.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Y.BooleanSetting({aliases:["noModelUpdates"],category:fe.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:fe.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new he.StringArraySetting({category:fe.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Y.BooleanSetting({category:fe.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:fe.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Y.BooleanSetting({category:fe.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Y.BooleanSetting({category:fe.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Y.BooleanSetting({category:fe.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:fe.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:fe.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:fe.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:fe.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Y.BooleanSetting({category:fe.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Y.BooleanSetting({aliases:["jpegMinimized"],category:fe.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:fe.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:I.CropStrategies.attention,strEnum:I.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:fe.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Y.BooleanSetting({aliases:["sharpen"],category:fe.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:fe.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:fe.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Y.BooleanSetting({category:fe.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:fe.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Z.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:fe.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Y.BooleanSetting({category:fe.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Y.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:fe.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:fe.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:fe.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:fe.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:fe.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:fe.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:fe.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:fe.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:fe.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:fe.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:fe.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:fe.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:fe.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:fe.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:fe.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:fe.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:fe.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:fe.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new he.StringArraySetting({category:fe.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:fe.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:fe.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:fe.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new he.StringArraySetting({category:fe.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:fe.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:fe.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:fe.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:fe.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:fe.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,L.isDocker)()}),tagDisplayNameFSLabels:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new he.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:fe.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Y.BooleanSetting({category:fe.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:fe.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Y.BooleanSetting({category:fe.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:fe.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,f.entries)(t.Settings))i._setName(e);function be(e){const i=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,L.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,fe.SettingCategories.indexOf(e.category)??fe.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,k.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,f.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>fe.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>fe.LibraryCategories.includes(e.category)))));const Me=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Me().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),n=i(31586),s=i(7282),o=i(49776),a=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),f=i(96706),h=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,f.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(h.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(22573),a=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),f=i(57924),h=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),S=i(81168),b=i(83556),P=i(87290),M=i(98314),_=i(34102),E=i(83278),T=i(95696),x=i(60865),D=i(4175),k=i(83179),C=i(81075),O=i(28874),I=i(41692),F=i(84438),L=i(32707),A=i(6707),R=i(98778),N=i(55018),j=i(10357),B=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(F.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return X(E.BaseFile.for(e))}async function W(){try{return(0,o.toNotBlank)((await(0,A.readTomlFile_)((0,L.systemSettingsFile)()))?.[O.Settings.libraryDir.name])}catch{return}}function U(e){return(0,A.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function H(){return U((0,L.systemSettingsFile)())}function G(e){return U(z(e))}function q(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return B().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:O.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void B().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),n=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let n="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(n,i),B().info("writeToml(): wrote settings",{dest:n,file:e,nonDefaults:(0,k.settingsToObj)(i),wip:r}),r){const t=await(0,A.readTomlFile_)(n),i=await(0,A.readTomlFile_)(e);(0,u.eql)(t,i)?(B().info("Equivalent contents",{dest:n,file:e,a:t,b:i}),await n.unlink()):(B().info("Archiving prior, different contents",{dest:n,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await n.unwip_())}}async function K(e=(0,L.systemSettingsFile)()){const t=T.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,O.persistedSystemSettings)()),t}function Z(e){return X(z(e))}async function Y(e){await(0,P.setupLibraryDataDir_)((0,o.firstNotBlank)(e,O.Settings.libraryDir.value));const i=z(e);return B().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,O.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=B().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,n.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,M.errorToS)(e)),[]}}async function Q(e){const t=B().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,A.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const s=[],o=(0,n.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,O.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,O.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;s.push(e)}})));return t.info("loaded",{settings:(0,k.settingsToObj)(o),warnings:(0,n.toNotEmpty)(s)}),await(0,D.handleDeprecatedSettings)(),(0,D.handleMetaSettings)(o),{settings:o,warnings:s}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),a.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return O.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=H,t.librarySettingsVersion=G,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await H()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await G()&&await Y()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{B().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",q),(0,_.ee)().on("settingsChanged",q),O.Settings.libraryDir.watchLater(q)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,x.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(T.PosixFile.for(e),(0,O.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=Y,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([O.Settings.noNetwork,O.Settings.httpPort,O.Settings.license,O.Settings.logStdout,O.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(O.Settings))ee().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,j.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),O.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(T.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(T.PosixFile.forMaybe(z())?.unlink("trace")),(0,_.ee)().emit("clearCache"),I.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${(0,x.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,o={...e.addToJSON()};(0,n.mapNotEmpty)(e.altKeys,(e=>o.aliases=(0,f.orList)(e)));const a=(0,p.entries)(o).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,n.isNotEmpty)(a)&&a.push(""),i.push(...ie((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...a,`${e.key}=${(0,h.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),n=i(40958),s=i(22573),o=i(98553),a=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function f(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=f;class h extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:f,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=h},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class n extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),n=i(98553),s=i(55835),o=i(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,n=e.strEnum,(0,r.compact)((0,o.splitStringArray)(i)?.map((e=>n.getCI(e))));var i,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),n=i(81168),s=i(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),n=i(55835),s=i(46292),o=i(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,r.join)(e,o.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),n=i(44652),s=i(22573),o=i(76850),a=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),f=i(98778);function h(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?h((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>h(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,f.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),n=i(96249),s=i(98553),o=i(68708),a=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[n]:(0,a.wrap)(n.split("\n"),i)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),n=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=o(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function o(e){const t=(0,n.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),n=i(81168);t.bname=function(e,t=!0){let i=(0,n.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,n.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),n=i(19851),s=i(40958),o=i(76790),a=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),f=i(31586),h=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),v=i(81168),w=i(76596),S=i(79842),b=i(66649),P=i(21330),M=i(98725),_=i(928),E=i(54261),T=i(89724),x=i(17415),D=i(88600),k=i(51275),C=i(29882),O=i(17217),I=i(68284),F=i(57902),L=i(28874),A=i(65162),R=i(71300),N=i(14036),j=i(61424),B=(0,n.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,h.isObject)(e)&&(0,a.notBlank)(e.nativePath)&&(0,S.isDated)(e.date)&&(0,a.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,T.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,O.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,f.toGt0)(e.local)??(0,T.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,S.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(L.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,I.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,h.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,M.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,x.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,x.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,T.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,w.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,E.hasTime)(this.date)}hasMillis(){return(0,f.gt0)((0,_.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,x.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?L.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,S.datedToStartDateTime)(this.date)??(0,S.datedToDateTime)(this.date);if(null!=i)return{start:(0,T.datedToLocal)(i.minus(t)),end:(0,T.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:L.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,S.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function H(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],n=r;if((0,D.isValidDate)(t)){if((0,x.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||R.OverrideUTCZoneTags.includes(n))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,a.blank)(e.tzSource)?"":" from "+(0,v.stripPrefix)(e.tzSource,"from ");n+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,T.datedToLocalSec)(t),date:t,src:n,precisionMs:(0,S.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,S.datedToStartTs)(e.date)));if(null==r)return;const n=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,S.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),o=(0,p.leastBy)(n,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:n,earliest:o}),o}function G(e,t){if(L.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)])){const e=(0,M.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,S.datedToPrecisionMs)(e),l.secondMs])}}}function q(e){if(L.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,M.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(L.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,o.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function n(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,T.datedToLocal)(i.date),src:(0,v.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!L.Settings.usePathsToInferDates.valueOrDefault||!L.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:L.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),o=n("tags",H(t,L.Settings.capturedAtTags.values))??(i?void 0:n("siblings",await(0,j.inferCapturedAtFromSiblings)(e)))??n("tags",H(t,L.Settings.capturedAtTagsFallback.values))??(s?void 0:n("stat+bname",await(0,j.extractStatBname)(e)))??(s?void 0:n("stat+path",await(0,j.extractStatPathTime)(e)))??(i?void 0:n("siblings",await(0,j.inferCapturedAtFromSiblings)(e)))??(s?void 0:n("bname",G(e,t)))??(s?void 0:n("path",q(e)))??(L.Settings.useStatToInferDates.valueOrDefault?n("stat",await $(e)):void 0);return B().tap({level:F.LogLevels.debug,msg:"extractCapturedAt()",result:o})},t.capturedAtFromTags=function(e){return H(e,L.Settings.capturedAtTags.values)},t.capturedAtFromBasename=G,t.capturedAtFromPath=q,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),n=i(97352),s=i(95696),o=i(47783),a=i(16170);function l(e){if(null!=e&&(0,a.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,n.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,o.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const n=i(77988),s=r(i(76760)),o=r(i(1708)),a=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),f=i(23838),h=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),v=i(12168),w=i(56038),S=i(4867),b=i(36557),P=i(98247),M=i(21330),_=i(98725),E=i(23467),T=i(88561),x=i(95696),D=i(17217),k=i(16287),C=i(50213),O=i(17921),I=i(7282),F=i(88158),L=i(23560),A=i(28874),R=i(12089),N=i(45255),j=i(81168),B=i(63870),z=i(15674),V=i(28544),W=i(43207),U=i(72180),H=i(75767),G=i(12788),q=i(80495),$=i(14036),J=i(67083),K=i(3432),Z=i(28630),Y=i(15912),X=i(30748),Q=i(16170),ee=i(95141),te=i(7330),ie=i(54979),re=i(1078),ne=i(61424),se=i(8791),oe=(0,a.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ce()};const le=(0,a.lazy)((()=>new b.BatchClusterObserver("ExifTool",new n.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,b.batchClusterOptions)((0,I.isTest)()?8:(0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function ue(){const e=le();return e.ended?le.refresh():e}function ce(e=!1){return(0,d.map)(le.clear(),(t=>t.end(e)))}t.exiftool=ue,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeoutError)({p:ue().version(),timeoutMs:N.ShortCommandTimeoutMs})},t.exiftoolVersionMaybe=function(){return(0,d.map)(le.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,B.commandTimeoutMs)()})))},t.shutdownExiftool=ce,t.extractBinaryTag=function(e,t,i){return ue().extractBinaryTag(e,t,i)},t.tagsCache=(0,a.lazy)((()=>new T.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,a.lazy)((()=>new T.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),ie.mimetypeCache.prior()?.clear()};async function de(e){return(0,h.omit)(await ge(e,!1),...t.IgnoredSidecarFields)}function fe(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function me(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function pe(e,t,i){if((0,j.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return oe().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,ie.readMimeType)(e),n=await e.sidecar(),s=(0,Q.isImageMimeType)(r)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,o=(0,Q.isVideoMimeType)(r)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,a=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await n.exists(),l=s||o||a;return oe().tap({msg:"writeTagDest()",result:l?n:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:o,writeMetadataToSidecarsIfSidecarExists:a}})}async function ge(e,i=!0){const r=x.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void oe().debug("readRawTags("+r+"): invalid file, returning null.");const n=await(0,t._readRawTags)(r.nativePath);if(null==n||!i)return n;oe().trace("readRawTags()",{pf:r,pickedFileTags:(0,h.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await r.jsonSidecars())s.push([e,(0,Z.readJsonSidecar)(e,n.tz)]);for(const e of await r.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const o={original:{},MIMEType:(0,u.mapNotBlank)(n.MIMEType,Q.normalizeMimetype),...n},a=[];for(const[e,i]of s){if(null==i)continue;const r=await i;if(null==r)continue;const n=(0,h.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,h.values)(n))?((o.sidecars??(o.sidecars=[])).push(e.base),a.push(...(0,g.toA)(r.History)),(0,F.assignNullishFields)(o.original,(0,h.pick)(o,...(0,h.keys)(n))),(0,h.assignFields)(o,n),oe().debug("readRawTags() sidecar had values",{sidecar:e.base})):oe().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return o.inferred=(0,J.getInferredHistoricValues)(a,e),(0,F.assignNullishFields)(o,o.inferred),o.Rotation=(0,ee.orientationToRotation)(o.Rotation),oe().debug("readRawTags() final",{pf:r,inferred:o.inferred,pickedResult:(0,h.pick)(o,"tz","tzSource",...A.Settings.capturedAtTags.values)}),o}async function ye(e,t){return null==t?void 0:(0,w.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Q.normalizeMimetype);if((0,u.blank)(r))return void oe().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(oe().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const a=!await(0,ne.canInferForDir)(e.parent()),l=await(0,K.maybeInferTimezone)(e,s,a);if(oe().debug("parseTags()",{tzMeta:l,skipSiblingInference:a}),null!=l?.tz){const e=s.tzSource!==n.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values])if(!(0,U.isUtcTagName)(t)){const i=s[t];i instanceof n.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,h.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,h.assignFields)(s,l)}const c=a?(0,X.extractMakeAndModel)(s):await(0,ne.inferMakeAndModel)(e,s);c.Make!==(0,X.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,G.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(s),f=await(0,V.extractCapturedAt)(e,s,a);if(null==f)return void oe().info("No capturedAt for "+e);!a&&f.isInferred&&(s.inferred.capturedAt=f);const m=(0,q.extractExposureSettings)(s),g=await(0,re.extractSizeInfoFromFile)(e,s);if(null==g)return void oe().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:f,exposureSettings:m,...(0,se.extractTitleDescription)(s),...d,cameraId:(0,H.cameraIdFromTags)(s),imageId:(0,H.imageIdFromTags)(s),lensId:(0,H.lensIdFromLensInfo)({...d,...(0,h.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,te.extractRating)(s)};(0,I.isTest)()&&(y.__parsedBy__=o.default.pid);const v={...s,...y};return oe().debug("parsedTags",{nativePath:i,skipInference:a,...y,inferred:s.inferred,original:s.original,pickedResult:(0,h.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,h.definedValues)(v)}catch(e){return void oe().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,h.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,h.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(de(e),de(t))},t.readTags=fe,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=x.PosixFile.for(e);return ye(t,await ge(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await fe(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await ue().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,F.pluckCaseInsensitive)(i,t)}catch(e){return void oe().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,ee.extractRotation)(await ge(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("exiftool.overwriteTags:"+e,(async()=>{await ue().write(e.nativePath,t,await me(e)),e.clearThisAndParent()}))}catch(i){oe().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await ue().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=me,t.writeTagDest=pe,t.writeTags_=function(e,t,i){return(0,w.time)("exiftool.writeTags:"+e,(async()=>{const r=new f.MultiMap;for(const[n,s]of(0,h.entries)(t)){const t=await pe(e,n,i);r.add(t.nativePath,[n,s])}for(const[t,i]of r.entriesArray()){const r=x.PosixFile.for(t),n=(0,h.fromEntries)(i);oe().info("writeTags()",{src:e,dest:t,t:n}),await ue().write(r.nativePath,n,await me(r)),A.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=ge,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return oe().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);oe().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...A.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,$.isVideoExt)(s.default.extname(e))?[]:["-fast"]],r=await(0,w.time)("exiftool.read()",(()=>ue().read(e,i).catch((t=>{oe().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;oe().debug("_readRawTags()",{nativePath:e,pickedTags:(0,h.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,Q.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,h.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const n=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(n)&&(r.problems=n),ae&&(r.__instance=(0,O.safeUUID)()),r}}),t.parseTags=ye},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(98553),a=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),f=i(54993),h=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,o.stringify)((0,u.fromEntries)(t))}function b(e){return(0,f.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new a.MultiMap,r=[];for(const o of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(n=e[o])||(0,s.blankish)(n)||(0,l.isNumber)(n)&&(0===n||1===n)||null!=t.zeroesRe.exec((0,f.toS)(n)))continue;const a=e[o],u=b(e[o]),c=(0,t.Tag2SynonymGroup)().get(o);if(null!=c){if(i.includes(c,a)||i.includes(c,u))continue;i.add(c,a)}r.push([o,(0,l.gt0)(a)?a:u])}var n;return S(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:r,parser:n}){const s=n(e[i]),o=n(t[i]),a=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==o||(0,l.approximates)(s,o,a)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function T(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),s=_(i);if(null==r||null==s||e===i)return;const o=(0,h.intersection)((0,u.keys)(r),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of o){const t=r[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const o=(0,u.values)(t).map(f.toS),a=(0,u.values)(i).map(f.toS);if((0,n.includesAny)(o,a))continue;const l=(0,h.least)((0,u.keys)(t)),c=(0,h.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return T({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=T,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),n=i(54993),s=/undefined|null|none|n\/a|unknown/i;function o(e){return null==e||(0,r.blank)(e)||s.test((0,n.toS)(e))}t.isExifUnset=o,t.toExifDefined=function(e){return o(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),n=i(22573),s=i(31586),o=i(68708),a=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,n.firstNotBlank)((0,a.toS)(e.ExposureTime),(0,a.toS)(e.ShutterSpeed),(0,a.toS)(e.ShutterSpeedValue),(0,a.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,o.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,a.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),n=i(40958),s=i(96249),o=i(23838),a=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),f=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const h=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,a.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return h()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:f.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:f.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:f.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:f.ExtTypes.Video},{exts:c.SidecarFiletypes,type:f.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:f.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:f.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,f.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,f.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(f.ExtTypes.Sharp)||t.includes(f.ExtTypes.RawImage)?"image":t.includes(f.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,f.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,f.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,f.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,f.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,f.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,f.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,f.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=f.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),n=i(45599),s=i(68708),o=i(50213),a=(0,n.defer)((()=>(0,o.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,s.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:n}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[n])&&(t[i]=t[n]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){a().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,s.pick)(e,"Directory","FileName"));for(const t of(0,s.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),n=i(19851),s=i(40958),o=i(76790),a=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),f=i(50989),h=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),v=i(50213),w=i(81168),S=i(66649),b=i(17415),P=i(29882),M=i(95696),_=i(17217),E=i(28874),T=i(47783);function x(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:n}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(n??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,f.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=x,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,n.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,h.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function O(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,a.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function F(e,i,r){if(null==e||(0,a.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const n=(0,_.toNativePath_)(e),o=await(0,T._readRawTags)(n),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(o,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const f=M.PosixFile.for(e);return await(0,T.overwriteTags_)(f,c),f.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const n=(0,m.toA)(e);if((0,s.isEmpty)(n))return{};const l=(0,o.sortBy)(n.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,a.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,a.notBlank)(t)){const r=O(e);(0,a.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=O,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const n=x(t.Actions.infer,r),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:n,additionalTags:s}),F(i,n,s)},t.ensureHistoryRecords=F},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const n=r(i(53705)),s=i(77988),o=i(19851),a=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),f=i(17415),h=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),w=i(14245),S=i(61424),b=(0,o.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,w.omitInvalidGeolocationTags)(t);{const e=M(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,f.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,a.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,f.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=_(e,t);if(null!=i)return i}if(!i){const t=await(0,S.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function M(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return b().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,n.default)(t,i);return b().tap({msg:"zoneFromLatLon()",result:(0,f.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return b().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function _(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const n=(0,u.toDated)(t[r]);if(null==n||(0,h.isValidDate)(n))continue;const s=Math.round(15*i.diff(n,"minutes").as("minutes")/15),o=(0,f.normalizeZoneOffsetMinutes)(s),a=0===o?void 0:(0,f.normalizeZone)(o);if(null!=a)return b().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:a.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(n),rawTzoffsetMinutes:s,normalizedOffsetMinutes:o}})}}t.maybeInferTimezone=async function(e,t,i){return b().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=M,t.inferTzOffsetMinutesFromFilename=_},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),n=i(40958),s=i(22573),o=i(38639),a=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),f=i(48884),h=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const n=(0,p.normalizeZone)(e?.formatted),s=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:n??t??r.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,f.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,h.validLat)(e)?e:void 0)),GPSLongitude:(0,f.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,h.validLon)(e)?e:void 0)),GPSAltitude:(0,f.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,a.map)(e.favorited,o.isTrue),peopleNames:(0,n.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,n.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(55835),a=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),f=i(28874),h=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,h.make)(e.LensMake),i=(0,h.make)(e.Make),r=[],a=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,n.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:a,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:a});const o=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))o.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:a});for(const i of(0,n.compactBlanks)([t,...f.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:a});o.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:a})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,o.map)(e.lensInfo,b)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,o.mapOr)((0,a.toFloat)(e),(e=>String((0,a.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),n=i(22573),s=i(55835),o=i(68708),a=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function f(e,t,i=""){const r=e.replace(t,i);return r===e?e:f(r,t,i)}const h=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=h.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=f(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,a.toS)(e.HandlerDescription))||y.test((0,a.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,o.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,n.blank)(e))for(const[t,i]of(0,o.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const r=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=f(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),n=i(54993),s=i(2322),o=i(277),a=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function f(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function h(e){const t=(0,n.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,n.toS)(e))},t.isImageMimeType=function(e){return(0,n.toS)(e).startsWith("image/")},t.isVideoMimeType=f,t.normalizeMimetype=h,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&h(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&h(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(f(t)?await(0,l.isVideoSupported)():(0,a.isHeifMimeType)(t)?await(0,o.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),n=i(54993),s=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??a(e.Orientation)};const o=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function a(e){return(0,r.isRotation)(e)?e:null!=e?o.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,n.toS)(e).startsWith("Mirror")},t.orientationToRotation=a;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),n=i(31586),s=i(28874);function o(e){const t=(0,n.toInt)(e);return null==t?void 0:(0,n.clamp)(-1,5,t)}function a(e){return o(e?.Rating)??(0,n.mapNumeric)((0,n.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=o,t.extractRating=a,t.extractLiked=function(e){const t=a(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),n=i(22573),s=i(55835),o=i(88561),a=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new o.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,n.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,a.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),n=i(40958),s=i(22573),o=i(81168),a=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),f=i(14036);function h(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isJsonExt)(i.ext),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(h(e.base,i.name,{ignoreCase:l}))return!0;if(h(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(h(e.name,t,{ignoreCase:l}))return!0}const m=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,n.uniq)([e.base,e.name,(0,f.stripExt)(e.base)]))for(const e of(0,n.uniq)([i.name,i.name,(0,f.stripExt)(i.name)]))if(h((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return a&&function(e,i){const r=(0,o.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function n(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=n(e.slice(r.length)),l=n(i.slice(r.length));return a&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),n=i(22573),s=i(42659),o=i(33374),a=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),f=i(34943),h=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,n.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,r,await(0,f.rawInfo)(e));const s=b(i,r);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,h.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,a.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,o.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:f.rawInfo,fileDimensions:r}});const n=(0,o.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:n.height,ImageWidth:n.width,aspectRatio:(0,d.aspectRatio)(n),dimensions:n,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:f.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),n=i(51168),s=i(19851),o=i(40958),a=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),f=i(48884),h=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),v=i(79842),w=i(21330),S=i(98725),b=i(51275),P=i(35280),M=i(19748),_=i(88561),E=i(95696),T=i(65238),x=i(17217),D=i(57902),k=i(28874),C=i(80496),O=i(65162),I=i(28544),F=i(47783),L=i(88840),A=i(30748),R=i(16170),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),j=7;async function B(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,T.isSlowDir)(e.nativePath)&&!await(0,T.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,A.extractMakeAndModel)(await(0,F.readRawTags)(t));if((0,h.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,h.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await B(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await G(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(L.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,o.compact)((0,f.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function G(e,t=7,i=!0){if(!await B(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const n=(0,a.sortBy)(r,(e=>(0,O.bname)(e))),s=(0,x.findFileIndex)(e,n);if(s<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),G(e,t,!1)):void 0;const l=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[n.slice(s-2*t,s),n.slice(s+1,s+1+2*t)],d=[],f=[];for(;(0,o.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,o.isNotEmpty)(c)&&f.length=l&&f.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:f},meta:{f:e}})}t.nearestSiblings=G,t.nearestSiblingTzOffset=async function(e){if(!await B(e.parent()))return;const t=H(await G(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,j);for(const t of e){const e=await(0,F.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,o.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:n.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(55835),a=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),f=i(81168);function h(e){return(0,u.toS)((0,a.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(h))}function p(e,i=t.TagSep){return m(e).map((e=>(0,a.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?h((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,f.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=h,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,o.mapOr)(v(e),(e=>(0,f.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,n.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,n.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),n=i(22573),s=i(68708),o=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,n.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,o.toS)(e[r]).trim();if((0,n.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(96249),a=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),f=i(7014),h=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,f.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),h.URI.file(e)])}async function S(e){const t=await w(e);return(0,n.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return h.URI.isUri(e)?e:h.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??h.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,n.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),n=i(57975),s=i(90595),o=i(22573),a=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),f=i(43334),h=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,n,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=n??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!h.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:n,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===n?n=this.query:null===n&&(n=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&r===this.path&&n===this.query&&s===this.fragment?this:new b(t,i,r,n,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const r=i[2]||g,n=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),o="psfile"===r&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(r,n,o,a,l,t)}static file(e){let t=g;if(f.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=f.isWin&&"file"===e.scheme?w.file(r.win32.join(E(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return T(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=w;const S=f.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let n=0;n=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),void 0!==i&&(i+=e.charAt(n));else{void 0===i&&(i=e.substr(0,n));const t=P[s];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),i+=t):-1===r&&(r=n)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,f.isWin&&(i=i.replace(/\//g,"\\")),i}function T(e,t){const i=t?_:M;let r="";const{scheme:n,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(n&&(r+=n,r+=":"),(l||"file"===n)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>r+="?"+e)),a&&(r+="#",r+=t?a:M(a,!1)),r}function x(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+x(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>x(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),n=i(40958),s=i(50357),o=i(89937),a=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const f=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function h(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&h(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return f().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||h(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,n.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),n=i(22573),s=i(51926),o=i(89937),a=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),f=i(85087);function h(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,n.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,n.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,f.volsha)(t.uuid),path:u})},t.joinMountpoint=h,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,n.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,s=(0,n.notBlank)(t)&&!t.includes(i);if(s&&!(0,n.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,f.volsha)(i.uuid)===e.authority)return h(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?h(a.mountpoint,e.path):s&&(0,n.notBlank)(t)?h(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),n=i(22573),s=i(51926),o=i(89937),a=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,n.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,n.blank)(t))return;const i=(0,r.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(76760)),a=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),f=i(16287),h=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,a.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const n=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,h.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...n);return await(0,f.isReadableDirectory)(t)?o.join(t,...n):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),n=i(42659),s=i(9103),o=i(37628);t.volsha=(0,s.memoize)((e=>(0,r.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:n.minuteMs})},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),n=i(30577);t.channel=function(){return(0,n.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),n=i(22573),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof r.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const s=o(e);return null!=s&&(0,r.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),n=i(9595),s=i(29882),o=i(43334),a=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,n.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),n=i(22573),s=i(59455),o=i(50213),a=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),f=i(69108),h=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,f.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),n=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||r||n);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:n}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,f.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,n.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,h.isGioSupported)())for(const e of(0,s.toA)(await(0,h.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),f=i(63870),h=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,n.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void h().info("parseDfVolume(): skipping (size is 0)",{vol:e});const n=m(e.Used)??0,s=m(e.Available)??0;if(0!==n||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?n+s:r,used:n,available:s};h().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:n,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,n.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,f.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return h().warn("empty output",{localsOnly:e,paths:t}),[];h().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(22573),a=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),f=i(59455),h=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),S=i(24541),b=i(60224),P=i(63870),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function T(e){return(0,l.map)(E(e),(e=>e+":\\"))}function x(e){return`Get-PSDrive -PSProvider FileSystem ${(0,h.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,h.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=T,t.getPsDriveCommand=x,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=T(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,n.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,h.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var s}async function F(){const e=(0,n.uniq)((0,f.toA)(await(0,S.mountpointsWin)()).map(T)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,n.compact)((0,a.flatten)(t).map(D)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,n.compact)((0,a.flatten)(r).map(I)),l=(0,n.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,n.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(42659),a=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),f=i(45255),h=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),S=i(16287),b=i(45969),P=i(43334),M=i(69108),_=i(98770),E=i(44224),T=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,T.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const x=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?x().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):x().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,n.isEmpty)(e)?[]:(x().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,T.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void x().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await D(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,T.mountpointsTtlMs)()}))),(0,a.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,T.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,h.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,h.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,h.stripPrefix)(e,"/"))).flatMap((e=>(0,h.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void x().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),n=i(5233),s=i(41400),o=i(56038),a=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function f(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,n.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&f(u)})),u},t.setupVolumeTTL=f},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),f=i(6012),h=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),S=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const s=(0,c.sortIgnoreCase)((0,n.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const n=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...n,...s},u=r?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:n,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,h.splitLines)(e).map((e=>(0,f.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),r=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,f.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),n=i(19851),s=i(40958),o=i(22573),a=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),f=i(56519),h=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,n.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),n=await(0,f.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,h.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of n)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(42659),a=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),f=i(23560),h=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),S=i(8769),b=i(34102),P=i(17217),M=i(16287),_=i(43334),E=i(28874),T=i(8540),x=i(68884),D=i(44224),k=i(24541),C=i(69375),O=i(63870),I=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function F(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,O.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function A(){F()}t.localMountpointSetup=(0,r.lazy)((async()=>{E.Settings.libraryDir.watchLater(F),E.Settings.scanPaths.watchLater(F),(0,f.isSyncService)()&&E.Settings.scanAllDrives.valueOrDefault?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,O.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux){const i=(0,D.maybeWatchProcMounts)();await(0,x.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,O.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,O.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),o.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,n.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?k.mountpointsWin:D.mountpointsPosix),h.ShortCommandTimeoutMs);if((0,n.isEmpty)(e))return I().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,O.commandTimeoutMs)(),f:async e=>!(!(0,T.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(I().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,a.later)((()=>{(0,b.ee)().on("clearCache",(()=>{x.gioVolumes.unset(),F()})),E.Settings.mountpointsTtlMs.watch(L)}),(0,c.isTest)()?1:o.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>A(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:x.GioCommand,args:x.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(x.gioVolumes.unset(),A()),minCallDelayMs:h.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,O.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>A(),minCallDelayMs:h.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),n=i(40958),s=i(42659),o=i(48884),a=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),f=i(73787),h=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),S=i(68884),b=i(59107),P=i(69375),M=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await x()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,S.isGioSupported)())try{await(0,c.thenMap)((0,S.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){M().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function E(e){return!v.Settings.excludedFilesystemTypes.has(e)}function T(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function x(e=_,t=E,i=T){if(y.isLinux)try{const r=await(0,h.readLines_)(e),s=(0,n.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),a=await(0,c.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,r])=>{const n=t(e),s=await i(r);return M().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:n&&s,meta:{fs:e,mp:r,fsOK:n,mpOK:s}})}});return M().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void M().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=E,t.readProcMounts=x,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(_)?new f.FileWatcher(_,{recursive:!1,persistent:!1},(()=>{M().info("detected change in "+_),(0,d.setUnrefTimeout)((()=>b.mountpoints.refresh()),s.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),n=i(42659),s=i(13538),o=i(50213),a=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),f=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function h(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(h(),a.ShortCommandTimeoutMs)}catch(e){return f().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=h;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*n.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),n=i(22573),s=i(50213),o=i(9103),a=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const f=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,h=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===f?.test(e)?"LinuxDevMapperRE":!0===h?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),n=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,r.blank)(e))return;const i=n.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),n=i(22573),s=i(42659),o=i(55835),a=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),f=i(81168),h=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await E()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,n.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,n.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(n.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,p.wmic)(),t=await(0,h.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,u.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,f.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,n.notBlank)(e.LocalName))).map((e=>(0,o.map)(M(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,f.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),n=i(12168),s=i(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(38639),a=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),f=i(81168),h=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),S=i(28874),b=i(59107),P=i(63870),M=i(68995),_=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),E=(0,n.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function T(e){return(0,o.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function x(e){if((0,s.blank)(e))return;const t=(0,f.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=x(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function k(e){if(S.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of S.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),r=await D(i).catch((e=>_().info("Failed to read "+i,{error:e})));if(null!=r)return _().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,M.volumeUuidSubpath)());if("/"===e.mountpoint)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(S.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(S.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,M.writeVolumeUuid)(e);if(!(0,s.blank)(t))return _().tap({msg:"readVolumeUUID(): wrote new "+(0,M.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return _().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>E.clear())),b.mountpoints.watchLater((()=>E.clear()))})),t.addVolumeUUIDs=async function(e){await(0,h.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(T(e))return;if((0,o.isFalse)(e.ok))return;const t=await E().getOrSetAsync(e.mountpoint,(async()=>k(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>_().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=T,t.toVolumeUUID=x,t.readUuidFile_=D,t.readVolumeUUID=k},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const n=r(i(48161)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),f=i(41400),h=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),S=i(50213),b=i(7282),P=i(23560),M=i(28850),_=i(45255),E=i(81168),T=i(56519),x=i(4867),D=i(49776),k=i(9595),C=i(77740),O=i(44198),I=i(96706),F=i(8769),L=i(57159),A=(i(34102),i(21144)),R=i(73209),N=i(29882),j=i(95696),B=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),H=i(43334),G=i(28874),q=i(85087),$=i(50424),J=i(48165),K=i(98770),Z=i(27461),Y=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,o.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=n.default.platform(),se=new Map,oe=new Map,ae=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,q.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,se),le((0,q.volsha)(e.uuid),e,ae),e}function ce(){return(0,a.compact)([j.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),se.clear(),ae.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,T.mapAsync)({name:"readCachedVolumes",arr:(0,T.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function fe(e){if(null==e)return;const i=new h.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),n=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:ne}))),s=new Map;for(const e of n)for(const t of(0,a.compactBlanks)([(0,q.volsha)(e.uuid),(0,q.volsha)(e.mountpoint)]))s.set(t,e);const o=ce();for(const e of o)await(0,R.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:n.map((e=>e.mountpoint))}),i.resolve()}async function he(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),n=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:n,priorIsMissingMountpoints:s}),n||s?void 0:e}async function me(e,i){const r=(0,m.map)(e,B.toNativePath_);if((0,u.blank)(r))return;const n=await(0,A.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(n,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:n,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:n}})}async function pe(e,t,i){const r=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(r))return;const n=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=n)return n;const s=await(0,W.friendlyname)(e);return(0,T.asyncFind)(r,(async e=>(0,E.equalsIgnoreCase)(s,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,P.isSyncService)()||(0,b.isTest)())),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await de()),t=(0,v.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,a.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=he,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,x.thenOrTimeoutError)({p:he(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,x.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,a.isNotEmpty)(i))return i}catch(e){(0,F.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if((0,b.isTest)()){const e=(0,p.toInt)((0,O.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,f.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,x.thenOrTimeoutError)({p:H.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,T.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,x.thenOrTimeoutError)({p:H.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,F.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await fe(r),Object.freeze(r)}}),t.rootPath=(0,o.lazy)((()=>H.isWin?(0,g.opt)((0,I.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,q.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,T.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return ae.get(e)??(await de())?.find((t=>(0,q.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,q.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(50213),a=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),f=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function h(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=h,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,h());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const n=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(n))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),f().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){f().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else f().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),n=i(40958),s=i(22573),o=i(89937),a=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,a.toURI)(e),l=i.scheme===o.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===o.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,s.blank)(l))return;const u=i.path.split("/");return(0,n.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),n=i(40958),s=i(31586),o=i(27776),a=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),f=i(34238),h=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,n.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,a.hostname)()]));const i=(0,f.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,h.uriToTagPath)({uri:i,isFile:!1});if((0,n.isEmpty)(r))return;const s=(0,o.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(s)},t.mkAssetUrl=function(e){return(0,s.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const o=s(i(37067)),a=s(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),f=i(50213),h=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),v=(0,u.defer)((()=>(0,f.mkLogger)("net.get")));async function w(e,t){return S({...t,url:e})}async function S(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?o.request:"https"===t.scheme?a.request:v().throw("unsupported scheme: "+t.scheme),n=e?.maxRedirects??8,s=e?.timeoutMs??h.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",f=e?.agent??!1,S=r(t.toString(),{method:c,headers:u,timeout:s,agent:f},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const o={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};n>0&&y.HttpStatusIs.redirect(o.statusCode)&&!(0,l.blank)(e.headers.location)?(v().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:o.statusCode}),i.observe(w(e.headers.location,{timeoutMs:s,maxRedirects:n}))):(v().debug("complete",{...o,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(o))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||S.write(e.body),S.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=w,t.httpRequest_=S},78932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httping=void 0;const r=i(19851),n=i(50213),s=i(34238),o=i(4988),a=(0,r.lazy)((()=>(0,n.mkLogger)("net.httping")));t.httping=function(e,t,i,r){return(0,o.get_)(s.URI.from({scheme:"http",authority:e+":"+t,path:i}),{timeoutMs:r}).then((e=>e.statusCode??-1),(e=>{a().warn("get() Failed",{error:e})}))}},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),n=i(19851),s=i(23838),o=i(81168),a=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,n.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,n.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(h(e))}));const d=(0,n.lazy)((()=>({trie:new s.MultiMap,small:[]}))),f=3;function h(e){const t=new s.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=n)return n}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),n=i(96249),s=i(23838),o=i(59455),a=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,n.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=r(i(48161)),s=i(19851),o=i(42659),a=i(31586),l=i(50213),u=i(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=r(i(48161)),s=i(19851),o=i(31586),a=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),f=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(r))return f().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return f().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),n=i(37692);let s=!1;function o(){return s}function a(e=!0){l(e),(0,n.writeStateFile)({paused:e})}function l(e){e!==s&&(s=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=o,t.pause=a,t.resume=function(){return a(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return o()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),n=i(42659),s=i(41400),o=i(31586),a=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),f=i(28874),h=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),h.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),f.Settings.cpuBusyPercent.watchLater(y),f.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,r.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,h.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(f.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,h.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=w();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,h.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const n=r(i(78474)),s=i(40958),o=i(76790),a=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),f=i(87290),h=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),v=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let w;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new n.default;let S=0;function b(){const e=(0,f.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-S>a.minuteMs;i&&(S=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(w?.nativePath)||(w?.close(),w=void 0),r&&null!=e&&(w??(w=new h.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=b()?.readJsonSync();for(const i of e?.events??[])M.get(i.e)!==i.ts&&(v().info("emitting event "+i.e),t.stateEvents.emit(i.e),M.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const M=new Map;function _(e){const i=b();if(null==i)v().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),n=function(e){const t=Date.now()-10*a.minuteMs;return(0,s.uniqByLast)((0,o.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:n};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=_,t.addStateEvent=function(e){const t=Date.now();M.set(e,t),_({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),n=i(87997),s=i(19851),o=i(42659),a=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),f=i(976),h=i(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new r.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,n.setInterval)(g,o.minuteMs).unref()));function g(){h.maxCpus.refresh(),h.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,f.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{h.maxCpus.unset(),h.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),n=i(22573),s=i(50357),o=i(98553),a=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),f=i(59455),h=i(54993);function m(e){return null!=e&&(0,f.toA)(e).length>0}function p(e){return null==e||0===(0,f.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function S(e){return null==e?[]:v((0,f.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,a.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const n=[];if(et;s-=i)n.push(r(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),n=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const n of t){const t=i(n);r.includes(t)||(e.push(n),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,f.toA)(e).map((e=>(0,h.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const n=new Set(i.map(r));return e.filter((e=>!n.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),n=i(36783),s=i(41801),o=i(98553),a=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,n.copyArrayTo)(h(e,t),e)}function f(e,t){const i=new Map;for(const r of e)(0,a.getOrSet)(i,(0,o.stringify)(t(r)),(()=>r));return h(i.values(),t)}function h(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=f,t.sortUniq=function(e){return f(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(f(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=h,t.deepSortBy=function e(t,i){return h(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),n=i(31586),s=i(13538),o=i(41583);t.retryOnReject_=async function(e,t){const i=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(55938),a=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,o.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,o.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,n.blank)(e)?"":"```"+(0,a.toS)(e)+"```"},t.b=function(e){return"**"+(0,a.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,a.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),n=i(42279),s=i(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),n=i(22573),s=i(30301),o=i(55835),a=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),f=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function h(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?f().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=h,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=h(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),n=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,n,r)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,n.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/r.ms);e-=s*r.ms,s>0&&(r.ms>=t.dayMs?i:n).push(s+r.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),n=i(73872);function s(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function o(e,t,i,r){if(null==i||y(e)||y(t))return;let n=i.get(e);null!=n?n.set(t,r):(n=new WeakMap,n.set(t,r),i.set(e,n))}function a(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const n=l(e,t);return null!==n?n:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,h=s(e,t,u);if(null!==h)return h;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return o(e,t,u,i),i;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(f(e),f(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],n=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(r.sort(),n.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let n=-1;for(;++n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const n=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return n.prior=()=>t,n.hasPrior=()=>r,n}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),n=i(35556),s=i(31586),o=i(68708);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=n.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return n.isBrowser||t<=r.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),n=i(21605),s=i(12168);function o(e){return{width:e.height,height:e.width}}function a(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=o,t.maybeDimSwap=function(e,t){return(0,n.swappableRotation)(t)?o(e):e},t.maybeFlipInPlace=function(e,t){(0,n.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(a(e))},t.pixels=a},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),n=i(68708),s=i(34666),o=i(32639);function a(e,t){return(0,r.deepEql)(e,t,{comparator:f})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const i of(0,n.keys)(e))if(!a(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function f(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(31586),a=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const f=/shortStack|errorToVerbose/;function h(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,s.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return h(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==f.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=h,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),n=i(42659),s=i(55835),o=i(31586),a=i(12168),l=[{ms:n.yearMs,s:"year",p:"years"},{ms:n.yearMs/12,s:"month",p:"months"},{ms:n.weekMs,s:"week",p:"weeks"},{ms:n.dayMs,s:"day",p:"days"},{ms:n.hourMs,s:"hour",p:"hours"},{ms:n.minuteMs,s:"minute",p:"minutes"},{ms:n.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,n){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(n,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function n(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),n=i(38639),s=i(68708),o=i(62220),a=i(50989);t.HealthCheckSections=(0,a.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,a.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&o.RunStates.has(e.state)&&(0,n.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const n=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,n){if((0,isFunction_1.isFunction)(r))return;let s,o,a,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),n=i(50357),s=i(31586),o=i(65812);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const s=await e,a=await i;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),n=i(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return a(o(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),n=i(76790),s=i(50357),o=i(98553),a=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,s.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),n=null==i?[]:e(t,i);(0,r.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,n]of this.store.entries()){const s=(0,r.findIndexes)(n,(t=>!e(i,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function f(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=f,t.groupByValues=function(e,t){const i=f(e,t);return(0,n.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),n=i(22573),s=i(42279),o=i(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const f=e=>(t,i)=>a(t)&&a(i)&&e(t,i);function h(e,i,n){return!(null==n||!a(n))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,n)&&(0,t.gte)(i,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function M(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function _(e,t,i){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return a(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return h(t-r,t+r,e)},t.within=h,t.max_=function(...e){let t;for(const i of e)a(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,i){return b(e,(e=>b(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return a(e)?t(e):i},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=M,t.toPrecisionMaybe=function(e,t){return d(e,(e=>M(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=_,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return _(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||h(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!a(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(32639),a=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function f(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function h(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!h(e)}function p(e){return f(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??f(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,n.sort)(f(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const n={};for(const e of(0,r.uniq)((0,r.flatMap)(i,f)))n[e]=S(...i.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of f(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=f,t.keysWithDefinedValues=function(e){return null==e?[]:f(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=h,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,n]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==n&&!0!==i?.assignNullish||(e[r]=n));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,s.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function n(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:S(i,t)}for(const r of i){const[i,o]=(0,c.splitFirst)(r,"."),a=b(t,i);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const r of f(t))((0,l.toInt)(r)??-1)>=0&&n(r,e(t[r],...i));return r},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const n=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(n)?void 0:{key:n[0].key,value:(0,r.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(i,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=f(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,o.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of f(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>r(this.a,e,t,i)))))))}}function n(e){return e instanceof r||e===t.None}function s(e){return n(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=n,t.opt=s},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),n=i(30976),s=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,n.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,s.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),n=i(54993),s={};function o(e,t){if(t<1)return"";if(!(0,r.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),n=i(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,s=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==s&&"symbol"!==s)){const r=(0,n.toS)(e),s=(0,n.toS)(i),o=r.localeCompare(s);return r[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==s?a.indexOf(r)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const n of(0,r.toA)(await e))if(null!=n){const e=await n;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),n=i(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return null==i||0===i.length?s(e,t):a(e,t,1,i)[0]}function a(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(r??[]);if(t===e&&0===n&&0===o.size&&1===i)return[e];const a=n-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of a(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let n=null;for(;null!=(n=t.exec(e));)n.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,n.index)+i(n)+r.slice(n.index+n[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function n(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=n,t.swappableRotation=function(e){const t=n(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),n=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),r=o(t);return null==i||null==r?void 0:i>r?1:i{const i=o(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),n=i(17586),s=i(22573),o=i(96249),a=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let f;function h(){if(void 0===f)try{f=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{f=null}return f??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=h();return null!=r?(0,a.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=h();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),n=(0,c.toS)(t);return r.length===n.length&&(r===n||r.toLowerCase()===n.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=h();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const r=i?.maxLineLen??80,n=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),n).trim()).length<=r)return[t];const s=S(t," ",r);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),i)];{const r=t.indexOf(" ",n.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),n=i(68708),s=i(42279),o=i(83104),a=i(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,i(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,i(t))}catch(e){n&&(n=!1,r(e))}finally{clearTimeout(s)}}))}async function c(e,t,i=!0){const n=await u(e,t,i);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?o.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{r(await i())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),r(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(n)+")");return c(e,n,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,s.tot)(i);const n=await u(e,t,r);return n===o.Timeout?(0,s.tot)(i):n}},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),n=i(22573),s=i(54993);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,n.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,n.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),n=i(30301),s=i(31586),o=i(46891),a=i(50989),l=i(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,s.isNumber)(r)&&(i+=r/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],f=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function h(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),n=Math.pow(10,3*r),o=d[r];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,i=3){return h(e*t.MB,i)},t.fmtBytes=h,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),n=Math.pow(2,10*r),o=f[r];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,n=/\bFirefox\b/,s=/\biPad\b/,o=/\biPhone\b/;function a(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return a(e,i)}function u(e){return a(e,n)}t.isChrome=l,t.isSafari=function(e){return a(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return a(e,s)},t.isIphone=function(e){return a(e,o)}},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),n=i(22573),s=i(98553),o=i(31586),a=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,o.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,o.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,o.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,o.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,s.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,n.notBlank)(e.name)},t.TagRoots=(0,a.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),n=i(30301),s=i(31586),o=i(97238),a=i(29652);function l(e,i){const r=(0,a.toURLSearchParams)(e);if(i||!(0,s.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,a.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,n.lazy)(o.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),n=i(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),n=i(23541),s=i(59455),o=i(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,r.compact)((0,s.toA)(e).map(a))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,r.stringify)(e)}}t.toStr=s},61209:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainService=void 0;const d=c(i(1708)),f=i(19851),h=i(50213),m=i(54826),p=i(22911),g=i(27395),y=i(78406),v=i(25764),w=i(38836),S=i(99331),b=i(45608),P=i(73614),M=i(86335),_=i(55534),E=i(38835),T=i(70025),x=i(8769),D=i(83278),k=i(19652),C=i(85021),O=i(28874),I=i(2858),F=i(34238),L=i(51140),A=c(i(98604)),R=i(78932),N=i(69385),j=i(22573),B=i(38639),z=i(42659),V=i(26905),W=i(98553),U=i(55835),H=i(31586),G=i(68708),q=i(54993),$=i(37158);class J{constructor(){r.add(this),this.start=Date.now(),n.set(this,(0,f.lazy)((()=>(0,h.mkLogger)("MainService")))),this.httpPort=new p.Deferred("MainService.httpPort"),this.libraryDir=new p.Deferred("MainService.libraryDir"),s.set(this,void 0),o.set(this,void 0),this.setup=(0,f.lazy)((async()=>{await this.service.ready.catch((e=>(0,m.consoleError)("MainService.setup() failed: "+(0,V.errorToS)(e)))),l(this,s,await M.ChildService.mk_("web",{onStdout:e=>this.onWebout("stdout",e),onStderr:e=>this.onWebout("stderr",e),onData:e=>this.onWebData(e),onRestartPaused:()=>(0,b.exit)({reason:"Too many web service fatal errors",status:13})}),"f"),await(0,j.mapNotBlank)(O.Settings.pidFile.value,(async e=>{const t=D.BaseFile.for(e);u(this,n,"f").call(this).info("Writing to pidfile "+t,{pid:d.default.pid}),await t.writeText_((0,q.toS)(d.default.pid)),new w.EndableWrapper("remove pidfile",(()=>t.unlink()),v.EndableRanks.postdb)})),await this.service.ready;try{await(0,k.externalDirectoryCheck)()}catch(e){u(this,n,"f").call(this).warn("Failed to check external directory permissions",{error:e})}if(this.service.setInputHandler("--restart-sync",(()=>this.restartSync())),this.service.setInputHandler(C.HealthCheckCommand,(()=>u(this,r,"m",a).call(this))),null==u(this,s,"f"))return(0,x.onError)("Failed to start webservice"+E.FatalErrorFlag);this.httpPort.promise.then((e=>{const t=(0,A.default)(e),i=(1===t.length?" ":"\n - ")+t.map((e=>`${e}`)).join("\n - ");(0,m.consoleLog)(`PhotoStructure is ready:${i}`),O.Settings.exposeNetworkWithoutAuth.valueOrDefault||(0,m.consoleLog)("See https://photostructure.com/faq/remote-access/ to enable non-localhost access.")})),this.libraryDir.promise.then((e=>{(0,m.consoleLog)(`Your library is at <${F.URI.file(e)}>`)})),new w.EndableWrapper("shutdown notice",(()=>(0,m.consoleLog)("\nShutting down PhotoStructure...")),v.EndableRanks.first),(0,H.gt0)(O.Settings.healthCheckIntervalMs.valueOrDefault)&&new y.EndableInterval({name:"webSyncHealthChecks",intervalMs:O.Settings.healthCheckIntervalMs.valueOrDefault,callback:()=>u(this,r,"m",a).call(this)})})),this.service=new $.Service("main"),this.setup(),(0,P.setUnrefTimeout)((()=>{this.httpPort.isPending&&!(0,S.ending)()&&(0,m.consoleLog)("Please wait, setting up...")}),4*z.secondMs)}async webHealthCheck(){const e=this.httpPort.value;if(null!=e)try{const t=await(0,R.httping)("localhost",e,"/ping",3*z.secondMs);return!!L.HttpStatusIs.success(t)||(u(this,n,"f").call(this).warn("webHealthCheck(): web service returned "+t),!1)}catch(e){return u(this,n,"f").call(this).warn("webHealthCheck(): httping error: "+e),!1}else u(this,n,"f").call(this).info("webHealthCheck(): no-op, no http port set (web is starting up still)")}onWebout(e,t){return u(this,n,"f").call(this).info("onWebout",{pipe:e,error:t}),t===_.ServiceExitCommand?(0,b.exit)({reason:"Web service exit command",status:0}):(t??(t=""),/EADDRINUSE/i.test(t)||t.includes(E.WebFatalErrorFlag)||(0,T.isFatalError)(t)?(0,b.exit)({status:1,reason:"Web service error",error:t}):this.onWebData((0,W.parseJSON)(t)))}async onWebData(e){(0,j.blank)(e)||(u(this,n,"f").call(this).info("onWebData",{input:e}),(0,U.map)(e[O.Settings.httpPort.key],(e=>{u(this,n,"f").call(this).info("Got HTTP port number from web service:"+e),O.Settings.httpPort.envValue=e,this.httpPort.maybeResolve(e)})),(0,B.mapBoolean)(e.pause,(e=>e?(0,N.pause)():(0,N.resume)())),await(0,B.mapTrue)(e.shutdown,(()=>(0,b.exit)({reason:"shutdown requested",status:0}))),await(0,B.mapTrue)(e.shutdownSync,(()=>this.shutdownSync())),(0,B.isTrue)(e.forceRestartSync)?await this.forceRestartSync():(0,B.isTrue)(e.restartSync)&&await this.restartSync())}async shutdownSync(){const e=u(this,o,"f");return l(this,o,void 0,"f"),u(this,n,"f").call(this).info("shutdownSync()",{syncWasDefined:null!=e}),(0,g.end)(e)}async forceRestartSync(){return this.restartSync()}async restartSync(){const e=(0,h.mkLogger)("MainService.restartSync()");if((0,S.ending)())return void e.info("ending, no-op");const t=u(this,o,"f");if(e.info("priorSync",(0,U.map)(t,(e=>(0,G.pick)(e,"pid","name")))),await(0,g.end)(t),l(this,o,void 0,"f"),await(0,I.readSystemSettings)(),!I.libraryHasSettings.refresh())return void e.info("restartSync(): no library settings",{libraryDir:O.Settings.libraryDir.value});const i=l(this,o,await M.ChildService.mk_("sync"),"f");e.info("Started sync",(0,U.map)(i,(e=>(0,G.pick)(e,"pid","name"))))}}t.MainService=J,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(){!1===await this.webHealthCheck()?await u(this,s,"f").restart():u(this,s,"f").runHealthCheck(),u(this,o,"f")?.runHealthCheck()},J.instance=(0,f.lazy)((()=>new J))},18449:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(7282),n=i(96706),s=i(29325),o=i(28874);t.sentryEnabled=function(){return(0,n.isEnvTrue)("ENABLE_SENTRY")||(0,r.isProd)()&&(0,s.isPacked)()&&!0===o.Settings.reportErrors.value}},95629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const a=s(i(16436)),l=o(i(48161)),u=o(i(1708)),c=i(19851),d=i(19043),f=i(50213),h=i(31578),m=i(7282),p=i(96175),g=i(23560),y=i(84968),v=i(81168),w=i(37805),S=i(25764),b=i(38836),P=i(99331),M=i(85100),_=i(98314),E=i(68301),T=i(70025),x=i(8769),D=i(34102),k=i(34592),C=i(42042),O=i(34474),I=i(20839),F=i(57902),L=i(45969),A=i(43334),R=i(40958),N=i(22573),j=i(42659),B=i(41400),z=i(98553),V=i(55835),W=i(12168),U=i(59455),H=i(54993),G=i(18449),q=(0,c.lazy)((()=>(0,f.mkLogger)("Sentry")));function $(e){(0,G.sentryEnabled)()&&null!=e&&!0!==(0,T.isDoNotSendError)(e)&&a.captureException(e)}t.installSentry=async function(e){try{return!!(0,G.sentryEnabled)()&&(a.init({dsn:A.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:(0,m.nodeEnv)(),maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,x.onError)("sentry.onFatalError",e)}),q().info("Sentry initialized",{isElectron:A.isElectron}),!0)}catch(e){return q().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,G.sentryEnabled)())return q().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(E.ErrorStore.instance()?.eventQuotaExceeded(e)))return q().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,T.isDoNotSendError)(i))return q().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await X(e);return await(E.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,D.ee)().on("fatal",$),(0,D.ee)().on("nonFatal",$),new b.EndableWrapper("EventFilter",(()=>this.end()),S.EndableRanks.first)}end(){return(0,V.map)(a.getCurrentHub().getClient(),(e=>e.close(5*j.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Z(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Z(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,H.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,L.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,h.memoryUsageMb)(),i.memoryUsageRssMb=(0,h.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,k.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/j.secondMs,...e}}async function Q(){await(0,B.delay)(3*I.DefaultLogFlushMs);const e=await(0,O.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/j.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Z,t.sentryExceptionToS=Y,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[F.LogLevels.fatal,"fatal"],[F.LogLevels.error,"error"],[F.LogLevels.warn,"warning"],[F.LogLevels.info,"info"],[F.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},37158:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const p=m(i(29907)),g=m(i(1708)),y=i(57206),v=i(19851),w=i(50213),S=i(59880),b=i(23560),P=i(19913),M=i(71567),_=i(37805),E=i(38836),T=i(99331),x=i(45608),D=i(56038),k=i(55534),C=i(42499),O=i(49776),I=i(96706),F=i(98314),L=i(38835),A=i(70025),R=i(8769),N=i(57159),j=i(34102),B=i(33456),z=i(87408),V=i(85021),W=i(17181),U=i(86941),H=i(28874),G=i(41692),q=i(2858),$=i(69385),J=i(22573),K=i(42659),Z=i(41400),Y=i(56409),X=i(55835),Q=i(41583),ee=i(54993),te=i(95629);t.setupEventHandlers=(0,v.lazy)((()=>{(0,j.ee)().on("resume",(()=>(0,$.resume)())),(0,j.ee)().on("pause",(()=>(0,$.pause)()))}));class ie extends E.EndableWrapper{constructor(e){super(e),r.add(this),n.set(this,void 0),s.set(this,new Y.Latch),o.set(this,new Map),this.setup_=(0,v.lazy)((()=>(0,D.time)("Service.setup",(()=>h(this,r,"m",a).call(this))))),u.set(this,(0,v.lazy)((()=>{const e=g.default.stdin.pipe(new B.LineReader);return e.on("data",(e=>h(this,r,"m",d).call(this,(0,ee.toS)(e)))),e}))),(0,b.isBillingService)()||(0,G.setSettingsDefaults)(),f(this,n,(0,w.mkLogger)("Service("+this.name+")"),"f"),h(this,r,"m",c).call(this),this.setup_()}get name(){return super.name}get ready(){return h(this,s,"f").promise}get isReady(){return h(this,s,"f").isResolved()}setInputHandler(e,t){h(this,o,"f").set(e.trim().toLowerCase(),t)}}t.Service=ie,n=new WeakMap,s=new WeakMap,o=new WeakMap,u=new WeakMap,r=new WeakSet,a=async function(){try{(0,J.mapNotBlank)((0,I.getEnv)("PS_FATAL_"+this.name),(e=>{throw new N.WrappedError(e,{fatal:!0})})),(0,J.mapNotBlank)((0,I.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new N.WrappedError(e)}),5*K.secondMs)})),(0,P.setServiceName)(this.name),(0,S.setProcessTitle)(),(0,b.isMainService)()&&await(0,U.mergeUserDataDirs_)(),await(0,q.readSettings)(),await h(this,r,"m",l).call(this),(0,W.setupLogger)(),(0,y.addDefaultJsonRevivers)(),(0,O.cacheDir)(),(0,t.setupEventHandlers)(),h(this,u,"f").call(this),await(0,C.setupLuxon)(),H.Settings.startPaused.valueOrDefault&&(0,$.pause)(),(0,T.ending)()?h(this,s,"f").reject():h(this,s,"f").resolve()}catch(e){console.error((0,F.errorToS)(e)),h(this,s,"f").reject((0,Q.toErr)(e)),(0,x.exit)({reason:(0,A.addErrorFlags)(this.name+" setup failed: "+(0,F.errorToS)(e),L.FatalErrorFlag),status:14})}},l=async function(){(0,b.isPermaService)()||(0,j.ee)().on("fatal",(e=>(0,x.exit)({error:e,status:12}))),g.default.on("unhandledRejection",(e=>(0,X.map)(e,(e=>(0,R.onError)("unhandledRejection",e))))),g.default.on("uncaughtException",(e=>(0,X.map)(e,(e=>(0,R.onError)("uncaughtException",e))))),g.default.on("SIGINT",(()=>(0,x.exit)({reason:"SIGINT",status:0}))),g.default.on("SIGHUP",(()=>(0,x.exit)({reason:"SIGHUP",status:0}))),g.default.on("SIGTERM",(()=>(0,x.exit)({reason:"SIGTERM",status:0}))),p.default.isWorker&&g.default.on("disconnect",(()=>(0,x.exit)({reason:"disconnect",status:0}))),await(0,te.installSentry)(this)},c=function(){this.setInputHandler("--version",(()=>(0,M.stdoutWrite)({version:_.version}))),this.setInputHandler(k.ServiceExitCommand,(()=>(0,Z.later)((()=>(0,x.exit)({reason:k.ServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,M.stdoutWrite)(D.PromiseTimer.instance().report()))),this.setInputHandler(V.HealthCheckCommand,(async()=>(0,M.stdoutWrite)(await(0,z.getStatusSummary)({refresh:!0}))))},d=async function(e){if(h(this,n,"f").debug("onLine()",{line:e,ending:this.ended||(0,T.ending)()}),await this.setup_(),e.startsWith("--")){const t=e.split(/\s+/,1)[0],i=h(this,o,"f").get(t);null==i?(h(this,n,"f").error("onLine(): unknown command",{line:e,knownCommands:[...h(this,o,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else h(this,n,"f").error("onLine(): failed to process",{line:e})}},38530:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DaemonArgs=void 0;const n=i(58587),s=i(31421),o=r(i(1708)),a=i(9727),l=i(83278),u=i(95402),c=i(28874),d=i(2858),f=i(22573),h=i(38639),m=i(31586);t.DaemonArgs={beforeParse:e=>e.option("-p, --pidfile PIDFILE","Write a pidfile of the main process.").option("--stop","Shutdown daemonized PhotoStructure. Requires --pidfile").option("-d, --daemon","Run PhotoStructure as a daemon. Enabled by default when --pidfile is provided."),afterParse:async e=>{if((0,f.mapNotBlank)(e.pidfile,(e=>c.Settings.pidFile.envValue=e)),(0,h.isTrue)(e.stop)){if(!c.Settings.pidFile.hasValue()&&(await(0,d.readSystemSettings)(),!c.Settings.pidFile.hasValue()))return console.error("--stop requires --pidfile to be set."),o.default.exit(1);const e=l.BaseFile.for(c.Settings.pidFile.value);if(await e.notExists())return console.error("Pidfile "+e+" does not exist."),o.default.exit(1);const t=(0,m.toInt)(await e.readTextFile());return(0,m.gt0)(t)?(0,n.pidExists)(t)?(await(0,u.killPid)(t),o.default.exit(0)):(console.error("Pid "+t+" does not exist."),o.default.exit(1)):(console.error("Pidfile "+e+" is invalid."),o.default.exit(1))}if(!(0,h.isTrue)(o.default.env.__is_daemon)&&((0,h.isTrue)(e.daemon)||c.Settings.pidFile.hasValue())){const e=o.default.argv.findIndex((e=>!e.includes("npx")&&!e.includes("node"))),t=o.default.argv.slice(-1===e?0:e),i=process.execPath,r={...(0,a.childEnv)(),__is_daemon:"1"},n=(0,s.spawn)(i,t,{env:r,detached:!0,shell:!0});return n.unref(),console.log("Daemonized PhotoStructure.",{pid:n.pid,args:t}),o.default.exit(0)}}}},98392:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExposeArg=void 0;const r=i(28874),n=i(38639);t.ExposeArg={beforeParse:e=>e.option("--expose","The web service is only accessible to the computer running PhotoStructure by default. Providing this option will expose your library to all computers on your network. See https://photostructure.com/faq/remote-access/ ."),afterParse:e=>{(0,n.isTrue)(e.expose)&&(r.Settings.exposeNetworkWithoutAuth.envValue=!0)}}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),n=i(83210),s=i(28874),o=i(38639);function a(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(a()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return a()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),a()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,o.isTrue)(e.error),i=(0,o.isTrue)(e.warn),r=(0,o.isTrue)(e.info)||(0,o.isTrue)(e.verbose)||(0,o.isTrue)(e.v),l=(0,o.isTrue)(e.debug),u=(0,o.isTrue)(e.trace);u?s.Settings.logLevel.envValue="trace":l?s.Settings.logLevel.envValue="debug":r?s.Settings.logLevel.envValue="info":i?s.Settings.logLevel.envValue="warn":t&&(s.Settings.logLevel.envValue="error"),(0,n.isDaemon)(e)?(s.Settings.tailLogs.envValue=!1,s.Settings.logStdout.envValue=!1):((0,o.isTrue)(e.tail)&&(s.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(s.Settings.logStdout.tmpValue=!0,a()&&(s.Settings.tailLogs.tmpValue=!0)),(s.Settings.tailLogs.valueOrDefault||s.Settings.logStdout.valueOrDefault)&&s.Settings.logLevel.isUnset()&&(s.Settings.logLevel.envValue="info"))}}},12195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoFilterArg=void 0;const r=i(4175),n=i(38639);t.NoFilterArg={beforeParse:e=>e.option("--no-filter","Disables import filters. All paths will try to be imported, even if they are too small or are missing tags. See https://photostructure.com/faq/why-is-my-file-missing/ ."),afterParse:async e=>{(0,n.isFalse)(e.filter)&&(0,r.disableAllFilters)()}}},33321:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PauseSyncArg=void 0;const r=i(28874),n=i(38639);t.PauseSyncArg={beforeParse:e=>e.option("--pauseSync","Pause sync processing until manually resumed via the system tray or nav menu."),afterParse:e=>{(0,n.isTrue)(e.pauseSync)&&(r.Settings.startPaused.envValue=!0)}}},51088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MainArgs=void 0;try{i(93944).install()}catch{}const r=i(69554),n=i(43380),s=i(28874),o=i(38639),a=i(5670),l=i(61209),u=i(38530),c=i(98392),d=i(31503),f=i(12195),h=i(33321);t.MainArgs={beforeParse:e=>e.option("--quiet","Don't emit lifecycle messages to stdout from the main service."),afterParse:e=>{(0,o.isTrue)(e.quiet)&&(s.Settings.quiet.tmpValue=!0)}},async function(){try{await new r.CLI(a.ServiceNames.main).add(t.MainArgs,c.ExposeArg,h.PauseSyncArg,u.DaemonArgs,f.NoFilterArg,n.WriteSettingsArg,d.LogArgs).parse(),new l.MainService}catch(e){console.error("Failed to start:")}}()},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},16436:e=>{"use strict";e.exports=require("@sentry/node")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},51168:e=>{"use strict";e.exports=require("luxon")},4927:e=>{"use strict";e.exports=require("papaparse")},22915:e=>{"use strict";e.exports=require("platform-folders")},57272:e=>{"use strict";e.exports=require("plist")},85949:e=>{"use strict";e.exports=require("process")},90595:e=>{"use strict";e.exports=require("punycode")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},93944:e=>{"use strict";e.exports=require("source-map-support")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},29907:e=>{"use strict";e.exports=require("cluster")},76982:e=>{"use strict";e.exports=require("crypto")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__=__webpack_require__(51088);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:n}=i(60308),{decode:s}=i(47859),o=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:a,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new n("unsupported PASETO version");if("local"!==a&&"public"!==a)throw new n("unsupported PASETO purpose");const d={footer:u?s(u):void 0,payload:void 0,version:i,purpose:a};if("local"===a)return d;const f="v1"===i?256:"v3"===i?96:64;let h;try{h=s(l).subarray(0,-f)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?o(h):h,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:n,jti:s,kid:o,notBefore:a,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(a))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.issuer must be a string");c.iss=n}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.kid must be a string");c.kid=o}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.jti must be a string");c.jti=s}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),n=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:s,subject:o,issuer:a,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const f=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.issuer must be a string");if(d.iss!==a)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.subject must be a string");if(d.sub!==o)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const h=l?n(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>f+h)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>f+h)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=f-h)throw new r("token is expired")}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+n(s){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),n=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!n(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),n=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,n),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:n}=i(60308),s=i(10968),{decode:o}=i(47859),a=i(40816);e.exports={post:function(e,t,i,r,n,o,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:n,footer:o?.length?o:void 0,version:e,purpose:l}:n}const u=a(n);return s(i,u),r?{payload:u,footer:o?.length?o:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new n(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:s="",length:a}=t.slice(e.length).split(".");try{r(a<=2),i=o(i),s=o(s)}catch{throw new n("token is not a PASETO formatted value")}return{raw:i,f:s}}}},56463:(e,t,i)=>{const r=i(76982),n=i(92460),s=i(70761),o=i(29534),{PasetoDecryptionFailed:a}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=n.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),f=Buffer.from("paseto-auth-key-for-aead"),h=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:n.promisify(r.sign),verify:n.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const n="v1.local.",a=m(e,r.randomBytes(32)).subarray(0,32),l=a.subarray(0,16),[u,h]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,f,32).then(Buffer.from)]),p=await g(e,u,a.subarray(16)),y=s(n,a,p,t),v=m(y,h);return o(n,t,a,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),n=e.subarray(-48),o=e.subarray(32,-48),u=r.subarray(0,16),[h,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,f,32).then(Buffer.from)]),g=s("v1.local.",r,o,t),v=m(g,p);if(!l(n,v))throw new a("decryption failed");const w=await y(o,h,r.subarray(16));if(!w)throw new a("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,n){const a="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,h,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,h,Buffer.concat([f,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),S=s(a,l,w,t,n),b=m(S,p);return o(a,t,l,w,b)},"v3.local-decrypt":async function(e,t,i,r){const n=e.subarray(0,32),o=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,h,Buffer.concat([d,n]),48).then(Buffer.from),c("sha384",i,h,Buffer.concat([f,n]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),S=s("v3.local.",n,u,t,r),b=m(S,g);if(!l(o,b))throw new a("decryption failed");const P=await y(u,v,w);if(!P)throw new a("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:n}=i(75162);n||(n=e=>null!=e&&e instanceof r),e.exports=n},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,n=Buffer.allocUnsafe(8);return n.writeUInt32LE(t,4),n.writeUInt32LE(i,0),n}},85223:e=>{const t=36e5,i=24*t,r=7*i,n=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const s=n.exec(e);if(!s)throw new TypeError(`invalid time period format ("${e}")`);const o=parseFloat(s[1]);switch(s[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*o);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*o);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(o*t);case"day":case"days":case"d":return Math.round(o*i);case"week":case"weeks":case"w":return Math.round(o*r);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*o)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let n=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(n+=`.${r(t)}`),n}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:n}=i(64770),s=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return n(s(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),n=i(70761),s=i(29534);e.exports=async function(e,t,i,o,a,l,u){const c=n(u,e,t,i,l),d=await r(o,c,a);return s(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),n=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!n(t))try{t=r(t)}catch{}if(!n(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),n=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(n(e,i),n(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:n}=i(56463),s=i(70761),{pre:o}=i(88965);e.exports=async function(e,t,i,a,l,u,c){const{raw:d,f}=o(e,t),h=d.subarray(0,-a),m=d.subarray(-a),p=s(c,e,h,f,u);if(!await n(i,p,l,m))throw new r("invalid signature");return{m:h,footer:f.length?f:void 0}}},91227:(e,t,i)=>{const r=i(60308),n=i(79665),s=i(56120),o=i(50015),a=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:n,V2:s,V3:o,V4:a,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),n=i(495).bind(void 0,"v1.local"),{pre:s,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:a=!1,...l}={}){const{raw:u,f:c}=s("v1.local.",e),d=(t=n(t)).export(),f=await r(u,c,d);return o("v1",a,l,i,f,c,"local")}},21472:(e,t,i)=>{const r=i(83561),n=i(495).bind(void 0,"v1.local"),s=i(1658),{"v1.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=n(t);const u=r(i),c=t.export();return o(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),n=i(77256),s=i(21472),o=i(39324),a=i(70866);e.exports={sign:r,verify:n,encrypt:s,decrypt:o,generateKey:a}},70866:(e,t,i)=>{const r=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:s}=i(60308),o=n(r.generateKeyPair),a=n(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await a("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await o("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new s("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPrivateKey:s}=i(76982),o=i(83561),a=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=a(e,c),f=o(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=s(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,f,"sha384",{key:t,padding:r,saltLength:n})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:n},createPublicKey:s}=i(76982),o=i(49826),a=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!a(e)||"private"===e.type)try{e=s(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:f}=await o("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:n});return l("v1",u,c,i,d,f,"public")}},56120:(e,t,i)=>{const r=i(88451),n=i(859),{generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}=i(62827);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}},62827:(e,t,i)=>{const r=i(64770),n=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:o}=i(60308),a=i(70981),l=s(n.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${f(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${f(r).toString("base64url")}`}:t}throw new o(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=n.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return n.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!a(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function f(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!a(t))try{t=n.createPrivateKey(t)}catch{}if(!a(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!a(t)||"private"===t.type)try{t=n.createPublicKey(t)}catch{}if(!a(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:f}},88451:(e,t,i)=>{const r=i(83561),n=i(1658),s=i(92366),{_checkPrivateKey:o}=i(62827),a=o.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=a(t);const u=r(i);return s("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:n}=i(62827),{post:s}=i(88965),o=n.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,...a}={}){t=o(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return s("v2",n,a,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),n=i(495).bind(void 0,"v3.local"),s=i(80608),{pre:o,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f}=o("v3.local.",e);t=n(t);const h=s(u),m=t.export(),p=await r(d,f,m,h);return a("v3",l,c,i,p,f,"local")}},43406:(e,t,i)=>{const r=i(83561),n=i(495).bind(void 0,"v3.local"),s=i(1658),o=i(80608),{"v3.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=s(e,u);t=n(t);const d=r(i),f=o(l),h=t.export();return a(c,d,h,f)}},50015:(e,t,i)=>{const r=i(42438),n=i(65466),s=i(43406),o=i(18582),{generateKey:a,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:n,encrypt:s,decrypt:o,generateKey:a,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:s}=i(60308),o=i(70981),a=i(82115),l=n(r.generateKeyPair),u=n(r.generateKey);function c(e){if(!o(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return a(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new s("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),n=i(83561),s=i(1658),o=i(80608),a=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...f}={}){const h=s(e,f),m=n(i),p=o(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),a("v3.public.",h,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),n=i(80608),s=i(49826),o=i(70981),{bytesToKeyObject:a}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...f}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=a(e)}catch{}if(!o(e)||"private"===e.type)try{e=r(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const h=n(d),{m,footer:p}=await s("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},h,l(t));return u("v3",c,f,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),n=i(77933),{generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}=i(24961);e.exports={sign:r,verify:n,generateKey:s,bytesToKeyObject:o,keyObjectToBytes:a}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:n,_generateKey:s,_keyObjectToBytes:o,bytesToKeyObject:a}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:n,bytesToKeyObject:a,generateKey:async function(...e){return s("v4",...e)},keyObjectToBytes:function(...e){return o("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),n=i(1658),s=i(80608),o=i(92366),{_checkPrivateKey:a}=i(24961),l=a.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:a,...u}={}){const c=n(e,u),d=s(a);t=l(t);const f=r(i);return o("v4.public.",c,f,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),n=i(49826),{_checkPublicKey:s}=i(24961),{post:o}=i(88965),a=s.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,assertion:l,...u}={}){t=a(t);const c=r(l),{m:d,footer:f}=await n("v4.public.",e,void 0,64,t,c);return o("v4",s,u,i,d,f,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),n=i(22573),s=i(38639);function o(){return(0,s.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,n.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),n=i(7282),s=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),n=i(36783),s=i(76790),o=i(22573),a=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),f=i(34666),h=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const n=new Set(t.map(i));return e.filter((e=>n.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,f.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,f.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return T(e,t,i).index}function T(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let r=0;re.slice(i,i+t)))}async function D(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,h.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,h.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,h.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let n=0;for(const s of e)(t(s,n++)?i:r).push(s);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=T(e??[],t,f.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=x,t.collectBatched=function(e,t,i){const n=[];for(const s of x((0,r.compact)((0,h.toA)(e)),t))n.push(...(0,r.compact)(i(s)));return n},t.collectBatchedAsync=async function(e,t,i){const n=[];for(const s of x((0,r.compact)((0,h.toA)(e)),t))n.push(...(0,r.compact)(await i(s)));return n},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await D(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+n;if(re+1),1));return(0,h.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=i(77988),l=o(i(1708)),u=i(19851),c=i(42659),d=i(55835),f=i(31586),h=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),S=i(99331),b=i(95937),P=i(98314),M=i(38835),_=i(70025),E=i(8769),T=i(43334),x=i(95402),D=i(28874),k=i(63870);class C extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,r,"m",n).call(this)),i,"worker"===e?(0,k.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const o=t;o.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,x.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new h.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+M.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,i,r)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,f.gt0)(e?.pid)&&x.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,_.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,E.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,r=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(T.isWin?3:1)*c.minuteMs,maxTasksPerProcess:D.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:D.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:D.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,k.commandTimeoutMs)(),taskTimeoutMillis:D.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class f{constructor(e){if(r.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,r,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,r,"m",a).call(this,0,(e=>{var t,i;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(i=u(this,s,"f"),--i),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const i=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=f},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of n)if(o(e,t))return e.subarray(t.length).toString(i);return e.toString()}function o(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,r.toS)(e)},t.bufferStartsWith=o},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class n{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=i(40958),a=i(23838),l=s(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,n=-1;for(const[i,s]of this.m.entries()){const o=(0,c.diceCoeff)(i,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(r=e,n=o)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),n=i(31586),s=i(68708),o=i(54993),a=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,n]of this.m.entries()){const s=e(r);t.fill(s,i,i+n),i+=n}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),n=i(72993),s=i(45969),o=i(43334);t.EditionType=(0,r.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),n=i(55835),s=i(68708);var o=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,s.omit)(e,...i),(0,s.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,n.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),n=i(19851),s=i(95696);t.examples=(0,n.lazy)((()=>s.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),n=i(65843),s=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,n.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),n=i(40958),s=i(55835),o=i(31586),a=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),f=i(54993),h=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new h.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(i=l(this,n,"f"),++i),"f"),c.promise):(u(this,r,(o=l(this,r,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(a=l(this,r,"f"),++a),"f"),c}get(e){var t,i;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,f.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(r=l(this,a,"f"),++r),"f")})),r.promise}},r=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class f{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const h=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,r).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new f(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,a=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(a,r.index);(0,s.blank)(l)||(h().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),f=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==f)this.skippedHeaders.push(m),h().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:f});else{const e=(0,n.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=f}a=t.lastIndex}const l=(0,n.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),n=i(20014),s=i(55222),o=i(97352),a=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,o.within)(-90,90,e)&&0!==e}function c(e){return(0,o.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function f(e,t,i=a){return(0,r.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=a){return f(e?.lat,e?.lon,t)},t.geohash=f,t.geohashNumericShort=function(e,t){return m(e,t,30)};const h=new n.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=a){return d(e,t)?h.zip([t,e],l(i)):void 0}function p(e,t=a){return h.unzip(e,l(t))?.reverse()}function g(e,t=a){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=a){return(0,r.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,n=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,o=Math.sin(n/2)*Math.sin(n/2)+Math.cos(i)*Math.cos(r)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),n=i(98553);var s=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,n.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,r.readFile)(e)).toString())}},57206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(77988),n=i(51168),s=i(45599),o=i(98553),a=i(68708),l=i(24689),u=i(21330),c=i(57159),d=i(28544),f=(0,s.defer)((()=>{n.DateTime.prototype.toJSON=function(){return(0,a.compactValues)({_ctor:n.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),h={name:n.DateTime.name,fromJSON:e=>n.DateTime.fromMillis(e.ts,(0,a.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,s.defer)((()=>{f(),(0,o.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,h,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},19851:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=i(57975),a=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new f(e,t)};class f extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,r,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(42659),a=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),f=i(44198),h=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,f.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,n.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*o.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,h.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),n=i(1708),s=i(45599),o=i(68708),a=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),f=i(37805),h=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,s.defer)((()=>{(0,a.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:f.version,StartTs:d.StartTs,argv:n.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,o.pick)(n.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:n.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,h.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),n=i(32105),s=i(14593);t.rootLoggers=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,r.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),n=i(55835),s=i(59455),o=i(48884);function a(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,o.concat)(...e.map((e=>t(e)))))},t.compactMap=a,t.toMap=function(e,t){return a((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:a(await Promise.all((0,r.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,n.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),n=i(54557);t.memoize=function(e,t){let i=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return i++,s.getOrSet((0,r.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,r.stringify)(e)),o.size=()=>s.size,o.callCount=()=>i,o}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),n=i(31586),s=i(12168),o=i(70417);function a(){const e=(0,r.memoryUsage)();return(0,o.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=a,t.memoryUsageMb=function(){return(0,n.sigFigs)(a()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,n.sigFigs)(l()/s.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=r(i(1708)),s=i(38639),o=i(54993),a=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(55835),a=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function f(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=f,t.mapGte0Or=function(e,t,i){return(0,o.orElse)(f(e,t),i)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=r&&r>0&&null!=n&&n>0?i(r,n):void 0};const h=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(h.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function p(e){return(0,a.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const n=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),n=i(42659),s=i(96249),o=i(55835),a=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),f=i(81168);function h(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,n]of(0,l.entries)(e)){const e=t(r,n);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=h,t.tryEach=function(e,t){[...e].forEach((e=>h((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const n of t)r[n]=i(n,e[n]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let n=0;for(const s of(0,l.keys)(e))if(r[s]=t(s,e[s]),n++,(0,a.gt)(n,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,f.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,s.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),n=i(73024),s=i(48161),o=i(19851),a=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),f=i(48884),h=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,o.lazy)((()=>(0,h.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,o.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return O();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,o.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,n.readFileSync)(e).toString();if((0,a.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,o.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,a.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,o.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const T={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},x={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),n=t[i];return(0,c.isString)(n)?n:n?.[r]}const k=(0,o.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,a.mapNotBlankOr)(function(e=k()){return D(e,T)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function O(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,x);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=O,t.CPUs=(0,o.lazy)((()=>(0,f.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,o.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(O())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=r(i(48161)),s=i(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(72993),n=i(50213),s=i(23560),o=i(43334);let a=!o.isElectron;t.setShortProcessNames=function(e){a=e},t.setProcessTitle=function(){try{const e=[a?r.SimpleShortAppName:r.SimpleAppName];(0,s.isMainService)()&&o.isElectron||e.push((0,s.serviceName)());const t=e.join(o.isElectron?" ":"-");i(85949).title=t}catch(e){(0,n.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},92782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),n=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,n.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,n.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),n=i(56409),s=i(31586),o=i(22911),a=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,f,h=!1,m=0;t=Math.ceil(t);const p=[];function g(){return h||m>Date.now()}function y(){if(null!=f){const e=f;f=void 0,w(...e)}}async function v(...r){h=!0,m=Date.now()+(0,s.max_)(t,i);const n=d=new o.Deferred(c);(0,s.gt0)(i)&&n.setTimeout(i);try{n.resolve(await e(...r))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{h=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return n.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return f=e,(0,r.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{f=void 0},w.donePromise=()=>{if(!h)return Promise.resolve();const e=new n.Latch;return p.push(e),e},w.force=async(...e)=>(f=void 0,h&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:h,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),n=i(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(n,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(s(t))}const n=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,i)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,r||(r=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):i+=s((0,n.toS)(t));return new RegExp(i,t??(r?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=r(i(48161)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),f=i(51926),h=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),S=i(24399),b=i(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,f.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,o.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return n.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(h.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=r(i(1708)),s=i(19851),o=i(40958),a=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function p(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||f(e)},t.isMainService=d,t.isWebService=f,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=h,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||f()||((0,u.isTest)()||p())&&!h()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!f()&&!d()&&!h()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function n(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=n(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=n(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),n=i(57150),s=i(7282),o=i(23560),a=i(17181);t.setServiceName=function(e){(0,o.isMainService)(e)&&(e=r.ServiceNames.main);const t=o.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),o.serviceName.set(e),(0,a.setupLogger)(),(0,n.logStartup)())}},28850:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const a=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends a.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),n.set(this,void 0),s(this,r,e,"f")}_call(){return(0,l.time)(o(this,r,"f")+(null==o(this,n,"f")?"(local)":"(remote)"),null==o(this,n,"f")?this.impl():o(this,n,"f").call(this))}setShim(e){s(this,n,e,"f")}hasShim(){return null!=o(this,n,"f")}clearShim(){s(this,n,void 0,"f")}}r=new WeakMap,n=new WeakMap},12089:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),f=i(54993),h=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends h.ExtensibleFunction{constructor(e,t,i,o){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",o).call(this,e),(()=>u(this,r,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,r=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,f.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=i(76790),o=i(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return n(this,r,"f")[Symbol.iterator]()}get length(){return n(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=n(this,r,"f").length-1;for(;t<=i;){const s=t+Math.floor((i-t)/2),o=this.valueOf(n(this,r,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:i=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...n(this,r,"f")];const o=t=>t<0||t>n(this,r,"f").length-1?null:(i??this.diff)(n(this,r,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const f=[];for(;f.lengththis.valueOf(e)))}shift(){return n(this,r,"f").shift()}at(e){return(0,o.at)(n(this,r,"f"),e)}toA(){return[...n(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,r,"f").length-1){const e=[...n(this,r,"f")];return n(this,r,"f").length=0,e}return n(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),n=i(82328),s=i(84542),o=i(95705),a=i(28874);t.consoleLog=function(e,...t){a.Settings.quiet.valueOrDefault||(0,n.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e){a.Settings.quiet.valueOrDefault||(0,o.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=a.Settings.quiet.envValue;try{return a.Settings.quiet.envValue=!0,await e()}finally{a.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),n=i(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=r(i(1708)),s=i(22573),o=i(98553),a=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function f(e,t){return h({obj:e,ready:t,stream:n.default.stdout})}function h({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);r.write(n+"\n"),(0,a.isWorkerService)()&&null!=i&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=f,t.stderrWrite=function(e){return h({obj:e,stream:n.default.stdout})},t.writeTTY=h,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);f(t)},t.stdoutWriteMigration=function(e){return f({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>f({shutdownSync:!0}),restartSync:()=>f({restartSync:!0}),forceRestartSync:()=>f({forceRestartSync:!0}),rebuildLibrary:()=>f({rebuildLibrary:!0}),shutdown:()=>f({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(55835),a=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),f=i(54993),h=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,f.toS)(e),t=(0,f.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,f.toS)(e).indexOf((0,f.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const n=t.indexOf(i,r);return-1===n?0:1+e(t,i,n+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(f.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,a.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,f.toS)(e),t=(0,f.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,f.toS)(e),n=(0,f.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(r.slice(-n.length),n,i)?r.slice(0,-n.length):r},t.gist=function(e,t=80,i=80){const r=(0,f.toS)(e),n=r.length-(t+i);return n<=0?r:r.slice(0,t).trim()+" …(+"+n+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,f.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,f.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,f.toS)(e))},t.capitalize=function(e){return e=(0,f.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,o.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),n=t.indexOf(r);if(n>=0)return{index:n,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,h.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,f.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,f.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const T=/^['‘’].*['‘’]$/,x=/^["“”„«»〃].*["“”„«»〃]$/;function D(e,t){const i=k(e,t);return(0,h.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,i.push(e.substring(s,n.index)),r.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,f.toS)(e).trim(),T.test(e)||x.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),n=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,o.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,f.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,f.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,n.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(f.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,s.blank)(r))for(const e of r.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>r.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function n(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=r(i(77598)),s=i(73913),o=i(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=o.Radix58,r=224){return i.encodeBuffer(a(e,r)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=o.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(31586),a=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),f=i(88158),h=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,n="";for(let s=0;s=r&&(r=i.get(s,o),n=(0,l.substr)(e,s-r+1,r)));return n}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),n=t.normalize();return e!==r||t!==n?y(r,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,f.firstThunk)((()=>i===r?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,h.intersection)(e,t),n=[];return i.forEach((i=>{const s=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,o.times)(s,(()=>n.push(i)))})),n}function b(e,t,i){const n=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,n))-i((0,l.strslice)(t,n))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,r,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,r,(e=>c.RadixAlphaNum.decode(e)))}function T(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const n=(0,o.mapNumericOr)(e.charCodeAt(r),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(r),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);i=null==i?a:(i+a)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=T,t.paddedPositionalDiff=function(e,t,i=8){return T((0,a.leftPad)(e,i," "),(0,a.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),n=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,n.sortedKeys)(e))}},75387:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const h=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",n.set(this,[]),s.set(this,new Map),o.set(this,void 0),a.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,o,"f")}set ttlMs(e){f(this,o,e,"f"),null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),f(this,a,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,a,"f")&&clearInterval(d(this,a,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const n=t();return null!=n&&this.set(e,n),n}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,h.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,n,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,n,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,r,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,r,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||a(this,r,"m",n).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)a(this,r,"m",n).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!a(this,r,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)a(e,r,"m",n).call(e,t,i)||(yield[t,t])}()}toA(){return a(this,r,"m",s).call(this),[...this.delegate.keys()]}[(r=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)a(this,r,"m",n).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=r(i(48161)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),f=i(45255),h=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,h.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:f.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),n=i(55835),s=i(31586),o=i(97790),a=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(i))return;const[o,a,u,c,d,f,h]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,f,h/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,r,"f")&&clearTimeout(s(this,r,"f")),o(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,n=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const n=r(i(87997)),s=i(31586);t.debounce=function(e,t){let i,r=[];const o=(0,s.gt0)(t)?(...s)=>{r=s,null!=i&&n.default.clearTimeout(i),i=n.default.setTimeout((()=>{e(...r)}),t)}:e;return o.reset=()=>{null!=i&&n.default.clearTimeout(i),i=void 0},o.force=()=>{o.reset(),e()},o.setTimeoutMs=e=>{o.reset(),t=e},o.timeoutMs=()=>t,o}},22911:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f,h,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),S=i(45599),b=i(26905),P=i(55835),M=i(31586),_=i(68708),E=i(20214),T=i(57153),x=i(85556),D=i(50213),k=i(70025),C=i(95937),O="TIMEOUT",I=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class F{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,M.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const n=i[r];if(n.isSettled){if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield n.value}}if(i.every((e=>e.name===O)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,T.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),f.set(this,void 0),h.set(this,void 0),this.id=(g(i=n,n,(y=p(i,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,h,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,o,"f")}get elapsedMs(){return(p(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,h=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,f,"f")&&(v.default.clearTimeout(p(this,f,"f")),g(this,f,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,M.gt0)(e)&&(g(this,f,v.default.setTimeout((()=>{this.isPending&&(this.reject(new x.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,f,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,a,"f")===T.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,a,"f")!==T.PromiseStates.pending}get isResolved(){return p(this,a,"f")===T.PromiseStates.resolved}get isRejected(){return p(this,a,"f")===T.PromiseStates.rejected}get settledMs(){return null==p(this,o,"f")?void 0:p(this,o,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,a,T.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,a,T.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=F,n=F,m=function(e){if(p(this,a,"f")===T.PromiseStates.pending){(0,P.map)(p(this,f,"f"),v.default.clearTimeout),e(),g(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),n=i(40958),s=i(42659),o=i(23838),a=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),f=i(25764),h=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,a.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return f.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,h.setEnding)(!0),w();for(const t of f.EndableRanks.values){const i=g.get(t)??[];(0,n.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,h.setEnding)(!0),Promise.all((0,n.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of f.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),f=i(55835),h=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",o).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,h.toInt)(e)??0,t=(0,h.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",o).call(this);const f=()=>{u(this,r,"a",l)&&(0,h.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,h.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,a,"f").call(this),f())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):f(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(){(0,f.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,f.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),f=i(25764),h=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=f.EndableRanks.first,o){this.endTimeoutMs=o,r.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,h.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){o(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,n=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,r.isTest)()?e:e||n}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=r(i(1708)),s=i(22573),o=i(45599),a=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),f=i(28874),h=i(27395),m=i(99331),p=i(56038),g=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{f.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,h.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const f=i(45599),h=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,f.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new S(e,t,i,r)};class S extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,r,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,h.eql)(e?.value??await(e?.promise),i))for(const e of c(this,a,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(i=c(this,s,"f"),++i),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),n=i(80049);t.memoizeAsync=function(e,t){let i=0;const s=new n.FifoCacheAsync(t),o=t=>(i++,s.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return o.clear=e=>{if(null==e)return s.clear();{const t=(0,r.stringify)(e);return s.deleteIf((e=>t===e))}},o.size=()=>s.size,o.callCount=()=>i,o}},22781:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),n.set(this,!1),s.set(this,!1)}_call(){return o(this,n,"f")?(a(this,s,!0,"f"),!0===this.undefinedIfBusy?void 0:o(this,r,"f")):(a(this,n,!0,"f"),a(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{a(this,n,!1,"f"),!0===this.runLaterIfBusy&&o(this,s,"f")&&(a(this,s,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return o(this,n,"f")}prior(){return o(this,r,"f")}async force(){return await o(this,r,"f"),this._call()}}r=new WeakMap,n=new WeakMap,s=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),n=i(76790),s=i(38639),o=i(42659),a=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),f=i(32639),h=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var S=i(20214);async function b(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:n}){const s=[];for(const o of(0,r.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(i(o),n):i(o));null!=e&&s.push([e,o])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function _({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,r.compact)(await e);if((0,r.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(i,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,f=await u.enqueueAll(i,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(f).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,i){const r=[];for(const n of(0,p.batches)((0,h.toA)(await e),t)){const e=await b(n);r.push(...await b(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,h.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,h.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,h.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,h.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s}){return(await _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:n,timeoutMs:s}){return(await _({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,n=null;try{r=await((0,f.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(n??r)}catch{}if(null!=n)throw n;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const n=await t;return null!=n?i(r,n):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const n=await t(r);return null==n?i():n},t.thenMap2Or=async function(e,t,i,r){const n=await e;if(null==n)return r();const s=await t;if(null==s)return r();const o=await i(n,s);return null==o?r():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await _({name:e,arr:t,f:i});return(0,n.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(42659),a=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),f=i(22454),h=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),S=i(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new f.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-r;return i?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new h.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/o.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},42638:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const h=f(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),S=i(82647),b=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new h.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:n}){const s=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),i=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const n=new P.Deferred(e,{payload:i,serialId:r});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),n=i(34546),s=i(41400),o=i(31586),a=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let a=!0;return Promise.race((0,r.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),n=i(42659),s=i(41400),o=i(32639),a=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let f=!1;const h=null==t?void 0:t+Date.now();let m=1;for(;null==h||Date.now()t/2&&!f&&(f=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(r,d),m++}}return f||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=r(i(1708)),s=i(45599),o=i(41400),a=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),f=i(59958),h=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),S=i(88158),b=i(45969),P=i(43334),M=i(28874),_=i(3790);function E(e){return T().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const T=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(M.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(f.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>E(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,M.allSettings)())t.watchLater(e)}));const x=["HOME","LANG","USER"],D=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],k=(0,p.lazy)((()=>{const e=(0,h.caseInsensitiveEnv)().pick(...P.isPosix?x:D),t=(0,h.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,M.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[f.PS_IS_CHILD_PROCESS]="1",t[f.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[f.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,M.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,a.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(n.default.env,(e=>E(e)||!(0,_.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:I({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function I({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...k(),...i?(0,g.childProcLocale)():{},...C(r),...e??{}});for(const e of(0,M.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,_.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>E(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return n}t.childEnv=I},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=r(i(31421)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),f=i(31586),h=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),S=i(22911),b=i(4867),P=i(73614),M=i(70025),_=i(57159),E=i(36868),T=i(66184),x=i(45643),D=i(95402),k=i(9727),C=(0,o.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function O(e){return(0,h.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",O(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",O(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,E.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,D.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,x.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",O(e)),!0;{D.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,D.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,x.waitForPidExit)(i,5e3)}function F(e,i,r,n=0){const o=new Date,a=[];return(0,v.niceable)(i,r)&&a.push((0,P.setUnrefTimeout)((()=>{(0,f.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,f.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,f.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,f.gt0)(e.pid))return(0,D.addPid)({pid:e.pid,cmd:i,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function L(e,t,i,r){const s=(0,k.spawnOptions)(r);return(0,T.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),F(n.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const r=i.quiet??!1,n=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,o=L(e,t,i.timeoutMs,(0,h.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,h=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new S.Deferred(h);o.on("error",(e=>g.push(e))),o.on("exit",(e=>{(0,f.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,f.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,E.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>g.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>g.push(e))),o.stderr?.on("data",(e=>p.push(e))),o.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:h}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:h,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const T=p.join("");(0,l.notBlank)(T)&&g.push(new Error(T)),!r&&(0,a.isNotEmpty)(g)&&C().warn(h+" resulted in errors:",g);const x=i.isIgnorableError??M.isIgnorableError,D=g.filter((e=>!0!==x(e)));if(D.length>0)throw 1===D.length?D[0]:new _.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!s&&0!==y.value)throw new Error(h+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:T}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,D.killPid)(o.pid,!0),e}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const s=(0,k.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),F(n.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const r=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},86335:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(77598),u=a(i(1708)),c=i(19851),d=i(40958),f=i(22573),h=i(50268),m=i(68708),p=i(5670),g=i(50989),y=i(12168),v=i(59455),w=i(41583),S=i(54993),b=i(80875),P=i(50213),M=i(81168),_=i(27395),E=i(25764),T=i(59958),x=i(70025),D=i(83278),k=i(85021),C=i(29325),O=i(43334),I=i(28874),F=i(84777),L=i(55534),A=i(85100),R=i(34330),N=(0,c.lazy)((()=>(0,P.mkLogger)("child.ChildService")));async function j(e){const t=(0,M.ensureSuffix)(e,".js"),i=D.BaseFile.projectRoot(),r=D.BaseFile.for(u.default.cwd()),n=(0,C.isPacked)()?[i.join("bin",t),O.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];(0,C.isPacked)()||(O.isElectron?(n.push(r.join("dist","app",t)),n.push(i.join("src","desktop","dist","library",t))):n.push(i.join("src","library","dist","library",t)));for(const e of n)if(null!=e&&!0===await e.isNonEmptyFile((0,C.isPacked)()?y.KB:128))return N().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:C.isPacked,paths:n.map(S.toS)}});return N().throw("Failed to find path to "+e,{paths:n,fatal:!0})}t.pathToService=j,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=(0,g.strEnum)(...p.ServiceNames.pick("web","sync"));class B{static async mk_(e,t={}){const i=t.pathToService??await j(e);if((0,f.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,v.toA)(t.nodeArgs),new B(e,i,t)}constructor(e,t,i){var a,l;r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,A.serviceExitTimeoutMs)(e),this.logger=(0,P.mkLogger)(this.name);const c=[...(0,v.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&c.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale","forWorker"),this.spawnOpts.forceCLocale=!1,(l=(a=this.spawnOpts).env??(a.env={}))[T.UV_THREADPOOL_SIZE]??(l[T.UV_THREADPOOL_SIZE]=(0,S.toS)(("web"===e?I.Settings.webUvThreads:I.Settings.syncUvThreads).valueOrDefault)),this.wc=new R.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&await(this.opts.onPreRestart?.()),this.restartCount++,(0,F.spawn)(u.default.execPath,c,-1,this.spawnOpts)),endableRank:E.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:o(this,r,"m",s).bind(this),onStderr:o(this,r,"m",n).bind(this),onError:this.opts.onError??(e=>!1===(0,x.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:L.ServiceExitCommand,...i}),(0,_.addEndable)(E.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(k.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(L.ServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,M.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,w.toErr)(i)),this.write(e,t-1)}}}t.ChildService=B,r=new WeakSet,n=function(e){const t=(0,b.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},s=function(e){if(!(0,f.blank)(e))try{const t=(0,b.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,h.isHealthCheckSummary)(t)){const e="failed"===t.state||"error"===t.level;this.logger.log(e?"error":"info",".onStdout(): health check summary",t),e&&this.wc.onError(this.name+".onStdout()",t,e)}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),n=i(41400),s=i(19851),o=i(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},85100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(23560),n=i(28874),s=i(45255);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?n.Settings.syncExitTimeoutMs.valueOrDefault:s.ShortCommandTimeoutMs}},34330:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),f=i(19851),h=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),S=i(25764),b=i(99331),P=i(42638),M=i(38835),_=i(8769),E=i(57159),T=i(66003),x=i(50213),D=i(45643),k=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new O({name:(0,h.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class O{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,f.lazy)((()=>(0,x.mkLogger)("WatchedChild("+(0,h.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),n.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),o=!1!==s.ignorable;this.logger().log(o?"warn":"error","onError()",s),u(this,n,"f")||o||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,r,"m",a).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",a).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,n,"f")}async end(){return c(this,n,!0,"f"),u(this,r,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,n,"f")}),!u(this,n,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",s).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=O,n=new WeakMap,r=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,n,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",o).call(this,e)},o=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},a=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,n,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",s).call(this),!this._stopped&&!u(this,n,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,n,"f")}),this._stopped||u(this,n,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,T.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,n,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",a).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const o=s(i(53916)),a=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),f=i(4001),h=i(95696);function m(e){return(0,f.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,a.toNativePath_)(e);const i=h.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),n=i.sibling(r);if(n.isSelfOrDescendantOf((0,l.examples)()))return o.join("$examples",n.posixPathFrom((0,l.examples)()));const s=(0,d.originalsDir)();if(n.isSelfOrDescendantOf(s))return o.join("$library",n.posixPathFrom(s));const f=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=f?o.join("$library",n.posixPathFrom(f)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const s=i(6858),o=i(1708),a=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),f=i(43334),h=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return n(this,r,"f").push(...e),this}async parse(e=o.argv,t){let i=(0,m.addHelpFooter)(new s.Command).description((0,m.cliWrap)(h.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of n(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":a.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,o.exit)(0)})),i.parse(e,t??{from:f.isMainElectron?"electron":"node"});const d=i.opts();for(const e of n(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),n=i(31586),s=i(51926),o=i(17344),a=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,n.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const n=r(i(1708)),s=i(22573),o=i(38639);t.isDaemon=function(e){return(0,o.isTrue)(n.default.env.__is_daemon)||(0,o.isTrue)(e?.daemon)||!(0,s.blank)(e?.pidfile)}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),n=i(40958),s=i(55835),o=i(31586),a=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,o.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},43380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(28874),n=i(2858),s=i(22573),o=i(38639),a=i(46292);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,o.isTrue)(e.writeSettings)){const e=await(0,n.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,a.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,s.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,n.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),n=i(19851),s=i(22573),o=i(42659),a=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),f=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function h(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=h,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?h(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),n=i(19851),s=i(55835),o=i(31586),a=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,n.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),f=["year","month","day","hour","minute","second","millisecond"];class h{static fromISO(e,t){const i=d().exec((0,a.toS)(e).trim()),r=i?.groups;return null==r?void 0:h.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,o.toInt)(r.index),(0,o.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,o.clamp)(1,1e3,(0,o.toInt)(r,{defaultValue:1})),i=(0,o.clamp)(0,r-1,(0,o.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const n=e.toMillis(),s=(t.toMillis()-n)/(r+1)*(i+1),a=e.plus({milliseconds:s});return null==a?void 0:new h(e,a,t,i,r)}constructor(e,t,i,r=0,n=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=n,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=f.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new h(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=h},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),n=i(51168),s=i(19851),o=i(76790),a=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),f=i(51926),h=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),v=i(21330),w=i(928),S=i(54261),b=i(73389),P=i(51275),M=(0,s.lazy)((()=>(0,h.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function T(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function x(e){try{if(null==e||(0,f.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?n.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),r=T(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[n,s]=(0,o.sortBy)([k(e,i),k(t,r)],(e=>e?.start));return null!=n&&null!=s&&null!=n&&null!=s&&(n.start===s.start||n.end>=Math.min(s.start,s.end))}function O(e,t){return(0,a.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=T,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?n.DateTime.fromObject(e):x(e)},t.datedToDateTime=x,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(O(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=D(e)),r??(r=D(t)),C(e,t,i,r))return!0;const n=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==n&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=n&&(t=(0,v.setZone)(t,n)??t),C(e,t,i,r)},t.isoToDated=O,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof n.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),n=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,n.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),n=i(31586),s=i(54557),o=i(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),n=i(40958),s=i(22573),o=i(42659),a=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const f=(0,n.compact)(d.map((e=>function(e,t){const i=(0,a.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*o.yearMs;case"weeks":case"week":case"w":return i*o.weekMs;case"days":case"day":case"d":return i*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),h=(0,a.lt0)(f[0])?[f[0],...f.slice(1).map((e=>-e))]:f;return(0,c.sum)(h)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),n=i(51168),s=i(19851),o=i(22573),a=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),f=i(68852),h=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:n,month:s,day:o,hour:c,minute:f,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==n||null==s||null==o)return;if(!h.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==f))return;const g=(0,a.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return b({year:n,month:s,day:o,hour:c??0,minute:f??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=n.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,o.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,o.blank)(e)?void 0:r.ExifDateTime.fromDateTime(n.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,o.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,f.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,f.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,a.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),n=i(22573),s=i(42659),o=i(49769),a=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),f=i(66649),h=i(98725),m=i(88600);t.recent=function(e,t=5*s.secondMs){return(0,c.isRecentMs)((0,f.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,n.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,n.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,o.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,f.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,a.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,h.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const s=i(77988),o=i(51168),a=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),f=i(31586),h=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),v=i(79842),w=i(66649),S=i(98247),b=i(98725),P=i(928),M=i(54261),_=i(73389),E=i(89724),T=i(17415),x=i(88600),D=i(51275);function k(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,x.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(b.ISO_YMD_RE.exec(e)?.groups??b.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,f.toGt0)(e?.year);if(null==e||null==t||tk(e))).join("-")}toLocal(){return(0,E.datedToLocal)(this)}toDateTime(){return o.DateTime.fromObject((0,h.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,h.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,h.pick)(e.plus({month:1}),"year","month"):(0,h.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function O(e,t){if(e instanceof s.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,M.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,T.zoneToTzOffsetMinutes)((0,w.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(n=>(0,d.map)((0,P.getDay)(e),(s=>(0,d.map)((0,P.getHour)(e),(o=>(0,S.dateObjectToExifDateTime)({year:r,month:n,day:s,hour:o,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,f.round)(e/15),n=Math.abs(r),s=Math.floor(n/60),o=Math.floor(Math.abs(n%60));return`${t?"UTC":""}${i}${k(s)}:${k(o)}`},t.toExifDateTime=O,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof s.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,M.hasTime)(e)||(i??(0,v.datedToPrecisionMs)(e))>=c.dayMs?L(e):O(e,(0,D.getZoneName)(e))?.toISOString({includeOffset:t})};const I="yyyy:MM:dd HH:mm:ss.SSS",F=I+"ZZ";function L(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>k(e))).join(t)}function A(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(w.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,f.isNumber)(t)?o.DateTime.fromMillis(t):(0,v.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,D.hasZone)(t)?F:I):void 0},t.datedToYMD=L,t.toFuzzyDate=A,t.sameDay=function(e,t){return(0,f.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,f.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,w.datedToMillis)(e)||null==(0,w.datedToMillis)(t))return;const[n,s]=[e,t].map((e=>(0,w.datedToMillis)(e))).sort(),a=(s-n)/(r+1),l=(0,D.getZoneName)(e),u=l===(0,D.getZoneName)(t)?l:void 0,c=o.DateTime.fromMillis(n+a*i,{zone:u});return[e,t].some((e=>!(0,M.hasTime)(e)))?A(c):c},t.setZone=function(e,t,i){const r={...(0,h.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,D.hasZone)(e)},n=(0,T.normalizeZone)(t);return null!=e&&null!=n&&(0,M.hasTime)(e)?e instanceof y.DateInterval?e.setZone(n,r):O(e)?.setZone(n,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,f.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,v.datedToDateTime)(e);if(null==i)return;const r=(0,D.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,n,s,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const a=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),f=i(49769),h=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),v=i(68852),w=i(4001),S=i(28874),b=i(24689),P=i(79842),M=i(66649),_=i(98247),E=i(21330),T=i(54261),x=i(73389),D=i(16400),k=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,h.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=F({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,x.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0};const O=new Map;function I(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const n=(0,f.getOrSet)(O,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:n?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function F({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:n=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:o}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>I(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>a.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(n(e))for(const e of s){const t=o(e);if(null!=t&&(0,k.isValidDate)(t))return t}}t.parseDated=F;class L{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>o(this,r,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>o(this,r,"m",s).call(this))),o(this,r,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=F({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,r=new WeakSet,n=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");o(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),o(this,r,"m",n).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),o(this,r,"m",n).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),o(this,r,"m",n).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),o(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),o(this,r,"m",n).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),o(this,r,"m",n).call(this,[t.yearRE,t.seps,t.monthishRE]),o(this,r,"m",n).call(this,[e,t.seps,t.yearRE]),o(this,r,"m",n).call(this,[t.yearRE,t.seps,e]),o(this,r,"m",n).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,h.toInt)(t.year),month:(0,h.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,h.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),n=i(31586),s=i(54261);function o(e){return e instanceof Date?e.getMinutes():e?.minute}function a(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=o,t.getSecond=a,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,n.gt0)(o(e))||(0,n.gt0)(a(e))||(0,n.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(a(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),n=i(31586),s=i(68708);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,n.gt0)(t.hour)||(0,n.gt0)(t.minute)||(0,n.gt0)(t.second)||(0,n.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),n=i(19851),s=i(42659),o=i(55835),a=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),f=i(74417),h=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,n.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,o.map)((0,c.isoToDated)(e),w)}function w(e){return(0,a.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,a.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},n=10*r(),s=r(),o=r(),l=(0,a.toGt0)(r()),u=(0,a.toGt0)(r()),c=(0,a.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:o,second:s,millisecond:n,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):h.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),n=i(76790),s=i(31586),o=i(9092),a=(0,r.lazy)((()=>{const e=new o.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(n=>{const s=r.format(new Date(2017,n));e.set(s,n+1),"short"===i&&"en-US"===t&&e.set(s+".",n+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:a().get(e)},t.monthNames=function(){return(0,n.sort)([...a().keys()])}},42499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(51168),n=i(19851),s=i(19043),o=i(28874);t.setupLuxon=(0,n.lazy)((async()=>{r.Settings.throwOnInvalid=!1,o.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,s.locale)()}))},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),n=i(51168),s=i(19851),o=i(22573),a=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),f=i(54993),h=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,h.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,a.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-±+−])/,T=/[-−]/,x=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:O((0,t.TimezoneOffsetRE)().exec(e))}function O(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,o.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=T.test((0,f.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,n=null==t?void 0:i*(60*t+r);return v(n)?n:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,x,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=O;const I=/\b(?(?:Etc\/)?GMT)\b/,F=(0,s.lazy)((()=>(0,m.concatRegexp)([I,E,D,m.RegExpOptional.from(k)])));function L(e){return O(F().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,o.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),n=i(19851),s=i(40958),o=i(22573),a=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),f=i(28874),h=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),v=(0,n.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),w=(0,n.lazy)((()=>(0,s.compact)(f.Settings.badDates.values.map((e=>(0,h.isoToDated)(e)))))),S=(0,n.lazy)((()=>(0,s.compact)(w().map((e=>(0,p.datedToISO)(e)))))),b=(0,n.lazy)((()=>(0,s.compact)(w().map((e=>(0,y.datedToLocal)(e)))))),P=(0,n.lazy)((()=>(0,s.compact)(w().map((e=>(0,m.datedToMillis)(e))))));function M(e){if(null==e)return!1;const t=E(e);return v().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return M(e)?e:void 0},t.isValidDate=M;const _=String(new Date("bad"));function E(e){try{if(!(0,h.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===_)return _;const t=(0,s.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const n=[];if((0,l.isNumber)(e)||n.push("year is not a number"),(0,l.lt)(e,f.Settings.minValidYear.valueOrDefault)&&n.push("year is less than "+f.Settings.minValidYear.key),(0,u.gt)(e,T())&&n.push("year is in the future"),null==t&&null!=i&&n.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&n.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&n.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const s=r.DateTime.fromObject({year:e,month:t,day:i});s.isValid||n.push(s.invalidExplanation??"not valid")}return(0,s.compact)(n)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=f.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+f.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):b().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):S().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,o.toNotBlank)((0,s.uniq)((0,s.compactBlanks)(t)).join("; "))}catch(t){return v().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=E;const T=(0,n.lazy)((()=>r.DateTime.now().plus({milliseconds:f.Settings.maxValidFutureMs.valueOrDefault}).year),a.dayMs);t.mapValidDate=function(e,t){return M(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==E({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),n=i(31586),s=i(24689),o=i(73389);t.hasZone=function(e){return null!=e&&!(0,n.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,o.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,o.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),n=i(7311);function s(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(n.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(i(76760)),a=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),f=i(97352),h=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),S=i(29882),b=i(45969),P=i(43334),M=i(28874),_=i(41692),E=i(32774),T=i(80612),x=i(32551),D=(0,d.lazy)((()=>(0,f.mapGte0)((0,h.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,o.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function C(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:E.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:E.DefaultDockerLibraryDir},...k()]);const e=(0,a.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),o.default.resolve((0,x.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,x.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,x.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,T.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,T.firstDir)({dirs:C(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),M.Settings.cacheDir.watchLater(I)}));function I(){M.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=M.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=I},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),n=i(45969),s=i(41692),o=i(32774),a=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},79960:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(19851),n=i(22573),s=i(50213),o=i(45255),a=i(84777),l=i(16287),u=i(57902),c=i(43334),d=(0,r.lazy)((()=>(0,s.mkLogger)("dir.DefaultApplePhotosLibrary"))),f=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,a.stdout_)("defaults",f,{timeoutMs:o.ShortCommandTimeoutMs});if((0,n.blank)(e))return void d().warn(`"defaults ${f.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),n=i(45969),s=i(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=r(i(76760)),s=i(40958),o=i(72993),a=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function f(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:f(),desc:"config"})},t.desktopConfigDirs=f},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),n=i(96706),s=i(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),n=i(40958),s=i(22573),o=i(66430);function a({dirs:e,desc:t}){for(const{dir:i,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(i)){if((0,o.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),n=i(76760),s=i(1708),o=i(19851),a=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),n=i(49776),s=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,n.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),n=i(54993),s=i(29882),o=i(28874);function a(e){return(0,r.toNotBlank)((0,n.toS)(e))??o.Settings.libraryDir.valueOrDefault}t.libraryDir=a,t.originalsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(a(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(a(e),o.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),n=i(55835),s=i(37805),o=i(15056),a=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),f=i(28874),h=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,h.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,h.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+a.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,h.originalsDir)(e))}async function S(e){return y(w(e),!1)}function b(e){return u.PosixFile.forMaybe((0,h.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(f.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,n.map)(g(e),(e=>(0,o.pathToDbDir)(e,o.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=r(i(76760)),s=i(19851),o=i(40958),a=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),f=i(45969),h=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function S(){return(0,f.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:h.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,a.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(44198),a=i(43334),l=i(24399),u=i(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),n=i(7282),s=i(29325),o=i(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,r.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),n=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=r(i(73024)),s=i(76760),o=r(i(1708)),a=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),f=i(7282),h=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),S=i(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,f.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),i={...o.default.env};for(const r of e)try{const e=(0,d.debom)(n.default.readFileSync((0,g.resolve)(r))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(s))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,h.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),n=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,r.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=o}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=r(i(1708)),s=i(19851),o=i(22573),a=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),f=i(34102),h=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,h.env)()))),t.onEnvChange=p,(0,l.later)((()=>{h.env.watchLater(p),(0,f.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,a.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),n=i(19851),s=i(40958),o=i(22573),a=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),f=i(89788),h=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),r=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(a.ErrorDelimiter)),r-o.length,n)+o.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,h.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new f.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,o.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,o.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),n=i(26905),s=i(55835),o=i(54993),a=i(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,n.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),n=i(76790),s=i(50989),o=i(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},68301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(19851),n=i(42659),s=i(75240),o=i(55835),a=i(31586),l=i(68708),u=i(59455),c=i(54993),d=i(50213),f=i(45255),h=i(37628),m=i(99331),p=i(46292),g=i(38835),y=i(32144),v=i(29882),w=i(95696),S=i(55222),b=i(28874),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*n.secondMs)).join((0,h.shortStringSha)(e.message,8,S.GeoRadix)+".json")}async eventsFrom(e=new Date,t=n.dayMs){const i=e.getTime(),r=i-t,o=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,a.within)(r,o,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,s.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),n=b.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=n,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:n,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:f.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,o.map)((0,p.configDir)(),(e=>new _(w.PosixFile.for(e).join("events"))))))},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),n=i(38639),s=i(26905),o=i(54993),a=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function f(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function h(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,r.compact)(t).join("");return f(i)+h(i).join("")},t.stripErrorFlags=f,t.extractErrorFlags=h,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),n=i(31586),s=i(68708),o=i(7282),a=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),f=i(38835),h=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,h.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===i.fatal,c=!0===i.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const f=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===f?"error":"warn","onError()",{event:f,error:i}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+f.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),n=i(22573),s=i(38639),o=i(26905),a=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),f=i(81168),h=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,n.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,n.firstNotBlank)((0,f.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,f.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,h.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,n.blank)(r)||(i=(0,f.dedupeNeedle)(i,r,"file")),(0,h.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,f.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=i(49769),a=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),o=s(this,r,"f").get(e);return null!=o&&(o.resolve(t),s(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,n=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),n=i(19851),s=i(15197);t.ee=(0,n.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=r(i(73024)),s=r(i(1708)),o=i(19851),a=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),f=(0,o.lazy)((()=>s.default.getgroups?.()));function h(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?h(t,n.default.constants.R_OK|n.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?h(t,n.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:f()??[],l=0===o,u=l||e.uid===o,h=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(h?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(h?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(h?8:0)|1)&e.mode))}t.canAccessSync=h,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=r(i(76760)),s=i(19851),o=i(81168),a=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),f=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,f.resolve)(...e)}};const h=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,f.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:h().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,f.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,o.equalsIgnoreCase)(e.basename,i.base))return n.default.join(r,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),n=i(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=a(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=h(i(76760)),v=h(i(1708)),w=i(46466),S=h(i(57975)),b=h(i(38522)),P=i(19851),M=i(40958),_=i(5233),E=i(22573),T=i(42659),x=i(50357),D=i(96249),k=i(98553),C=i(55835),O=i(31586),I=i(68708),F=i(97790),L=i(39926),A=i(51926),R=i(59455),N=i(54993),j=i(48884),B=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),H=i(76850),G=i(70025),q=i(34102),$=i(80875),J=i(50213),K=i(70417),Z=i(43334),Y=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),ne=i(89968),se=i(20197),oe=i(88561),ae=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),fe=i(65238),he=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),Se=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,r=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=be().get(i);if(null!=r)return r;const n=(0,he.resolve)(i),s=new Pe(n,t);return be().set(i,s),be().set(n,s),s}static clear(e){(0,q.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,q.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),f(this,o,void 0,"f"),this}clearThisAndParent(){return(0,q.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,he.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",s).call(this)??await d(e=this.clearThisAndParent(),r,"m",s).call(e)}async children_(e){const t=await(0,fe.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const i=await d(this,n,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,x.eql)(["."],e)||e.every(E.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&f(this,o,void 0,"f"),f(this,o,d(this,o,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&f(this,o,void 0,"f"),f(this,o,d(this,o,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,T.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>=(0,T.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,T.unixtime)(t)>(0,T.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,F.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*T.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,H.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:T.secondMs,errorIsRetriable:G.isRetriableError})}async gunzip(){return d(this,r,"m",a).call(this,(0,Y.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,r,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,r,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,A.newlineRe)(),(r=>{const n=e.exec(r);null!=n&&(t.maybeResolve(n),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,O.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),Me)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,n)=>{try{const s=await e.f(r,(0,C.denull)(n));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,s=async function(){const e=(await(0,fe.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*T.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let Me=!0;t.useFsWatch=function(e){Me=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),n=i(88840),s=i(14036),o=i(29882);function a(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,o.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=a,t.isBrowserExtension=a(n.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=a(n.ExtTypes.Video),t.isAssetFileExtension=a(n.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),n=i(96249),s=i(51926),o=i(54993),a=i(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),n=i(19851),s=i(50213),o=i(37805),a=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const f=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function h(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return f().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return h((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=h,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(i),await(0,d.writeTextfile_)((0,a.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=r(i(76760)),s=r(i(1708)),o=i(19851),a=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(i(44652)),l=o(i(73024)),u=i(76760),c=i(57975),d=i(19851),f=i(59455),h=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),S=i(16287),b=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,h.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},n=await a.stat(t);return new _(i,new P(r,n))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,f.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,f.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=r(i(76760)),s=i(39926),o=i(29882),a=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if(await(0,o.mkdirp_)(r.dir),!i.requireNumber&&await(0,a.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,a.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,o.parseNativePath)(i.nativePath);if((0,o.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=n.default.join(r.dir,`${r.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},88561:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=i(40958),a=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),f=i(34102),h=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends h.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,f.ee)().on("fileChanged",(e=>s(this,r,"m",n).call(this,e))),(0,f.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),n=i(22573),s=i(45599),o=i(96249),a=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],f=(0,s.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),h=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=h.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(i)?void 0:f()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),n=i(17217),s=i(16287),o=i(68284);async function a(e){return(0,r.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),n=i(19851),s=i(22573),o=i(50213),a=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),f=i(95696),h=i(93854),m=i(16287),p=(0,n.lazy)((()=>(0,o.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,h.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const n=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),o=(0,l.normalizeExt)(f.PosixFile.for(e))??(0,c.mimetypeExt)(n);return(0,s.blank)(n)||(0,s.blank)(o)?void 0:{ext:o,mime:n}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new a.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),f=i(38836),h=i(43624);class m extends f.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,n.set(this,[]),s.set(this,void 0),o.set(this,void 0),l(this,o,(0,h.fileStatsSync)(e),"f"),l(this,s,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",a).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,n,"f").push(e)}close(){u(this,s,"f").close()}}t.FileWatcher=m,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(e){const t=await(0,h.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,o,"f"),t)){l(this,o,t,"f");for(const t of u(this,n,"f"))t(e,this.nativePath)}}},73209:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f,h,m,p,g,y,v,w,S=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const M=i(58587),_=P(i(44652)),E=i(87997),T=i(40958),x=i(17586),D=i(42659),k=i(50357),C=i(75240),O=i(55835),I=i(31586),F=i(30976),L=i(13538),A=i(54993),R=i(7282),N=i(68852),j=i(23560),B=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),H=i(55222),G=i(63870),q=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(q.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return b(this,n,Math.max(Date.now(),S(this,n,"f",s)+1),"f",s),(0,T.compactBlanks)([H.TokenRadix.encode(S(this,n,"f",s)),j.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return n.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,I.toInt)(J.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return S(this,n,"f",a).find((t=>t.opts.file===e.file))??new n(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>S(this,r,"m",w).call(this)),e.endableRank??B.EndableRanks.postdb,(0,G.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,b(t=n,n,(i=S(t,n,"f",o),++i),"f",o)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),f.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(S(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,q.fsLockFileBasename)(n.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await S(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,q.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+S(this,l,"f")),this.staleMs=(0,I.round)(this.opts.timeoutMs/(0,F.randomFloat)(2,4)),S(n,n,"f",a).push(this)}get acquired(){return S(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await S(this,r,"m",h).call(this,e)??S(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,x.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==S(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:D.secondMs);b(this,c,setInterval((()=>S(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=S(this,c,"f")&&(clearInterval(S(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(S(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),b(this,u,!1,"f"),(0,O.map)(S(this,d,"f"),(e=>(0,E.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?S(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>S(this,r,"m",v).call(this)),(0,I.toGt0)(this.staleMs)??D.secondMs),"f"),S(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(S(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,L.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,n=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,r=new WeakSet,h=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,I.gt0)(this.staleMs)&&Date.now()>S(this,f,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await S(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,f,Date.now(),"f");const e=[],t=await S(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,I.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,q.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;n.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=n.pidFromBasename(i[0]);if((0,I.gt0)(t)&&!(0,M.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),S(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await S(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await S(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,T.filterInPlace)(S(n,n,"f",a),(e=>S(e,l,"f")!==S(this,l,"f")))},s={value:0},K.internalErrors=0,o={value:0},a={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),n=i(51926),s=i(54993),o=i(17217);function a(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,n.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,n.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,o.basename)(e);return a(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&a((0,o.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),n=i(55835),s=i(31586),o=i(51926),a=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function f(e,t={aggressive:!0}){return h((0,r.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function h(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,s.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:h(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const n=(0,u.parsePosixPath)(i),s=f(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=f,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),i=f(t),r=(0,o.stripPrefix)(t.toLowerCase().normalize(),i);return(0,n.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const n=r(i(73024)),s=i(57075),o=i(46466),a=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends s.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,a.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,o.pipeline)([n.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const n=r(i(44652)),s=r(i(73024)),o=i(46466),a=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),a.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await n.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=r(i(77598)),s=r(i(73024)),o=i(46466),a=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),f=i(73913),h=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,a.lazy)((()=>(0,h.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=S().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),S().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=n.default.createHash(i);return await(0,o.pipeline)([e,...t,r]),r.digest().subarray(0,f.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(f.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),n=i(42659),s=i(55835),o=i(31586),a=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),f=i(63870),h=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,a.stdout_)("chflags",["hidden",t],{timeoutMs:10*n.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,f.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:h.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,a.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*n.secondMs}),i=(0,o.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),n=i(54993),s=i(7282),o=i(43334),a=i(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,f=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function h(e){return null!=f?.exec((0,n.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":h(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=h,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),n=i(55835),s=i(57159),o=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,n.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,o.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new s.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),n=i(51926),s=i(54993);class o extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=r.pop();this._prior=o??"";let a=!1;for(const e of r)a||(a=!this.push(e));a?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=r(i(76760)),s=i(17217),o=i(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const o=s(i(76760)),a=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),f=i(68852),h=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),S=i(88561),b=i(65238),P=i(16287),M=(0,a.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),_="NoMedia",E=new RegExp("(?:^|["+(0,l.uniq)([(0,f.escapeRegExp)(o.default.sep),"/"]).join("")+"])\\.?"+_+"$","im"),T=Object.freeze(["."+_,_]),x=Object.freeze((0,u.flatten)(T.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function D(e){return null!=E.exec(e)}t.isNoMediaName=D;const k=(0,a.lazy)((()=>new S.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=v.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return D(i.base)||await(0,w.isCachedirTagFile)(i)?k().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await k().getOrSetAsync(i.nativePath,(()=>O(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function O(e){if(D(e.base))return k().set(e.parent().nativePath,e.nativePath),M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,b.readdirCached)(e.nativePath);if(null!=t)return F(e.nativePath,t);const i=new h.Abortable,r=await Promise.race([I(e.nativePath,i),(0,b.readdir)(e.nativePath).then((t=>F(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,w.isCachedirTagDirectory)(e)?M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function I(e,t){for(const i of g.isCaseSensitiveFs?x:T){if(!0===t?.aborted)return null;const r=o.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return M().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function F(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(D(r.basename))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,o.join)(e,r.basename))});if(r.basename===w.CACHEDIR_TAG){const t=(0,o.join)(e,r.basename);if(await(0,w.isCachedirTagFile)(t))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=O,t._dirHasNoMediaChild=I},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=r(i(44652)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),f=i(51926),h=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),S=i(17217),b=i(16287),P=i(66430),M=i(5545);function _(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return C(e).some(_)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return T((0,v.posix2native)(e))},t.extname=function(e){return T(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const E=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function T(e){const t=E.exec(e)?.groups,i=t?.ext2??"",r=s.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function x(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,f.splitLast)(t.dir,s.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),i=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const r=e(t),n=e(i);return null!=r&&null!=n&&(y.isLinux?r===n:(0,p.equalsIgnoreCase)(r,n))}function C(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function I({p:e,maxLength:t}){const i=(0,S.toNativePath_)(e);if(i.length<=t)return i;const r=C(e),n=[],s=[r.pop()];for(;r.length>0;)if(n.length=t){r.unshift(n.pop());break}}else if(s.unshift(r.pop()),L([...n,...s]).length>=t){r.push(s.shift());break}return r.length>0&&n.push("…"),L([...n,...s])}function F(e){return e.startsWith("\\\\")}function L(e){return(0,f.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=T,t.parentBasename=x,t.grandParentBasename=function(e){return x(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return k(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(S.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,S.toNativePath_)(e),r=(0,S.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,v.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=I,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const n=[];for(const r of e.slice(0,i))n.push(I({p:r,maxLength:t}));return n.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=T(e);return`${i.base}${t}${i.ext}`},t.isUNC=F,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(F(e)||null!=e.match(M.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=L,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:L(e)},t.bestMountpointForDir=function(e,t){return(0,h.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=r(i(76760)),s=i(19851),o=i(40958),a=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),f=i(54993),h=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),S=i(16287),b=(0,s.lazy)((()=>(0,h.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,a.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,a.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(i,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,f.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,o.uniq)((0,o.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=n.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,n,s,o=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&o(t,e,i);return a(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),f=c(i(73024)),h=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),S=i(22573),b=i(42659),P=i(26905),M=i(75240),_=i(55835),E=i(31586),T=i(68708),x=i(13538),D=i(89937),k=i(12168),C=i(54993),O=i(48884),I=i(50213),F=i(45255),L=i(81168),A=i(56519),R=i(56038),N=i(31562),j=i(84777),B=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),H=i(43334),G=i(33847),q=i(24399),$=i(28874),J=i(79915),K=i(45200),Z=i(34238),Y=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),ne=i(73209),se=i(48313),oe=i(29882),ae=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),fe=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,O.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class he extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,I.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>H.isMac?(0,j.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:F.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return he.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?he.for(e):void 0}static for(e,t){if(e instanceof he)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=fe().get(e);if(null!=t)return t}const i=(0,ae.toNativePath_)(e),r=new he(i,t);return(0,L.isString)(e)&&fe().set(e,r),fe().set(i,r),r}static forPosix(e){return he.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>he.for(e)))}for(e,t){return he.for(e,t)}forDirectoryEntry(e){return he.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,oe.containedByNativePath)({ancestor:(0,B.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,oe.containedByNativePath)({ancestor:(0,B.originalsDir)(),descendant:this,acceptSelf:!0}))return H.isWin&&this.nativePath.startsWith("\\\\")?he.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>he.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(H.isWin||H.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,O.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,T.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:n,skipWip:s=!1,skipFsLock:o=!1,retries:a=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const a=await this.clear().isNonEmptyFile(i);if(!a){if(s&&o)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:o,minSizeBytes:i,timeoutMs:n,dirty:l})}return a&&r?void 0:this.utimes()}),{maxRetries:a,timeoutMs:2*n,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:n,dirty:s=!1}){return await this.parent().mkdirp_(),(0,ne.withLock_)({file:this,skipFsLock:r,timeoutMs:n,dirty:s},(async()=>{const r=this.wip();try{await r.unlink("trace");const s=await(0,x.thenOrTimeoutError)(e(r),n);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:F.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(F.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",n).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,f.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,E.clamp)(F.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,oe.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,oe.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=he,r=new WeakSet,n=async function(e){let t,i=e;const r=e.wip();try{const n=await this.stat_();if(null==n)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(n.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await h.default.copyFile(this.nativePath,r.nativePath,f.default.constants.COPYFILE_FICLONE),n.size>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},n.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,E.approximates)(n.size,await r.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:n.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:n.birthtimeMs,mtimeMs:n.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,n.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${n.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),n=r?.size;return null==r||null==n?this.pflog().throw("Can't copy missing files"):(n>5*k.MiB&&(t=new G.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},n,(()=>e.clear().size()))),H.isWin?await q.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,q.pwshQuote)(this.nativePath)} -Destination ${(0,q.pwshQuote)(i.nativePath)}`,(e=>e)):H.isMac?await(0,j.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,j.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=r(i(76760)),s=i(22573),o=i(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const i=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",r=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=r(i(76760)),s=r(i(1708)),o=i(19851),a=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),f=i(43334),h=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),f.isElectron&&t.push(n.default.join((0,p.execDir)(),"resources"),n.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,p.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,h.hasChildrenSync)(i,e))return i;for(const t of(0,h.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,h.hasChildrenSync)(t,e))return t;const r=n.default.join(i,"node_modules","photostructure");if((0,h.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!f.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),n=i(19851),s=i(31586),o=i(50213),a=i(57902),l=i(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),n=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const n=i??(await(0,r.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await(0,r.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(i(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),n=i(84542);t.readLines_=async function(e){return(0,n.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class n extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=r(i(51455)),s=i(76760),o=i(19851),a=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),f=i(13538),h=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),S=i(88561),b=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function M(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=M;const _=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function E(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function T(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),r=x(e),n=await(0,f.thenOrTimeout)(r,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===h.Timeout&&(0,g.onTimeout)({soft:!1}),n!==h.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=E,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),M()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?M():E(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){E(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await T(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?T(e):x(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=T,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=x},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=i(73024),s=r(i(76760)),o=i(40958),a=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),f=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),h=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=s.default.resolve(t,...e);if((0,n.existsSync)(i))return i}f().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(h).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),n=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=r(i(73024)),s=r(i(76760)),o=i(22573),a=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),f=i(14427);function h(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof n.default.Dirent?e.name:h(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=h,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return h(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(h(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=h.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=S(e),r=S(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],n=t[i],s=(0,u.diff)(b(r),b(n));if(null==s||s>1)return"unmatched "+i+": "+r+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=h.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??h.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=h.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=h.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=h.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=r(i(73024)),s=i(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const i=o(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=o(e);return t.emptyIsNew?null==i:a(i)},t.isNonEmptyFileSync=function(e,t=0){const i=o(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),n=i(56409);t.onDataChunked=function(e,t,i){const r=new s(t,i,!0);return r.read(e),r.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=r(i(57075)),s=i(41400),o=i(55835),a=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class f extends n.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=f},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=r(i(73024)),s=i(76760),o=i(22573),a=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f,h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),v=i(19851),w=i(40958),S=i(22573),b=i(42659),P=i(98553),M=i(31586),_=i(68708),E=i(50989),T=i(51926),x=i(85556),D=i(54993),k=i(89788),C=i(23467),O=i(7282),I=i(23560),F=i(77377),L=i(71567),A=i(73568),R=i(25764),N=i(38836),j=i(99331),B=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),H=i(5012),G=i(32144),q=i(95696),$=i(36868),J=i(57902),K=i(28874),Z=i(84542),Y=i(73428);t.AssetFileSyncStates=(0,E.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,E.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,F.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,E.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,E.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const X={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,_.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??q.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,E.strEnum)(...(0,_.keys)(new class{constructor(e,t,i,r,n,s,o,a,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=n,this.elapsedMs=s,this.details=o,this.url=a,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,v.lazy)((()=>(0,Y.writeTextfile_)(re().nativePath,(0,T.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(X)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=b.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,G.isCsvExt)(e)&&(0,M.gte)(e.mtimeMs(),t)))},t.syncReport=(0,v.lazy)((()=>new ne));class ne extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>h(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),n.set(this,void 0),s.set(this,void 0),o.set(this,void 0),a.set(this,0),l.set(this,0),this.outputFiles=new k.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return h(this,n,"f")?.nativePath}get rowCount(){return h(this,l,"f")}onProgress(e){if(null==e||(0,S.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,H.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,D.toS)(e.path),state:e.state,details:(0,D.toS)(e.details).trim().replace(/\r?\n/g,"; ")},n={ts:t,at:new Date(t).toISOString(),...i,...(0,_.pick)(e,"from","elapsedMs","url")};(0,_.isEmptyObj)(e.meta)||(n.meta=(0,P.stringify)(e.meta)),(0,O.isTest)()&&process.stdout.write((0,P.stringify)(e)+Z.Newline),h(this,r,"m",u).call(this,n)}}maybeSystemData(e){(0,I.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const n=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const s=await r(),o=s.state??(null!=s.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return o===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:s}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-n,...s,state:o}),s}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,j.ending)()||r instanceof A.AbortError?t.SyncFileStates.canceled:r instanceof x.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,j.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-n}),r}}get output(){return h(this,s,"f")??h(this,r,"m",f).call(this)}async flushClose(){return h(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=h(this,s,"f");return m(this,s,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:h(this,n,"f")}}t.SyncReport=ne,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=h(this,o,"f");if(m(this,o,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,a,(t=h(this,a,"f"),t++,t),"f");null!=i&&(0===h(this,a,"f")?h(this,r,"m",c).call(this,i):(h(this,r,"m",c).call(this,{...i,details:(0,w.compactBlanks)([i.details,`(repeated ${h(this,a,"f")+1} times)`]).join(" ")}),m(this,a,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Z.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=h(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:h(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},f=function(){return m(this,n,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,B.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(h(this,n,"f").nativePath),this.logger.info("Opening new report: "+h(this,n,"f")),(0,O.isTest)()&&(0,L.stdoutWrite)({syncReport:h(this,n,"f").nativePath},!1),m(this,s,(0,g.createWriteStream)(h(this,n,"f").nativePath),"f"),h(this,s,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Z.Newline),h(this,s,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const n=r(i(48161)),s=i(19851),o=i(55835),a=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),f=i(8103),h=i(43899);function m(){return(0,o.map)(h.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,o.map)(m(),(e=>e.join(c.platformName+"-"+n.default.arch())))}async function g(e){if(c.isWin&&(e=(0,a.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,f.pathIfExists)(m()?.join("bin",e))),(()=>(0,f.pathIfExists)(m()?.join(e))),(()=>(0,f.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,f.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=r(i(44652)),s=i(19851),o=i(22573),a=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),f=i(17217),h=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const r=(0,f.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,f.dirname)(t.file));const a=(0,s.lazy)((()=>(0,h.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),n=i(41400),s=i(55835),o=i(92782),a=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),f=i(87128),h=i(95696);function m(){return(0,o.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends f.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:a.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,s.map)(h.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,s.map)((0,l.configDir)(),(e=>new p(h.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,n.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const o=s(i(51455)),a=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,a.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await o.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=r(i(76760)),s=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??n.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),n=i(45255),s=i(17217);t.WipTimeoutMs=n.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const o=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(o,"")},t.isWip=function(e){return o.test((0,s.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),n=i(22911);class s extends r.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=r(i(44652)),s=r(i(76760)),o=i(51926),a=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function f(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,o.wrap)(t));await d(e,i)},t.writeFileSync_=f,t.writeTextSync_=function(e,...t){return f(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=r(i(73024)),s=i(76760),o=i(46466),a=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),f=i(50213),h=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,f.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const r=[],s=[n.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>r.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(r))throw new h.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new g.ReadableBuffer(i),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},19652:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const o=i(51455),a=s(i(22915)),l=i(40958),u=i(82950),c=i(22573),d=i(45599),f=i(12168),h=i(50213),m=i(79960),p=i(32551),g=i(98314),y=(0,d.defer)((()=>(0,h.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,p.homeDir)(),a.getHomeFolder(),a.getPicturesFolder(),a.getVideosFolder(),a.getDesktopFolder(),await(0,m.defaultApplePhotosLibrary)()]).sort(),t=new Map,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,o.readdir)(e,{withFileTypes:!0})}catch(i){if(["ENOTDIR","ENOENT"].includes(i?.code))continue;t.set(e,i)}const r=0===t.size?{level:"ok",msg:["Default media directories are OK","The following directories are readable:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Error reading "+(0,f.plur)(t.size,"media directory")+":",(0,u.li)([...t.entries()].map((([e,t])=>(0,u.tt)(e)+":"+(0,g.errorToS)(t,{maxLen:80}))))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},87408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(63870),n=i(18454),s=i(89035),o=i(82638);t.getStatusSummary=async function(e={}){return(0,o.summarizeHealthChecks)({healthChecks:[...n.HealthCheck.allCritical(),(0,s.memoryHealthCheck)()],errors:n.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},18454:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f,h,m,p,g,y,v,w,S,b,P,M=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},_=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const E=i(19851),T=i(40958),x=i(76790),D=i(22573),k=i(41400),C=i(50357),O=i(26905),I=i(50268),F=i(55835),L=i(68708),A=i(30976),R=i(51926),N=i(13538),j=i(42279),B=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),H=i(50213),G=i(69591),q=i(22911),$=i(99331),J=i(5916),K=i(42638),Z=i(77740),Y=i(98314),X=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),ne=i(21525),se=i(82638),oe=(0,E.lazy)((()=>(0,H.mkLogger)("health.HealthCheck")));class ae{static traceLater_(e,t){const i=new q.Deferred(e);i.catch((t=>{M(this,n,"f",l).push(e+": failed: "+(0,Y.errorToS)(t)),this.onResultChange()})),M(this,n,"m",a).call(this).push(i);try{return i.observe((0,j.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return M(this,n,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){M(this,n,"f",l).push((0,R.isString)(e)?e:(0,Y.errorToS)(e)),this.onResultChange()}static lastErrors(){return M(this,n,"f",l).toA()}static addLoadingMsg(e){M(this,n,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,T.compact)((0,B.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return oe().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:M(this,n,"f",f).entriesByCountDesc()}),(0,F.map)((0,V.leastBy)(e,(e=>[M(this,n,"f",f).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=M(this,n,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,F.map)(e,(e=>M(this,n,"f",f).incr(e.msg))),oe().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,n.reset()}static findById(e){return M(this,n,"f",h).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,I.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=M(this,n,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=n.summary();if(e.pendingCount>0){const t=await Promise.all(n.testResultsCritical());e=n.summaryFromResults(t),oe().info("awaitSettled(): summary result",{summary:e,results:t})}return oe().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){n.summary.unset()}static reset(){if((0,$.ending)())oe().warn("Rejecting reset() when ending()",(0,O.shortStack)());else{this.onResultChange(),M(this,n,"f",l).clear(),M(this,n,"f",d).clear(),M(this,n,"f",f).clear(),M(this,n,"f",c).clear(),this.summary.clear(),_(this,n,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new n(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return M(this,n,"f",h).push(i),this.all.unset(),i}constructor(e,t,i,s,a,l,u,c,d,f,h,m,b,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=s,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=f,this.errorLinks=h,this.onReset=m,this.ttlMs=b,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),w.set(this,(0,E.lazy)((async()=>{await M(this,p,"f").prior(),(0,C.eql)(M(this,g,"f"),M(this,r,"m",v).call(this))||(this.onReset?.(),await this.refresh(),M(this,w,"f").unset())}))),this.refresh=(0,E.lazy)((()=>new q.Deferred("refresh").observe((async()=>{await M(this,p,"f").prior();const e=M(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,H.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[I.HealthCheckSections.ordinal(this.section),l??999,this.id],_(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>M(n,n,"f",o).enqueue({name:this.id,l:()=>M(this,r,"m",S).call(this,a)}),ttlMs:b}),"f"),this.isCritical&&M(this,p,"f").watchLater({onChange:n.onCriticalResult,onError:n.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>M(this,w,"f").call(this)))}isStale(){return M(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return M(this,p,"f").settledCount()}reset(){return M(this,p,"f").unset(),this.onReset?.(),_(this,g,{starting:!0},"f"),this}setTTL(e){M(this,p,"f").setTTL(e)}result(){return M(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return M(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return M(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??M(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,T.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,T.isNotEmpty)(i)&&(r.links=(0,T.uniqBy)(i)),(0,T.isNotEmpty)(t)&&(r.buttons=(0,T.uniqBy)(t)),r}t.HealthCheck=ae,n=ae,p=new WeakMap,g=new WeakMap,y=new WeakMap,w=new WeakMap,r=new WeakSet,a=function(){return(0,T.filterInPlace)(M(this,n,"f",s),(e=>!e.isPending)),M(this,n,"f",s)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=oe().tap({level:"warn",msg:"#summary()",result:(0,se.summarizeHealthChecksSync)({errors:M(this,n,"f",l),skipPending:M(this,n,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&_(this,n,!0,"f",u),i.state!==M(this,n,"f",c).last?.state&&M(this,n,"f",c).push({state:i.state,ts:Date.now()}),i},v=function(){return(0,L.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},S=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();oe().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,O.shortStack)()}),_(this,g,M(this,r,"m",v).call(this),"f");try{if((0,Z.getDevEnvFlag)("PS_SLOMO")&&await(0,k.delay)((0,A.randomInt)(.3*i,.7*i)),this.isSkipped())return M(this,r,"m",b).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const n=await(0,N.thenOrTimeoutError)(e(),i);return M(this,r,"m",b).call(this,{test:n,elapsedMs:Date.now()-t})}catch(e){return M(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},b=function({test:e,src:t="#toResult",elapsedMs:i}){var r,s;const o=n.normalizeMsg(e.msg),a=e.level??((0,z.toS)(o).toLowerCase().includes("error")?"error":(0,z.toS)(o).toLowerCase().includes("warn")?"warn":"ok"),l=(0,T.compact)([...e?.links??("ok"===a||"pending"===a?this.okLinks:"warn"===a?this.warnLinks:"no-library"===a?this.noLibraryLinks:"error"===a?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:a,msg:o,elapsedMs:i,...le(l)};return u.runCount=(_(this,y,(s=M(this,y,"f"),r=s++,s),"f"),r),(0,$.ending)()?u:this.logger.tap({level:ne.HealthCheckLevelToLogLevel[a],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const n=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,D.toNotBlank)((0,Y.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,X.isFatalError)(e)&&n.toLowerCase().includes("warn")?"warn":"error"),M(this,r,"m",b).call(this,{test:{msg:n,level:t},src:"#toErrorResult",elapsedMs:i})},s={value:[]},o={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},f={value:new U.CountingSet},h={value:[]},ae.all=(0,E.lazy)((()=>Object.freeze((0,x.sortBy)(M(n,n,"f",h),(e=>e.sortBy))))),ae.onCriticalResult=(0,G.debounce)((()=>{oe().info("onCriticalResult()",n.summary.refresh())}),250),ae.summary=(0,E.lazy)((()=>M(n,n,"m",m).call(n))),ae.resetDebounced=(0,G.debounce)((()=>n.reset()),50)},85021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),n=i(50268),s=i(459),o=i(23560),a=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,o.isPermaService)(t)&&(e===n.HealthCheckLevels.error||(0,o.isLibraryRequiredService)(t)&&e===n.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,a.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),n=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,n.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const n=r(i(48161)),s=i(19851),o=i(82950),a=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),f=i(23560),h=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,f.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,o.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return n.default.totalmem()h.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:h.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(h.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*h.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:h.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:h.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),a.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:a.minuteMs,later:async()=>g()})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),n=i(42659),s=i(45599),o=i(41400),a=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),f=i(23560),h=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const n=new Map;for(const e of t??[])n.set(e.id,e);if(null!=e)for await(const t of h.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))n.set(t.id,t);return[...n.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:f.serviceName.prior()??process.title}})));function S(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),s=i.length,o=i.map((e=>e.id)),c=t.length-s,d=0===s,f=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(f.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:o,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",f.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const n=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(n)){const e=t.filter((e=>!n.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+n.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:o,pendingCount:s,settledCount:c,linkIds:n.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,a.flatten)([...n,...e].map((e=>e.msg[0])))])},meta:{checks:n.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:o,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,n.fmtDateShort)(Date.now())]}})}(0,o.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),n=i(33374),s=i(31586),o=i(21605),a=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,n.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,a.toS)(e).split(/[x×]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:o.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),n=i(31586),s=i(50213),o=i(56519),a=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,n.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,o.thenMap)((0,a.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),n=i(41400),s=i(54993),o=i(19851),a=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),f=i(78330),h=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),v=(0,o.lazy)((()=>(0,a.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,o.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,f.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,h.hasPacman)()&&(i=(await(0,h.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,n.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),n=i(22573),s=i(42659),o=i(41400),a=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),f=i(28874),h=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,n.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:f.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,o.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,h.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(f.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:f.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(a.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),n=i(54993),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&s.test((0,n.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),n=i(19851),s=i(42659),o=i(59455),a=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),f=i(46199),h=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),S=(0,n.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,n.lazy)((()=>(b(),g.PosixFile.for((0,h.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,n.lazy)((()=>{h.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const n=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const s=n.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,f.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const o=s.join(i+r);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:o}),o}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,o.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,a.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const n=await P(e,t,i);return await n.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),n}catch(r){return S().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),n=i(33374),s=i(31586),o=i(34666),a=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,a.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,o.lt)((0,s.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,a.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,n.maybeDimSwap)(e.dimensions,e.rotation),(0,n.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),n=i(31586),s=i(80049),o=i(50213),a=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),f=(0,r.lazy)((()=>(0,o.mkLogger)("img.RawInfo"))),h=(0,r.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:a.ShortCommandTimeoutMs})));async function m(e){return h().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,s,o]=e.split("\t"),a=(0,n.toGt0)(s),l=(0,n.toGt0)(o);return null==a||null==l?f().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):f().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:a,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>h.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?h.prior()?.clear():h.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{f().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const n=r(i(9288)),s=i(19851),o=i(41400),a=i(50213),l=i(28874),u=i(15674),c=(0,s.lazy)((()=>(0,a.mkLogger)("img.Sharp")));function d(e,t){return(0,n.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,s.lazy)((()=>{n.default.simd(l.Settings.enableSIMD.valueOrDefault),n.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),n.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,o.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),n=i(40958),s=i(41400),o=i(50213),a=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,o.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:f().test(t)||!d().test(t),meta:{err:e,allow:f().test(t),block:d().test(t),validationErrorAllowlist:f().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,a.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),f=(0,r.lazy)((()=>(0,a.orRegExpPatterns)((0,n.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>f.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),n=i(40958),s=i(38639),o=i(42659),a=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),f=i(7282),h=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),v=i(56038),w=i(31562),S=i(98314),b=i(34102),P=i(88561),M=i(95696),_=i(17217),E=i(74128),T=i(31843),x=i(70417),D=i(33847),k=i(28874),C=i(94678),O=i(43207),I=i(47783),F=i(16170),L=i(95141),A=i(1078),R=i(63870),N=i(89782),j=i(13940),B=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,f.isProd)()&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,B.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,a.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,T.lerp2d)(e,{x:76800,y:k.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:k.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:o.minuteMs})));async function H(e){return await(0,t.isVideoSupported)()?M.PosixFile.for(await(0,t._extractVideoFrame_)((0,_.toNativePath_)(e))):void 0}async function G(e,t){const i=V("extractVideoFrame",e),r=M.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,B.isFFmpegSupported)())return i.throw("no video implementation");const n=await(0,j.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+n+")");const a=await r.mtimeMs();if(null==a)return i.throw("null mtime");const l=await(0,I.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,L.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,A.extractSizeInfoFromTags)(l,u)?.dimensions,d=await n.stat(),f=null==d?void 0:await(0,N.dimensions)(n);if(null!=d&&d.mtimeMs>a&&null!=f&&(null==c||f.height===c.height&&f.width===c.width))return i.debug("prior dest, "+n+" seems reasonable",{srcDim:c,destDim:f}),n.nativePath;const h=(0,O.extractDurationSec)(l),m=Math.min(h??0,k.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:h}),await n.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,B.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*o.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,I.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),n.nativePath}async function q(){return k.Settings.transcodeVideos.valueOrDefault&&await(0,B.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await q())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,I.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,F.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const s=(0,O.extractDurationSec)(i);if(!(0,c.gt)(s,k.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const o=(0,n.compactBlanks)([i.AudioFormat]),a=o.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,n.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(a&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:o,isSafeAudioCodec:a,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=H,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>G(e)}),t.__extractVideoFrame_=G,t.isVideoTranscodingSupported=q,t.needsTranscoding=$;const J=new g.TTLMap(o.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await q())return;const s=Date.now(),o=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return o.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void o.info("no transcoding needed");const a=await e.size();if(!(0,u.gt0)(a))return o.throw("source is empty or cannot read");const d=await(0,I.readTags)(e),f=(0,A.extractSizeInfoFromTags)(d),m=(0,O.extractDurationSec)(d);if(null==d||null==f||null==m)return o.throw("failed: missing video metadata",{sizeInfo:f,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return o.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,I.readRawTags)(t),r=await(0,I.readRawTags)(e),n=(0,O.extractDurationSec)(r),s=(0,O.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(n,s,1.5),meta:{srcDurationSec:n,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,i))return o.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),n=k.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,n))return r.throw("invalid width: "+s,{ignorable:!0});const o=i.ImageHeight;if(null!=o&&!(0,u.gte)(o,n))return r.throw("invalid height: "+o,{ignorable:!0});const a=(0,C.extractBitrateKbps)(i)??k.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,h.mapGt0)(s,(e=>(0,h.mapGt0)(o,(i=>(0,u.clamp)(0,a,(0,t.bitrateKps)(e*i)))))),c={width:s,height:o,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,v.time)("video.transcode:"+e,(async()=>{const t=K(a,g.videoBitrateKbps,m);return await i.applyWip_({fn_:a=>async function(a){o.info("starting...",{destWip:a});const f=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),h={src:e,dest:a,halt:r.halt,...g},m=k.Settings.transcodeMaxDim.valueOrDefault,p=(0,x.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?o.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(h.width=(0,u.roundEven)(e.width),h.height=(0,u.roundEven)(e.height),o.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await f.observe((0,B.ffmpegTranscode_)(h));0!==t.code&&o.throw((0,n.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,E.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-s})}catch(t){throw(0,E.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,S.errorToS)(t),elapsedMs:Date.now()-s}),o.error("transcode failed",{error:t}),t}}(a),skipFsLock:!1,timeoutMs:0}),i}))),o.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await H(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,B.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),n=i(22573),s=i(38639),o=i(42659),a=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),f=i(56519),h=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),v=i(84258),w=i(28874),S=i(76280),b=i(63870),P=i(19769),M=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function _(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:w.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=_;const E=/ffmpeg version n?(?\S+)/i,T=(0,u.lazy)((async()=>{const e=await _();if(null==e)return void M().info("failed to find ffmpeg in $PATH",{ffmpegPath:w.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,b.commandTimeoutMs)(),ignoreStderr:!0}),i=E.exec(t.result)?.[1];return M().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function x(){T.unset(),t.ffmpegVersionDescription.unset()}function D(e){const t=e?.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault;return(0,n.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function k(e){const t=[...w.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(w.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function O(e){const t=w.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,f.thenMapOr)(T(),(e=>"version "+e),(()=>"(not found)")))),(0,a.later)((()=>{(0,g.ee)().on("clearCache",x),(0,g.ee)().on("clearToolCache",x)})),t.ffmpegVersion_=async function(){return await T.prior()??T.refresh()},t.isFFmpegSupported=async function(){return null!=await T()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:o.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,h.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*o.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=k,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...k(t),...O(t),...D(t),"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){M().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,v.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return M().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return M().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await _(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),n=i(84777),s=i(8103),o=i(43334),a=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>o.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,n.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(a.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},42042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(22573),n=i(28874),s=i(81674);t.getEmail=async function(){const e=n.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,s.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),n=i(40958),s=i(42659),o=i(34666),a=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,a.intersection)(this._sids,this._l.uids),t=(0,n.uniq)(e.map(c.getScheme)),i=(0,n.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,o=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+s.dayMs,Date.now());return this.meta[(0,u.k)().o]=o,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,o&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,o.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),n=i(22573),s=i(38639),o=i(45599),a=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),f=i(79114),h=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),v=i(50213),w=i(56519),S=i(76596),b=i(46292),P=i(87290),M=i(77740),_=i(34102),E=i(83278),T=i(28874),x=i(37692),D=i(71706),k=i(83950),C=i(72042),O=i(33603),I=i(48132);t.k=(0,y.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const F=(0,o.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function L(e){const i=await(0,C.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,S.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const n=(0,S.utcIsoToTs)(i[(0,t.k)().r]);if(null==n)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(n),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function A(e,i,r,s){try{return(0,n.blank)(e)||e===(0,t.k)().f?void 0:k.L.for({str:e,l:await L(e),sids:null!=s?s:await(0,O.sids)({timeoutMs:r}),src:i})}catch(i){return F().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await A((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,I.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function j(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=L,t.v=A,t.vok=async function(e,t,i){if((0,n.blank)(e))return;const r=await A(e,t,i);return(0,s.isTrue)(r?.ok)&&r instanceof k.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,O.sids)({timeoutMs:I.UserTimeoutMs}),i=(0,u.map)((0,b.configDir)(),(e=>E.BaseFile.for(e))),n=(s=(0,l.flatten)((await(0,w.someOrTimeout)([()=>function(e){return A(T.Settings[(0,t.k)().L].value,"Settings",I.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:I.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(s.filter((e=>null!=e&&((0,h.isError)(e)&&F().warn((0,t.k)().d+": ",e),null!=e&&!(0,h.isError)(e)&&null!=e?.l))),(e=>[!e.ok,f.S.indexOf(e.l?.[(0,t.k)().T])??f.S.length+1,-(e.l?.exp?.getTime()??1)])));var s;return F().tap({msg:(0,t.k)().d+"()",result:n})})),(0,a.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset())),x.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=j,t.l=async function(){try{return await j()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await j()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),n=i(19851),s=i(22573),o=i(71706);t.l=(0,n.lazy)((()=>(0,o.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const n=(0,s.notBlankOr)(i.k,(0,t.l)().d),o=(0,t.l)().o.find((e=>e.k===n));if(null==o)throw new Error("Unknown key");return r.V2.verify(e,o)}},84194:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const s=i(40958),o=i(76790),a=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),f=i(19851),h=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,o.sortBy)((0,s.uniq)(e.filter(b)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,a.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,h.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const S=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function b(e){return null!=e&&null!=S().exec(e)}t.isValidUid=b,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,f.lazy)((()=>{const e=new d.CountingSet;for(const t of n(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return n(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||n(this,r,"f").has(t)||(n(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),n=i(22573),s=i(42659),o=i(45599),a=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),f=i(50213),h=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),v=i(45879),w=i(70854),S=i(57902),b=i(72308),P=i(43334),M=i(24399),_=i(7014),E=i(30933),T=i(71706),x=i(84194);t.k=(0,o.defer)((()=>(0,T.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const D=(0,o.defer)((()=>(0,f.mkLogger)((0,t.k)().n)));async function k(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=k;const C=(0,o.defer)((()=>(0,m.thenMap)(k(),(e=>(0,x.toUID)(x.S.lc,e.join(",")))))),O=/o\.e\.m\./i;async function I(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,S.LogLevels.trace))))).map(d.toS).filter((e=>(0,n.notBlank)(e)&&null==e.match(O)))}async function F(){return P.isLinux?(await I("lm")).map((e=>(0,x.toUID)(x.S.lm,e))):void 0}async function L(){return P.isLinux?(await I("lp")).map((e=>(0,x.toUID)(x.S.lp,e))):void 0}async function A(){return P.isLinux?(await I("lb")).map((e=>(0,x.toUID)(x.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*s.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,x.toUID)(e,t)))}catch(e){return void D().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function j(){return P.isWin?(0,x.toUID)(x.S.wm,await N()):void 0}t.win_machineGuid_=N;const B=(0,o.defer)((()=>(0,x.toUID)(x.S.cm,(0,E.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,x.toUID)(x.S.bm,(0,r.compactBlanks)(await I("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,x.toUID)(x.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,x.toUID)(x.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,b.networkMacAddresses)().map((e=>(0,x.toUID)(x.S.nm,e)))}async function H(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,x.toUID)(x.S.vl,e.uuid)))}const G=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[B,C,R,V,W,z,F,L,A,j,U,H],r=(0,a.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)G.add(e);return D().tap({msg:"sids()",result:(0,x.sortUids)([...G,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,h.isTest)())for(const t of e)G.add(t)},t.clearSids=function(){(0,h.isTest)()&&G.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},34474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(40958),n=i(42659),s=i(41400),o=i(96249),a=i(68708),l=i(34666),u=i(20214),c=i(71371),d=i(50213),f=i(42638),h=i(31562),m=i(98314),p=i(89968),g=i(28874),y=i(4904),v=i(57902),w=i(89241),S=i(83954);function b(e=10*n.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=b,t.allRecentLogEntries=async function(e=50){(0,S.writeRecentLogEntries)();const t=(0,a.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-n.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(b(),(e=>(0,f.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const o=[],a=new w.LogReader(e,(e=>o.push(e)));for(await(0,h.untilTrue)((()=>a.ready()),{timeoutMs:10*n.secondMs});!a.complete()&&!a.hasErrors();){const e=a.shift();null==e?await(0,s.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(o)&&(p.warn("Read error(s) for "+e,o),o.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-n.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,o.flatten)((0,a.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),n=i(19851),s=i(40958),o=i(22573),a=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),f=i(66184),h=i(93475),m=(0,n.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,o.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,h.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,f.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),n=i(23560),s=i(66184),o=i(72210);class a{log(e,t,i,r){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,r.lazy)((()=>new a))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),n=i(22573),s=i(26905),o=i(55835),a=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),f=i(76740),h=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new f.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,h.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),n=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof n.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),n=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new n.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(41400),a=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),f=i(23560),h=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,f.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,o.later)((()=>f.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,h.stripAnsiEsc)((0,n.uniq)((0,n.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,a.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,a.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(77030),o=i(19851),a=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),f=i(31586),h=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),S=(0,o.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,o.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,f.toInt)(t);return(0,a.blank)(e)||!(0,f.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),h.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),n(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const o=this.socket;null==o?n(this,r,"f").call(this):o.write(this.logFormatter.format(e,t,i,s)+b)}catch(r){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),n=i(42659),s=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??s.Settings.logDir.valueOrDefault,(0,n.fmtIsoDate)(t??new Date))}},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),n=i(31586),s=i(51926),o=i(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),n=i(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),f=i(28874),h=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=f.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,n.set(this,[]),s.set(this,(0,l.lazy)((()=>{a(this,n,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=h.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:a(this,n,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>a(this,s,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=a(this,r,"m",o).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=a(this,r,"m",o).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},n=new WeakMap,s=new WeakMap,r=new WeakSet,o=function(e){if(null==e||0===a(this,n,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return a(this,n,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),n=i(50989),s=i(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),n=i(68708),s=i(20214),o=i(51926),a=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,f=4){if(null==i)return null;if(f<0)return"…";if((0,o.isString)(i)||Buffer.isBuffer(i))return(0,o.ellipsize)(i.toString(),256,32);if((0,a.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,f-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,f-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),f-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const a=(0,u.mapNullEntries)(i,((t,i)=>e(i,f-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,n.keys)(i),(0,n.keys)(a));return(0,r.isNotEmpty)(c)&&(a["…"]="omitted: "+(0,o.ellipsize)(c.join(", "),128,32)),a}return i}},89241:function(e,t,i){"use strict";var r,n,s,o,a,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),f=i(38522),h=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),v=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),n.set(this,!1),s.set(this,!1),o.set(this,!1),this.from=(0,h.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,f.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,f.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,o,!0,"f")})),this.stream.on("data",c(this,r,"m",a).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,n,!0,"f")})),this.stream.on("end",(()=>{u(this,n,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,o,"f"),ended:c(this,n,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,s,"f")}}hasErrors(){return c(this,o,"f")}get ended(){return c(this,n,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(e){if(null===e)u(this,n,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,s,"f")&&(this.fileStream.pause(),u(this,s,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,s,"f")&&(this.fileStream.resume(),u(this,s,!1,"f"))}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),n=i(76760),s=i(1708),o=i(87997),a=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),f=i(34666),h=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),S=i(38836),b=i(99331),P=i(42638),M=i(76596),_=i(98314),E=i(89968),T=i(29882),x=i(28874),D=i(28981),k=i(20839),C=i(21727),O=i(66184),I=i(57902),F=i(72210),L=i(98192);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class R extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,a.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,x.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,T.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=n.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,F.setLogTailEnabled)(!0),this.flushTimeout=(0,o.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,o.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,F.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,O.ifLog)(I.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,n.join)(e,i))}))}catch(t){return void(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,_.errorToS)(t))))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,h.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,T.mkdirp_)(t),this.watchDir(t)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,_.errorToS)(e))))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,F.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,o.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,o.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,F.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,f.gte)(r,i))return;await(0,h.thenMap)((0,L.readLogEntries)(e,{start:r,end:i}),(e=>(0,F.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,O.ifLog)(I.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,a.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),n=i(82328),s=i(28981),o=i(20839),a=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const f=d(i(73024)),h=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),S=i(23560),b=i(81168),P=i(78406),M=i(25764),_=i(20197),E=i(14977),T=i(36868),x=i(28874),D=i(32105),k=i(20839),C=i(21727),O=i(66184),I=i(93475),F=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger,unref:!0,onEnd:()=>c(this,n,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,n.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:O.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const n={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(n.meta=(0,I.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(n)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,F.recentLogEntries)()),(0,F.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,n=new WeakMap,r=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),n=e.splice(0,i);this._linesSinceRotate+=n.length,t.write(n.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},o=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},a=function(e){return t=>(c(this,r,"m",o).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,h.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=f.default.createWriteStream(t).on("error",c(this,r,"m",a).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,T.endStream)(e.stream),x.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,r,"m",o).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),n=i(40958),s=i(55835),o=i(68708),a=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),n=i(84542),s=i(4001),o=i(13047),a=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,a.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),r=[],a=await(0,o.zcat)(e.nativePath,t);if(null!=a)for(const e of(0,n.splitLines)(a)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),n=i(76790),s=i(68708),o=i(89788),a=i(57902);t.SentLogLevels=(0,r.lazy)((()=>a.LogLevels.values.filter((e=>e!==a.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new o.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,n.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),n=i(41400),s=i(55835),o=i(37975),a=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),f=i(28874),h=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),S=i(24068),b=i(43705),P=i(51879);function M(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),_();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new b.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||f.Settings.logStdout.valueOrDefault||f.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,s.map)((0,y.logBroadcaster)(),(e=>i.push(e))),a.rootLoggers.set(i),f.Settings.tailLogs.valueOrDefault&&S.LogTail.instance()}function _(){const e=f.Settings.logColor.valueOrDefault;(0,o.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new h.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=M,t.setupLogFormatter=_,(0,n.later)((()=>{f.Settings.logStdout.watchLater(M),f.Settings.logDir.watchLater(M),f.Settings.tailLogs.watchLater(M),f.Settings.logColor.watchLater(_),f.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},83954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(89179);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},82647:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=i(57975),a=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),f=i(59455),h=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,h.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,f.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,f.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,r,"m",n).call(this,-1)}get p29(){return s(this,r,"m",n).call(this,-.5)}get p38(){return s(this,r,"m",n).call(this,-.25)}get p69(){return s(this,r,"m",n).call(this,.5)}get p84(){return s(this,r,"m",n).call(this,1)}get p98(){return s(this,r,"m",n).call(this,2)}get p99(){return s(this,r,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),n=i(55835),s=i(31586),o=i(30976),a=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,n.map2)(e,t,((e,t)=>(0,r.sum)((0,a.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,i[t]=o):r[t]=o}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let n=0;n(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function f(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=f(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=f,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function n(e,t,i=.5){return(1-i)*e+i*t}t.lerp=n,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,o]=(0,r.sortBy)(i,(e=>e.x)),a=o.x-s.x,l=(e-s.x)/a;return n(s.y,o.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),n=i(22573),s=i(55835),o=i(32639),a=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),n=this.normalizeToken(t);return r.length>=i&&r===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),n=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,n.toS)(e)}},17921:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),n=i(65713);function s(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,n.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),f=i(77377),h=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,r,"f")/(s(this,r,"f")+1)+e/(s(this,r,"f")+1),"f"),o(this,r,(t=s(this,r,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,u.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),n=v(t,(e=>(e-i)**2));return 0===n?0:r/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new h.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,f.intersection)(e,t).size/(0,f.union)(e,t).size,void 0)}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const n=r(i(48161)),s=i(19851),o=i(22573),a=i(41400),l=i(81168),u=i(28874);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??n.default.hostname())),(0,a.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,o.blank)(e)&&!(0,o.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??n.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),n=i(17344),s=i(96175),o=i(37805),a=i(81674),l=i(28874);function u(){return r.SimpleAppName+o.version}async function c(){return u()+" ("+(0,s.osFullName)()+") "+(0,n.EditionType)().toLowerCase()+"/"+await(0,a.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),n=i(19851),s=i(40958),o=i(22573),a=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),f=i(81168);function h(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),a.minuteMs),t.networkMacAddresses=(0,n.lazy)((()=>(0,s.uniq)((0,s.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),a.minuteMs),t.myExternalIpAddresses=h,t.myExternalIp4Addresses=function(){return h().filter((e=>!e.includes(":")))};const m=(0,n.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,o.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,o.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,f.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),n=i(19851),s=i(22573),o=i(42659),a=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),f=i(50213),h=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),S=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==S.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=b.exec(e)}function M(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,h.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=M,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=M(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs});const _=(0,n.lazy)((()=>(0,f.mkLogger)("net.nslookup")));(0,a.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=M(e)?r.promises.reverse(e):r.promises.resolve4(e),5*o.secondMs);if(t===c.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),n=i(42659),s=i(31586),o=i(97790),a=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),f=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*n.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,o.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,a.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*n.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),n=i(22573),s=i(45599),o=i(59455),a=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),f=i(63870),h=(0,s.defer)((()=>(0,a.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,o.toA)(await async function(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return h().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,n.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(h().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),n=i(38639),s=i(19851),o=i(59958),a=i(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),n=i(19851),s=i(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),n=i(50213),s=i(84777),o=i(68284),a=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,n.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,o.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,a.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=r(i(48161)),s=r(i(1708)),o=i(22573),a=i(38639),l=i(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=r(i(73024)),s=i(19851),o=i(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),n=i(59455),s=i(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),f=u(i(1708)),h=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),S=i(54993),b=i(54557),P=i(19851),M=i(50213),_=i(88158),E=i(409),T=i(78406),x=i(25764),D=i(99331),k=i(56519),C=i(46292),O=i(8769),I=i(83278),F=i(32144),L=i(29882),A=i(43334),R=i(24399),N=i(58261),j=(0,P.lazy)((()=>(0,M.mkLogger)("proc.Pids"))),B=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,F.isJsonExt)(t)&&(0,L.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,E.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??A.isWin,r=await this.pidfiles(),n=await this.pids(r??[]);if((0,h.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,N.pidInfos)(n);if(null!=a){for(const n of r){const r=await n.readJson();if(null==r){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:r,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!z(r,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:r,pidEntry:u}),await n.unlink("debug"),s.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:r}),o.push(W(l,i,!1)),s.push({...r,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(i&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const i=a(this,r,"m",s).call(this,e.pid),n=(0,v.opt)((0,_.Try)((()=>(0,L.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await i.writeJson_(l),j().debug("addPid() wrote "+i,l),i}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==f.default.pid}))}async pids(e=this.pidfiles()){return(0,h.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,r,"m",s).call(this,e);return(0,k.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new T.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:x.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=U,n=new WeakMap,o=new WeakMap,r=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new U(I.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=i(31421),s=i(48161),o=r(i(1708)),a=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),f=i(59455),h=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),S=i(56519),b=i(84777),P=i(8103),M=i(45879),_=i(43334),E=i(24399),T=i(45643),x=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function k(e){if(_.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,M.readFileMaybe)("/proc/"+i+"/stat")));return x().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,T.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?F:N)).filter((e=>D(e)&&t.includes(e.pid)));return x().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=D,t.pidInfo=async function(e){return(0,S.thenMap)(k([e]),(t=>(0,f.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,T.existingPids)(e),(t=>{const i=[o.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=k;const C="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function F(e){if(E.PowerShell.instance().ended)return R(e);const t=[C,"-Id",I(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(E.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const L={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,a.isNotEmpty)(e)){const i=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,L),r=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,h.toS)(e.CommandLine)}))));return r.find((e=>e.pid===o.default.pid))||r.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),r}async function N(e){return t=(await(0,b.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...L,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,h.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const j=(0,g.lazy)((()=>{try{if(_.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){x().warn("clk_tck failed",{error:e})}return 100})),B=(0,g.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,h.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(n)?{pid:i,cmd:r,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),n=i(22573),s=i(31586),o=i(29882),a=i(97352);t.progressEvtToS=function(e){const t=(0,n.blank)(e.path)?null:(0,o.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,n.notBlank)(e.op)&&(0,a.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),n=i(42659),s=i(31586),o=i(12089),a=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new a.TTLMap(15*n.secondMs))),t.recentDone=(0,r.lazy)((()=>new a.TTLMap(2*n.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,o.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),n=i(31586),s=i(409),o=i(78406),a=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class f extends o.EndableInterval{constructor(e,t,i,n=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:n,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=n,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,n.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,n.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=f},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),n=i(19851),s=i(22573),o=i(42659),a=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),f=i(50213),h=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),S=i(31562),b=i(84777),P=i(34102),M=i(43334),_=i(28874),E=i(63870),T="{ready}",x=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,f.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${T}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:T,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,x),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,h.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,n)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,n)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,x),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,n.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),n=i(38639),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),n=i(31586),s=i(97790),o=i(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(97790),o=i(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(r.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),n=i(22573),s=i(45599),o=i(50213),a=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function f(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function h(e,t,i){try{return(0,n.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:f,...e})}cron(e){return h(this.name,this.value,e)??h(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),n=i(91655),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},86941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(19851),n=i(59455),s=i(72993),o=i(46292),a=i(95696),l=i(50213),u=i(83179),c=i(28874),d=i(2858),f=i(84438),h=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),s=await t.resolve_();if(null==r||null==s||s.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:s?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+s.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(f.SettingsToml);if(await e.isNonEmptyFile()){const t=s.join(f.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=s.join("licenses");for(const r of(0,n.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const o=s.join("old");try{const e=await r.renameYMDHMS_({subdir:o.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+o,e)}}t.mergeUserDataDirs_=async function(){const e=(0,o.configDir)();if(null==e)return;const t=a.PosixFile.for(e);for(const e of[t.join((0,s.AppName)()),t.join((0,s.AppName)().toLowerCase()),t.parent().join((0,s.AppName)().toLowerCase())])try{await m(e,t)}catch(i){h().error("Failed to merge "+e+" and "+t,i)}h().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),n=i(22573),s=i(38639),o=i(42659),a=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),f=i(67958),h=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){M(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&_()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,n.blank)(m.Settings.assetPathnameFormat.value)&&(0,n.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*o.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const S=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],b={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function M(e){for(const t of S)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:b;for(const[e,i]of(0,a.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:h.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:f.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function _(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=M,t.disableExternalNetworkRequests=_},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),n=i(53265),s=i(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),n=i(31586),s=i(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class n extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),n=i(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,n,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=i(19851),a=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),f=i(55835),h=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),S=i(44198),b=i(96706),P=i(34102),M=i(28283),_=i(81075),E=i(98778),T=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,r,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?s(this,r,"m",n).call(this,e??t)+": "+i:null==this.fromEnv(e)?s(this,r,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,f.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,M.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(M.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return _.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,f.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,S.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&b.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,S.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&b.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,f.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],T.WrapComments);function i(e,i){(0,a.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],T.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,h.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+r],T.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,f.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,E.wrapTomlToLines)({lines:e,wrap:T.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,E.wrapTomlToLines)({lines:e,wrap:T.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,E.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),n=i(51168),s=i(76760),o=i(19851),a=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),f=i(68708),h=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),S=i(7282),b=i(12801),P=i(4328),M=i(70488),_=i(84248),E=i(5531),T=i(99315),x=i(34365),D=i(34580),k=i(96706),C=i(50274),O=i(33866),I=i(52086),F=i(48584),L=i(45969),A=i(43334),R=i(24540),N=i(70379),j=i(71300),B=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),H=i(30577),G=i(1485),q=i(19861),$=i(55111),J=i(30933),K=i(22859),Z=i(71988),Y=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),ne=i(57039),se=i(9945),oe=i(74589),ae=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),fe=i(81075),he=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:fe.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:fe.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Y.BooleanSetting({category:fe.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:fe.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:fe.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Y.BooleanSetting({category:fe.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Y.BooleanSetting({category:fe.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new he.StringArraySetting({aliases:["scanPath"],category:fe.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new he.StringArraySetting({category:fe.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:fe.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:fe.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:fe.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:fe.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:fe.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:fe.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:fe.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new ge.StringSetting({category:fe.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:fe.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Y.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:fe.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new oe.IntegerSetting({category:fe.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Y.BooleanSetting({category:fe.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:fe.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:fe.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Y.BooleanSetting({category:fe.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Y.BooleanSetting({category:fe.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:fe.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:fe.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new he.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:fe.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>q.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new he.StringArraySetting({category:fe.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>G.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new he.StringArraySetting({aliases:["ignoredMountpoints"],category:fe.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:G.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new he.StringArraySetting({category:fe.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>G.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Y.BooleanSetting({category:fe.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new he.StringArraySetting({category:fe.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:fe.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new he.StringArraySetting({category:fe.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new he.StringArraySetting({category:fe.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Y.BooleanSetting({category:fe.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Y.BooleanSetting({category:fe.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Y.BooleanSetting({category:fe.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new he.StringArraySetting({category:fe.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:fe.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:fe.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:fe.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:fe.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Y.BooleanSetting({category:fe.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:fe.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Y.BooleanSetting({category:fe.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,L.isDocker)()}),cspReportOnly:new Y.BooleanSetting({category:fe.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Y.BooleanSetting({category:fe.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:fe.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:fe.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new Y.BooleanSetting({category:fe.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,M.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:fe.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:fe.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:fe.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:fe.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:fe.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:fe.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:fe.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:fe.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:fe.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:fe.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:fe.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Y.BooleanSetting({category:fe.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:fe.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:fe.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:fe.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:E.CheckpointTypes,defaultValue:E.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:fe.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:x.SynchronousModes,defaultValue:x.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:fe.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:T.RepairModes,defaultValue:T.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:fe.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:fe.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:fe.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:fe.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Y.BooleanSetting({category:fe.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Y.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:fe.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Y.BooleanSetting({category:fe.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,L.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:fe.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:fe.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new he.StringArraySetting({category:fe.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:fe.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:fe.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Y.BooleanSetting({aliases:["transcodeVideo"],category:fe.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:fe.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:fe.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new he.StringArraySetting({category:fe.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new he.StringArraySetting({category:fe.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new he.StringArraySetting({category:fe.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Y.BooleanSetting({category:fe.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Y.BooleanSetting({category:fe.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Y.BooleanSetting({category:fe.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Y.BooleanSetting({category:fe.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new he.StringArraySetting({category:fe.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:fe.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:fe.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:fe.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new he.StringArraySetting({category:fe.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:fe.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:fe.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new he.StringArraySetting({category:fe.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Y.BooleanSetting({category:fe.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Y.BooleanSetting({category:fe.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Y.BooleanSetting({category:fe.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Y.BooleanSetting({category:fe.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:fe.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:H.UpdateChannels}),autoUpdateCheck:new Y.BooleanSetting({category:fe.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Y.BooleanSetting({category:fe.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Y.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:fe.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new de.OptionalStringSetting({category:fe.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Y.BooleanSetting({category:fe.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:fe.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:fe.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new he.StringArraySetting({category:fe.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:fe.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Y.BooleanSetting({category:fe.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Y.BooleanSetting({category:fe.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:fe.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,h.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:fe.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Y.BooleanSetting({aliases:["syncLibraryFirst"],category:fe.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Y.BooleanSetting({aliases:["syncLibraryLast"],category:fe.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new he.StringArraySetting({category:fe.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:fe.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:fe.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:fe.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:fe.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Y.BooleanSetting({category:fe.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Y.BooleanSetting({aliases:["noModelUpdates"],category:fe.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:fe.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Y.BooleanSetting({category:fe.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:fe.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new he.StringArraySetting({category:fe.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Y.BooleanSetting({category:fe.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Y.BooleanSetting({category:fe.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:fe.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Y.BooleanSetting({category:fe.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Y.BooleanSetting({category:fe.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Y.BooleanSetting({category:fe.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:fe.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:fe.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:fe.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:fe.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:fe.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Y.BooleanSetting({category:fe.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Y.BooleanSetting({aliases:["jpegMinimized"],category:fe.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:fe.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:I.CropStrategies.attention,strEnum:I.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:fe.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Y.BooleanSetting({aliases:["sharpen"],category:fe.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:fe.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:fe.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Y.BooleanSetting({category:fe.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:fe.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Z.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:fe.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Y.BooleanSetting({category:fe.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new he.StringArraySetting({category:fe.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Y.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:fe.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:fe.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:fe.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:fe.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:fe.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:fe.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:fe.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:fe.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:fe.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:F.SharpFailOns.truncated,strEnum:F.SharpFailOns}),validateRawImages:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Y.BooleanSetting({category:fe.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new he.StringArraySetting({category:fe.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:fe.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:fe.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new he.StringArraySetting({category:fe.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:fe.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:fe.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:fe.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Y.BooleanSetting({category:fe.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:fe.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:fe.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:fe.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:fe.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:fe.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new he.StringArraySetting({category:fe.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:fe.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:fe.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:fe.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new he.StringArraySetting({category:fe.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:fe.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:fe.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:fe.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:fe.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:fe.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,L.isDocker)()}),tagDisplayNameFSLabels:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new he.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:fe.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new he.StringArraySetting({category:fe.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Y.BooleanSetting({category:fe.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:fe.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Y.BooleanSetting({category:fe.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:fe.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Y.BooleanSetting({category:fe.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:fe.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,f.entries)(t.Settings))i._setName(e);function be(e){const i=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,L.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(i).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,fe.SettingCategories.indexOf(e.category)??fe.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,k.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,f.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>fe.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>fe.LibraryCategories.includes(e.category)))));const Me=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Me().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),n=i(31586),s=i(7282),o=i(49776),a=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),f=i(96706),h=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,f.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(h.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(22573),a=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),f=i(57924),h=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),S=i(81168),b=i(83556),P=i(87290),M=i(98314),_=i(34102),E=i(83278),T=i(95696),x=i(60865),D=i(4175),k=i(83179),C=i(81075),O=i(28874),I=i(41692),F=i(84438),L=i(32707),A=i(6707),R=i(98778),N=i(55018),j=i(10357),B=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(F.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return X(E.BaseFile.for(e))}async function W(){try{return(0,o.toNotBlank)((await(0,A.readTomlFile_)((0,L.systemSettingsFile)()))?.[O.Settings.libraryDir.name])}catch{return}}function U(e){return(0,A.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function H(){return U((0,L.systemSettingsFile)())}function G(e){return U(z(e))}function q(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return B().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:O.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void B().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),n=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let n="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(n,i),B().info("writeToml(): wrote settings",{dest:n,file:e,nonDefaults:(0,k.settingsToObj)(i),wip:r}),r){const t=await(0,A.readTomlFile_)(n),i=await(0,A.readTomlFile_)(e);(0,u.eql)(t,i)?(B().info("Equivalent contents",{dest:n,file:e,a:t,b:i}),await n.unlink()):(B().info("Archiving prior, different contents",{dest:n,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await n.unwip_())}}async function K(e=(0,L.systemSettingsFile)()){const t=T.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,O.persistedSystemSettings)()),t}function Z(e){return X(z(e))}async function Y(e){await(0,P.setupLibraryDataDir_)((0,o.firstNotBlank)(e,O.Settings.libraryDir.value));const i=z(e);return B().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,O.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=B().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,n.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,M.errorToS)(e)),[]}}async function Q(e){const t=B().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,A.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const s=[],o=(0,n.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,O.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,O.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;s.push(e)}})));return t.info("loaded",{settings:(0,k.settingsToObj)(o),warnings:(0,n.toNotEmpty)(s)}),await(0,D.handleDeprecatedSettings)(),(0,D.handleMetaSettings)(o),{settings:o,warnings:s}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),a.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return O.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=H,t.librarySettingsVersion=G,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await H()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await G()&&await Y()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{B().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",q),(0,_.ee)().on("settingsChanged",q),O.Settings.libraryDir.watchLater(q)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,x.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(T.PosixFile.for(e),(0,O.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=Y,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([O.Settings.noNetwork,O.Settings.httpPort,O.Settings.license,O.Settings.logStdout,O.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(O.Settings))ee().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,j.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),O.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(T.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(T.PosixFile.forMaybe(z())?.unlink("trace")),(0,_.ee)().emit("clearCache"),I.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${x.versionMajorMinor}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,o={...e.addToJSON()};(0,n.mapNotEmpty)(e.altKeys,(e=>o.aliases=(0,f.orList)(e)));const a=(0,p.entries)(o).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,n.isNotEmpty)(a)&&a.push(""),i.push(...ie((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...a,`${e.key}=${(0,h.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),n=i(40958),s=i(22573),o=i(98553),a=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function f(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=f;class h extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:f,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=h},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class n extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),n=i(98553),s=i(55835),o=i(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,n=e.strEnum,(0,r.compact)((0,o.splitStringArray)(i)?.map((e=>n.getCI(e))));var i,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),n=i(81168),s=i(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),n=i(55835),s=i(46292),o=i(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,r.join)(e,o.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),n=i(44652),s=i(22573),o=i(76850),a=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),f=i(98778);function h(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?h((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>h(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,f.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),n=i(96249),s=i(98553),o=i(68708),a=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[n]:(0,a.wrap)(n.split("\n"),i)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),n=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=o(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function o(e){const t=(0,n.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),n=i(81168);t.bname=function(e,t=!0){let i=(0,n.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,n.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),n=i(19851),s=i(40958),o=i(76790),a=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),f=i(31586),h=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),v=i(81168),w=i(76596),S=i(79842),b=i(66649),P=i(21330),M=i(98725),_=i(928),E=i(54261),T=i(89724),x=i(17415),D=i(88600),k=i(51275),C=i(29882),O=i(17217),I=i(68284),F=i(57902),L=i(28874),A=i(65162),R=i(71300),N=i(14036),j=i(61424),B=(0,n.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,h.isObject)(e)&&(0,a.notBlank)(e.nativePath)&&(0,S.isDated)(e.date)&&(0,a.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,T.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,O.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,f.toGt0)(e.local)??(0,T.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,S.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(L.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,I.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,h.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,M.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,x.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,x.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,T.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,w.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,E.hasTime)(this.date)}hasMillis(){return(0,f.gt0)((0,_.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,x.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?L.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,S.datedToStartDateTime)(this.date)??(0,S.datedToDateTime)(this.date);if(null!=i)return{start:(0,T.datedToLocal)(i.minus(t)),end:(0,T.datedToLocal)(i.plus(t))};B().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:L.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return B().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,S.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function H(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],n=r;if((0,D.isValidDate)(t)){if((0,x.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||R.OverrideUTCZoneTags.includes(n))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,a.blank)(e.tzSource)?"":" from "+(0,v.stripPrefix)(e.tzSource,"from ");n+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,T.datedToLocalSec)(t),date:t,src:n,precisionMs:(0,S.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,S.datedToStartTs)(e.date)));if(null==r)return;const n=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,S.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),o=(0,p.leastBy)(n,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return B().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:n,earliest:o}),o}function G(e,t){if(L.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)])){const e=(0,M.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,S.datedToPrecisionMs)(e),l.secondMs])}}}function q(e){if(L.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,M.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(L.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,o.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function n(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,T.datedToLocal)(i.date),src:(0,v.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!L.Settings.usePathsToInferDates.valueOrDefault||!L.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:L.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),o=n("tags",H(t,L.Settings.capturedAtTags.values))??(i?void 0:n("siblings",await(0,j.inferCapturedAtFromSiblings)(e)))??n("tags",H(t,L.Settings.capturedAtTagsFallback.values))??(s?void 0:n("stat+bname",await(0,j.extractStatBname)(e)))??(s?void 0:n("stat+path",await(0,j.extractStatPathTime)(e)))??(i?void 0:n("siblings",await(0,j.inferCapturedAtFromSiblings)(e)))??(s?void 0:n("bname",G(e,t)))??(s?void 0:n("path",q(e)))??(L.Settings.useStatToInferDates.valueOrDefault?n("stat",await $(e)):void 0);return B().tap({level:F.LogLevels.debug,msg:"extractCapturedAt()",result:o})},t.capturedAtFromTags=function(e){return H(e,L.Settings.capturedAtTags.values)},t.capturedAtFromBasename=G,t.capturedAtFromPath=q,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),n=i(97352),s=i(95696),o=i(47783),a=i(16170);function l(e){if(null!=e&&(0,a.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,n.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,o.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const n=i(77988),s=r(i(76760)),o=r(i(1708)),a=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),f=i(23838),h=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),v=i(12168),w=i(56038),S=i(4867),b=i(36557),P=i(98247),M=i(21330),_=i(98725),E=i(23467),T=i(88561),x=i(95696),D=i(17217),k=i(16287),C=i(50213),O=i(17921),I=i(7282),F=i(88158),L=i(23560),A=i(28874),R=i(12089),N=i(81168),j=i(63870),B=i(15674),z=i(28544),V=i(43207),W=i(72180),U=i(75767),H=i(12788),G=i(80495),q=i(14036),$=i(67083),J=i(3432),K=i(28630),Z=i(15912),Y=i(30748),X=i(16170),Q=i(95141),ee=i(7330),te=i(54979),ie=i(1078),re=i(61424),ne=i(8791),se=(0,a.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const ae=(0,a.lazy)((()=>new b.BatchClusterObserver("ExifTool",new n.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,b.batchClusterOptions)((0,I.isTest)()?8:(0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,B.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function le(){const e=ae();return e.ended?ae.refresh():e}function ue(e=!1){return(0,d.map)(ae.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeoutError)({p:le().version(),timeoutMs:A.Settings.statTimeoutMs.valueOrDefault})},t.exiftoolVersionMaybe=function(){return(0,d.map)(ae.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,j.commandTimeoutMs)()})))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,a.lazy)((()=>new T.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,a.lazy)((()=>new T.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,h.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function fe(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function he(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,N.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),n=await e.sidecar(),s=(0,X.isImageMimeType)(r)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,o=(0,X.isVideoMimeType)(r)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,a=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await n.exists(),l=s||o||a;return se().tap({msg:"writeTagDest()",result:l?n:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:o,writeMetadataToSidecarsIfSidecarExists:a}})}async function pe(e,i=!0){const r=x.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void se().debug("readRawTags("+r+"): invalid file, returning null.");const n=await(0,t._readRawTags)(r.nativePath);if(null==n||!i)return n;se().trace("readRawTags()",{pf:r,pickedFileTags:(0,h.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await r.jsonSidecars())s.push([e,(0,K.readJsonSidecar)(e,n.tz)]);for(const e of await r.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const o={original:{},MIMEType:(0,u.mapNotBlank)(n.MIMEType,X.normalizeMimetype),...n},a=[];for(const[e,i]of s){if(null==i)continue;const r=await i;if(null==r)continue;const n=(0,h.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,h.values)(n))?((o.sidecars??(o.sidecars=[])).push(e.base),a.push(...(0,g.toA)(r.History)),(0,F.assignNullishFields)(o.original,(0,h.pick)(o,...(0,h.keys)(n))),(0,h.assignFields)(o,n),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return o.inferred=(0,$.getInferredHistoricValues)(a,e),(0,F.assignNullishFields)(o,o.inferred),o.Rotation=(0,Q.orientationToRotation)(o.Rotation),se().debug("readRawTags() final",{pf:r,inferred:o.inferred,pickedResult:(0,h.pick)(o,"tz","tzSource",...A.Settings.capturedAtTags.values)}),o}async function ge(e,t){return null==t?void 0:(0,w.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const a=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,a);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:a}),null!=l?.tz){const e=s.tzSource!==n.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values])if(!(0,W.isUtcTagName)(t)){const i=s[t];i instanceof n.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,h.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,h.assignFields)(s,l)}const c=a?(0,Y.extractMakeAndModel)(s):await(0,re.inferMakeAndModel)(e,s);c.Make!==(0,Y.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,Y.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(s),f=await(0,z.extractCapturedAt)(e,s,a);if(null==f)return void se().info("No capturedAt for "+e);!a&&f.isInferred&&(s.inferred.capturedAt=f);const m=(0,G.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:f,exposureSettings:m,...(0,ne.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,h.pick)(s,"LensSerialNumber")}),...g,duration:(0,V.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};(0,I.isTest)()&&(y.__parsedBy__=o.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:a,...y,inferred:s.inferred,original:s.original,pickedResult:(0,h.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,h.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,h.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,h.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=x.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,F.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=fe,t.overwriteTags_=async function(e,t){try{await(0,w.time)("exiftool.overwriteTags:"+e,(async()=>{await le().write(e.nativePath,t,await he(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=he,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("exiftool.writeTags:"+e,(async()=>{const r=new f.MultiMap;for(const[n,s]of(0,h.entries)(t)){const t=await me(e,n,i);r.add(t.nativePath,[n,s])}for(const[t,i]of r.entriesArray()){const r=x.PosixFile.for(t),n=(0,h.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:n}),await le().write(r.nativePath,n,await he(r)),A.Settings.overwriteOriginal.valueOrDefault||await fe(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...A.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,q.isVideoExt)(s.default.extname(e))?[]:["-fast"]],r=await(0,w.time)("exiftool.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,h.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,h.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const n=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(n)&&(r.problems=n),oe&&(r.__instance=(0,O.safeUUID)()),r}}),t.parseTags=ge},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(98553),a=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),f=i(54993),h=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,o.stringify)((0,u.fromEntries)(t))}function b(e){return(0,f.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new a.MultiMap,r=[];for(const o of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(n=e[o])||(0,s.blankish)(n)||(0,l.isNumber)(n)&&(0===n||1===n)||null!=t.zeroesRe.exec((0,f.toS)(n)))continue;const a=e[o],u=b(e[o]),c=(0,t.Tag2SynonymGroup)().get(o);if(null!=c){if(i.includes(c,a)||i.includes(c,u))continue;i.add(c,a)}r.push([o,(0,l.gt0)(a)?a:u])}var n;return S(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:r,parser:n}){const s=n(e[i]),o=n(t[i]),a=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==o||(0,l.approximates)(s,o,a)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function T(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),s=_(i);if(null==r||null==s||e===i)return;const o=(0,h.intersection)((0,u.keys)(r),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of o){const t=r[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const o=(0,u.values)(t).map(f.toS),a=(0,u.values)(i).map(f.toS);if((0,n.includesAny)(o,a))continue;const l=(0,h.least)((0,u.keys)(t)),c=(0,h.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return T({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=T,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),n=i(54993),s=/undefined|null|none|n\/a|unknown/i;function o(e){return null==e||(0,r.blank)(e)||s.test((0,n.toS)(e))}t.isExifUnset=o,t.toExifDefined=function(e){return o(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),n=i(22573),s=i(31586),o=i(68708),a=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,n.firstNotBlank)((0,a.toS)(e.ExposureTime),(0,a.toS)(e.ShutterSpeed),(0,a.toS)(e.ShutterSpeedValue),(0,a.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,o.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,a.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),n=i(40958),s=i(96249),o=i(23838),a=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),f=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const h=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,a.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,a.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,n.uniq)((0,s.flatten)((0,a.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return h()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new o.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:f.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:f.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:f.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:f.ExtTypes.Video},{exts:c.SidecarFiletypes,type:f.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:f.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:f.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,a.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,f.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,f.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(f.ExtTypes.Sharp)||t.includes(f.ExtTypes.RawImage)?"image":t.includes(f.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,f.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,f.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,f.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,f.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,f.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,f.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,f.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=f.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),n=i(45599),s=i(68708),o=i(50213),a=(0,n.defer)((()=>(0,o.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,s.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:n}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[n])&&(t[i]=t[n]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){a().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,s.pick)(e,"Directory","FileName"));for(const t of(0,s.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),n=i(19851),s=i(40958),o=i(76790),a=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),f=i(50989),h=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),v=i(50213),w=i(81168),S=i(66649),b=i(17415),P=i(29882),M=i(95696),_=i(17217),E=i(28874),T=i(47783);function x(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:n}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(n??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,f.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=x,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,n.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,h.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function O(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,a.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function I(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function F(e,i,r){if(null==e||(0,a.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const n=(0,_.toNativePath_)(e),o=await(0,T._readRawTags)(n),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(o,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const f=M.PosixFile.for(e);return await(0,T.overwriteTags_)(f,c),f.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const n=(0,m.toA)(e);if((0,s.isEmpty)(n))return{};const l=(0,o.sortBy)(n.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,a.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,a.notBlank)(t)){const r=O(e);(0,a.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=O,t.inferredToTags=I,t.ensureInferredHistoryRecords=async function(e,i,r){const n=x(t.Actions.infer,r),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?I(r):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:n,additionalTags:s}),F(i,n,s)},t.ensureHistoryRecords=F},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const n=r(i(53705)),s=i(77988),o=i(19851),a=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),f=i(17415),h=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),w=i(14245),S=i(61424),b=(0,o.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,w.omitInvalidGeolocationTags)(t);{const e=M(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,f.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,a.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,f.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=_(e,t);if(null!=i)return i}if(!i){const t=await(0,S.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function M(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return b().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,n.default)(t,i);return b().tap({msg:"zoneFromLatLon()",result:(0,f.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return b().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function _(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,h.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const n=(0,u.toDated)(t[r]);if(null==n||(0,h.isValidDate)(n))continue;const s=Math.round(15*i.diff(n,"minutes").as("minutes")/15),o=(0,f.normalizeZoneOffsetMinutes)(s),a=0===o?void 0:(0,f.normalizeZone)(o);if(null!=a)return b().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:a.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(n),rawTzoffsetMinutes:s,normalizedOffsetMinutes:o}})}}t.maybeInferTimezone=async function(e,t,i){return b().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=M,t.inferTzOffsetMinutesFromFilename=_},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),n=i(40958),s=i(22573),o=i(38639),a=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),f=i(48884),h=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const n=(0,p.normalizeZone)(e?.formatted),s=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:n??t??r.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,f.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,h.validLat)(e)?e:void 0)),GPSLongitude:(0,f.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,h.validLon)(e)?e:void 0)),GPSAltitude:(0,f.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,a.map)(e.favorited,o.isTrue),peopleNames:(0,n.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,n.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(55835),a=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),f=i(28874),h=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,h.make)(e.LensMake),i=(0,h.make)(e.Make),r=[],a=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,n.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:a,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:a});const o=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))o.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:a});for(const i of(0,n.compactBlanks)([t,...f.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:a});o.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:a})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,o.map)(e.lensInfo,b)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,o.mapOr)((0,a.toFloat)(e),(e=>String((0,a.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),n=i(22573),s=i(55835),o=i(68708),a=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function f(e,t,i=""){const r=e.replace(t,i);return r===e?e:f(r,t,i)}const h=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=h.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=f(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,a.toS)(e.HandlerDescription))||y.test((0,a.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,o.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,n.blank)(e))for(const[t,i]of(0,o.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const r=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=f(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),n=i(54993),s=i(2322),o=i(277),a=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function f(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function h(e){const t=(0,n.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,n.toS)(e))},t.isImageMimeType=function(e){return(0,n.toS)(e).startsWith("image/")},t.isVideoMimeType=f,t.normalizeMimetype=h,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&h(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&h(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(f(t)?await(0,l.isVideoSupported)():(0,a.isHeifMimeType)(t)?await(0,o.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),n=i(54993),s=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??a(e.Orientation)};const o=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function a(e){return(0,r.isRotation)(e)?e:null!=e?o.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,n.toS)(e).startsWith("Mirror")},t.orientationToRotation=a;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),n=i(31586),s=i(28874);function o(e){const t=(0,n.toInt)(e);return null==t?void 0:(0,n.clamp)(-1,5,t)}function a(e){return o(e?.Rating)??(0,n.mapNumeric)((0,n.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=o,t.extractRating=a,t.extractLiked=function(e){const t=a(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),n=i(22573),s=i(55835),o=i(88561),a=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new o.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,n.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,a.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),n=i(40958),s=i(22573),o=i(81168),a=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),f=i(14036);function h(e,t,{ignoreCase:i}){return i?(0,o.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,u.isJsonExt)(i.ext),l=a||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(h(e.base,i.name,{ignoreCase:l}))return!0;if(h(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(h(e.name,t,{ignoreCase:l}))return!0}const m=a||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,n.uniq)([e.base,e.name,(0,f.stripExt)(e.base)]))for(const e of(0,n.uniq)([i.name,i.name,(0,f.stripExt)(i.name)]))if(h((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return a&&function(e,i){const r=(0,o.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function n(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=n(e.slice(r.length)),l=n(i.slice(r.length));return a&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,a.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,o.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),n=i(22573),s=i(42659),o=i(33374),a=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),f=i(34943),h=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,n.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,r,await(0,f.rawInfo)(e));const s=b(i,r);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,h.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,a.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,o.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:f.rawInfo,fileDimensions:r}});const n=(0,o.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:n.height,ImageWidth:n.width,aspectRatio:(0,d.aspectRatio)(n),dimensions:n,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:f.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),n=i(51168),s=i(19851),o=i(40958),a=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),f=i(48884),h=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),v=i(79842),w=i(21330),S=i(98725),b=i(51275),P=i(35280),M=i(19748),_=i(88561),E=i(95696),T=i(65238),x=i(17217),D=i(57902),k=i(28874),C=i(80496),O=i(65162),I=i(28544),F=i(47783),L=i(88840),A=i(30748),R=i(16170),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),j=7;async function B(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,T.isSlowDir)(e.nativePath)&&!await(0,T.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,A.extractMakeAndModel)(await(0,F.readRawTags)(t));if((0,h.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,h.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await B(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await G(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(L.ExtTypes.AssetFile);function H(e){return null==e?[]:(0,o.compact)((0,f.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function G(e,t=7,i=!0){if(!await B(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const n=(0,a.sortBy)(r,(e=>(0,O.bname)(e))),s=(0,x.findFileIndex)(e,n);if(s<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),G(e,t,!1)):void 0;const l=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[n.slice(s-2*t,s),n.slice(s+1,s+1+2*t)],d=[],f=[];for(;(0,o.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,o.isNotEmpty)(c)&&f.length=l&&f.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:f},meta:{f:e}})}t.nearestSiblings=G,t.nearestSiblingTzOffset=async function(e){if(!await B(e.parent()))return;const t=H(await G(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,j);for(const t of e){const e=await(0,F.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,o.uniq)([(0,O.bname)(e,!0),(0,O.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:n.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(55835),a=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),f=i(81168);function h(e){return(0,u.toS)((0,a.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(h))}function p(e,i=t.TagSep){return m(e).map((e=>(0,a.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?h((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,f.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=h,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,o.mapOr)(v(e),(e=>(0,f.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,n.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,n.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),n=i(22573),s=i(68708),o=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,n.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,o.toS)(e[r]).trim();if((0,n.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(96249),a=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),f=i(7014),h=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,f.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),h.URI.file(e)])}async function S(e){const t=await w(e);return(0,n.uniq)((0,o.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return h.URI.isUri(e)?e:h.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case a.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case a.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??h.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,n.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),n=i(57975),s=i(57160),o=i(22573),a=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),f=i(43334),h=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,n,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=n??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!h.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:n,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===n?n=this.query:null===n&&(n=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&r===this.path&&n===this.query&&s===this.fragment?this:new b(t,i,r,n,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const r=i[2]||g,n=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),o="psfile"===r&&s.startsWith("//")?s.slice(1):s,a=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(r,n,o,a,l,t)}static file(e){let t=g;if(f.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=f.isWin&&"file"===e.scheme?w.file(r.win32.join(E(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,a.map)(this.path,(e=>(0,d.findLast)(e.split(y),o.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return T(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=w;const S=f.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let n=0;n=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),void 0!==i&&(i+=e.charAt(n));else{void 0===i&&(i=e.substr(0,n));const t=P[s];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,n)),r=-1),i+=t):-1===r&&(r=n)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,f.isWin&&(i=i.replace(/\//g,"\\")),i}function T(e,t){const i=t?_:M;let r="";const{scheme:n,query:s,fragment:a}=e;let{authority:l,path:u}=e;if(n&&(r+=n,r+=":"),(l||"file"===n)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,o.mapNotBlank)(s,(e=>r+="?"+e)),a&&(r+="#",r+=t?a:M(a,!1)),r}function x(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+x(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>x(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),n=i(40958),s=i(50357),o=i(89937),a=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",o.PS_LOCAL_FILE_SCHEME,o.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,a.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const f=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function h(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&h(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return f().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||h(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,n.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),n=i(22573),s=i(51926),o=i(89937),a=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),f=i(85087);function h(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,n.blank)(e))return;if(null==(t=null!=t&&(0,a.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,n.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:o.PS_LOCAL_FILE_SCHEME,authority:(0,f.volsha)(t.uuid),path:u})},t.joinMountpoint=h,t.psfile2nativePath=async function(e,t){if(e.scheme!==o.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,n.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,s=(0,n.notBlank)(t)&&!t.includes(i);if(s&&!(0,n.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,f.volsha)(i.uuid)===e.authority)return h(i.mountpoint,e.path)}const a=await(0,c.bestVolumeForVolsha)(e.authority);return null!=a?h(a.mountpoint,e.path):s&&(0,n.notBlank)(t)?h(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),n=i(22573),s=i(51926),o=i(89937),a=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,n.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,n.blank)(t))return;const i=(0,r.uniq)([t,(0,a.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:o.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==o.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,a.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const o=s(i(76760)),a=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),f=i(16287),h=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,a.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,a.notBlank)(t.remoteHost)&&(0,a.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:o.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,a.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,a.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(o.sep)}`;const n=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,h.isEquivalentHost)(e.authority,t.remoteHost))return o.join(t.mountpoint,...n);return await(0,f.isReadableDirectory)(t)?o.join(t,...n):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),n=i(42659),s=i(9103),o=i(37628);t.volsha=(0,s.memoize)((e=>(0,r.mapNotBlank)(e,o.shortStringSha)),{maxSize:128,ttlMs:n.minuteMs})},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),n=i(30577);t.channel=function(){return(0,n.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),n=i(22573),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function o(e){if(e instanceof r.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=o,t.semverSatisfies=function(e,t){if((0,n.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const s=o(e);return null!=s&&(0,r.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),n=i(9595),s=i(29882),o=i(43334),a=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([a.Settings.libraryDir.valueOrDefault,(0,n.originalsDir)(),...a.Settings.scanPaths.values]))if((!o.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),n=i(22573),s=i(59455),o=i(50213),a=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),f=i(69108),h=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,f.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),n=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||r||n);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:n}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,f.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,n.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,h.isGioSupported)())for(const e of(0,s.toA)(await(0,h.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,a.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),f=i(63870),h=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,o.toInt)(e,{defaultValue:0})*a.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,n.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void h().info("parseDfVolume(): skipping (size is 0)",{vol:e});const n=m(e.Used)??0,s=m(e.Available)??0;if(0!==n||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?n+s:r,used:n,available:s};h().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:n,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,f.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,n.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,f.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return h().warn("empty output",{localsOnly:e,paths:t}),[];h().debug("output",{localsOnly:e,paths:t,output:i});const o=p(i);return!0===e&&o.forEach((e=>e.remote=!1)),o},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(22573),a=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),f=i(59455),h=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),S=i(24541),b=i(60224),P=i(63870),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await F()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function T(e){return(0,l.map)(E(e),(e=>e+":\\"))}function x(e){return`Get-PSDrive -PSProvider FileSystem ${(0,h.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,o.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,o.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,h.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=T,t.getPsDriveCommand=x,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function O(e,t){return e=e?.trim(),(0,o.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function I(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=T(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,n.compact)([O(e.HealthStatus,"healthy"),O(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,o.notBlank)(e.DriveLetter)&&(0,o.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,h.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var s}async function F(){const e=(0,n.uniq)((0,f.toA)(await(0,S.mountpointsWin)()).map(T)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,n.compact)((0,a.flatten)(t).map(D)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),o=(0,n.compact)((0,a.flatten)(r).map(I)),l=(0,n.uniq)([...i,...o].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,n.uniq)([...i,...o].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:o,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...o.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=I,t.volumeInfoWin=F},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(42659),a=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),f=i(45255),h=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),S=i(16287),b=i(45969),P=i(43334),M=i(69108),_=i(98770),E=i(44224),T=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,T.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const x=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?x().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):x().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,n.isEmpty)(e)?[]:(x().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,T.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void x().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await D(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,T.mountpointsTtlMs)()}))),(0,a.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,T.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,h.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,h.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,h.stripPrefix)(e,"/"))).flatMap((e=>(0,h.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void x().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:f.ShortCommandTimeoutMs,clearEveryMs:10*o.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),n=i(5233),s=i(41400),o=i(56038),a=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function f(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,o.time)("volumes."+e,(()=>(0,n.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,a.isRetriableError)(e)&&!1!==(0,a.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&f(u)})),u},t.setupVolumeTTL=f},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),n=i(40958),s=i(22573),o=i(31586),a=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),f=i(6012),h=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),S=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const s=(0,c.sortIgnoreCase)((0,n.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),o=[];for(const t of s){const n=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),a={...n,...s},u=r?.find((e=>e.filesystem===a.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(a,u),null==a.size||null==a.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:n,df:e}),null!=e&&(0,l.assignMissingPrimitives)(a,e)}o.push(a)}return o};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,o.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,o.gte)(t[0],2)&&(0,o.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,h.splitLines)(e).map((e=>(0,f.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,o.toInt)(e.fsused),r=(0,o.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,f.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),n=i(19851),s=i(40958),o=i(22573),a=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),f=i(56519),h=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,n.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),n=await(0,f.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,h.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of n)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,o.blank)(t.MountPoint)||(0,a.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),n=i(40958),s=i(76790),o=i(42659),a=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),f=i(23560),h=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),S=i(8769),b=i(34102),P=i(17217),M=i(16287),_=i(43334),E=i(28874),T=i(8540),x=i(68884),D=i(44224),k=i(24541),C=i(69375),O=i(63870),I=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function F(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,O.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function A(){F()}t.localMountpointSetup=(0,r.lazy)((async()=>{E.Settings.libraryDir.watchLater(F),E.Settings.scanPaths.watchLater(F),(0,f.isSyncService)()&&E.Settings.scanAllDrives.valueOrDefault?(0,a.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,O.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux){const i=(0,D.maybeWatchProcMounts)();await(0,x.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,O.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,O.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),o.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,n.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?k.mountpointsWin:D.mountpointsPosix),h.ShortCommandTimeoutMs);if((0,n.isEmpty)(e))return I().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,O.commandTimeoutMs)(),f:async e=>!(!(0,T.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(I().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,a.later)((()=>{(0,b.ee)().on("clearCache",(()=>{x.gioVolumes.unset(),F()})),E.Settings.mountpointsTtlMs.watch(L)}),(0,c.isTest)()?1:o.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>A(),minCallDelayMs:1.5*o.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:x.GioCommand,args:x.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(x.gioVolumes.unset(),A()),minCallDelayMs:h.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,O.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>A(),minCallDelayMs:h.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),n=i(40958),s=i(42659),o=i(48884),a=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),f=i(73787),h=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),S=i(68884),b=i(59107),P=i(69375),M=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await x()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,S.isGioSupported)())try{await(0,c.thenMap)((0,S.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){M().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function E(e){return!v.Settings.excludedFilesystemTypes.has(e)}function T(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function x(e=_,t=E,i=T){if(y.isLinux)try{const r=await(0,h.readLines_)(e),s=(0,n.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,o.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),a=await(0,c.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,r])=>{const n=t(e),s=await i(r);return M().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:n&&s,meta:{fs:e,mp:r,fsOK:n,mpOK:s}})}});return M().tap({msg:"readProcMounts()",result:a.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void M().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=E,t.readProcMounts=x,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(_)?new f.FileWatcher(_,{recursive:!1,persistent:!1},(()=>{M().info("detected change in "+_),(0,d.setUnrefTimeout)((()=>b.mountpoints.refresh()),s.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),n=i(42659),s=i(13538),o=i(50213),a=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),f=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsWin")));async function h(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(h(),a.ShortCommandTimeoutMs)}catch(e){return f().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=h;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*n.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),n=i(22573),s=i(50213),o=i(9103),a=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const f=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,h=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===f?.test(e)?"LinuxDevMapperRE":!0===h?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),n=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function o(e){if((0,r.blank)(e))return;const i=n.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const o=t.nfsRe.exec(e);if(null!=o){const e=o[1],t=o[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=o(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=o},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),n=i(22573),s=i(42659),o=i(55835),a=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),f=i(81168),h=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await E()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,o.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,n.blank)(e))return(0,a.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,a.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,n.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,a.opt)(e.pathname).filter(n.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,p.wmic)(),t=await(0,h.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,u.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,o.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,f.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,n.notBlank)(e.LocalName))).map((e=>(0,o.map)(M(e.RemoteName),(({host:t,share:i})=>(0,o.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,f.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),n=i(12168),s=i(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(38639),a=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),f=i(81168),h=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),S=i(28874),b=i(59107),P=i(63870),M=i(68995),_=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),E=(0,n.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function T(e){return(0,o.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function x(e){if((0,s.blank)(e))return;const t=(0,f.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=x(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function k(e){if(S.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of S.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),r=await D(i).catch((e=>_().info("Failed to read "+i,{error:e})));if(null!=r)return _().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,M.volumeUuidSubpath)());if("/"===e.mountpoint)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(S.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(S.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,M.writeVolumeUuid)(e);if(!(0,s.blank)(t))return _().tap({msg:"readVolumeUUID(): wrote new "+(0,M.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return _().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,a.later)((()=>{(0,m.ee)().on("clearCache",(()=>E.clear())),b.mountpoints.watchLater((()=>E.clear()))})),t.addVolumeUUIDs=async function(e){await(0,h.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(T(e))return;if((0,o.isFalse)(e.ok))return;const t=await E().getOrSetAsync(e.mountpoint,(async()=>k(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>_().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=T,t.toVolumeUUID=x,t.readUuidFile_=D,t.readVolumeUUID=k},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const n=r(i(48161)),s=r(i(76760)),o=i(19851),a=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),f=i(41400),h=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),S=i(50213),b=i(7282),P=i(23560),M=i(28850),_=i(45255),E=i(81168),T=i(56519),x=i(4867),D=i(49776),k=i(9595),C=i(77740),O=i(44198),I=i(96706),F=i(8769),L=i(57159),A=(i(34102),i(21144)),R=i(73209),N=i(29882),j=i(95696),B=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),H=i(43334),G=i(28874),q=i(85087),$=i(50424),J=i(48165),K=i(98770),Z=i(27461),Y=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,o.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),ne=n.default.platform(),se=new Map,oe=new Map,ae=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,q.volsha)(t.uuid),(e=>oe.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,se),le((0,q.volsha)(e.uuid),e,ae),e}function ce(){return(0,a.compact)([j.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),j.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),oe))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),se.clear(),ae.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,T.mapAsync)({name:"readCachedVolumes",arr:(0,T.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,a.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function fe(e){if(null==e)return;const i=new h.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),n=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:ne}))),s=new Map;for(const e of n)for(const t of(0,a.compactBlanks)([(0,q.volsha)(e.uuid),(0,q.volsha)(e.mountpoint)]))s.set(t,e);const o=ce();for(const e of o)await(0,R.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:o,vol_mountpoints:n.map((e=>e.mountpoint))}),i.resolve()}async function he(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,a.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,G.Settings.volumeMetadataTtlMs.valueOrDefault),n=0!==G.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),s=!(0,a.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:n,priorIsMissingMountpoints:s}),n||s?void 0:e}async function me(e,i){const r=(0,m.map)(e,B.toNativePath_);if((0,u.blank)(r))return;const n=await(0,A.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,a.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(n,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:n,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:n}})}async function pe(e,t,i){const r=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,a.isEmpty)(r))return;const n=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=n)return n;const s=await(0,W.friendlyname)(e);return(0,T.asyncFind)(r,(async e=>(0,E.equalsIgnoreCase)(s,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,o.lazy)((()=>(0,P.isSyncService)()||(0,b.isTest)())),t.priorWriteVolumesToCacheLatch=(0,o.lazy)((()=>{})),t.writeVolumesToCache=fe,t.cachedVolumes=(0,o.lazy)((async()=>{const e=(0,a.compact)(await de()),t=(0,v.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,a.isNotEmpty)(i)?i:e.filter((e=>ne===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=he,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,x.thenOrTimeoutError)({p:he(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,x.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,a.isNotEmpty)(i))return i}catch(e){(0,F.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if((0,b.isTest)()){const e=(0,p.toInt)((0,O.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,f.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,x.thenOrTimeoutError)({p:H.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=G.Settings.validateMountpoints.valueOrDefault?(0,a.compact)(await(0,T.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,x.thenOrTimeoutError)({p:H.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,F.onError)("Failed to get remote volume info",{error:e})}));const i=(H.isWin?t:H.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await fe(r),Object.freeze(r)}}),t.rootPath=(0,o.lazy)((()=>H.isWin?(0,g.opt)((0,I.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,a.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,a.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,q.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,T.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return ae.get(e)??(await de())?.find((t=>(0,q.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,q.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),n=i(19851),s=i(22573),o=i(50213),a=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),f=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.WriteVolumeUUID")));function h(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=h,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,h());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const n=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(n))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+a.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),f().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){f().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else f().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),n=i(40958),s=i(22573),o=i(89937),a=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,a.toURI)(e),l=i.scheme===o.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===o.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,s.blank)(l))return;const u=i.path.split("/");return(0,n.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),n=i(40958),s=i(31586),o=i(27776),a=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),f=i(34238),h=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,n.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,a.hostname)()]));const i=(0,f.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,h.uriToTagPath)({uri:i,isFile:!1});if((0,n.isEmpty)(r))return;const s=(0,o.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(s)},t.mkAssetUrl=function(e){return(0,s.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const o=s(i(37067)),a=s(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),f=i(50213),h=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),v=(0,u.defer)((()=>(0,f.mkLogger)("net.get")));async function w(e,t){return S({...t,url:e})}async function S(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?o.request:"https"===t.scheme?a.request:v().throw("unsupported scheme: "+t.scheme),n=e?.maxRedirects??8,s=e?.timeoutMs??h.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",f=e?.agent??!1,S=r(t.toString(),{method:c,headers:u,timeout:s,agent:f},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const o={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};n>0&&y.HttpStatusIs.redirect(o.statusCode)&&!(0,l.blank)(e.headers.location)?(v().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:o.statusCode}),i.observe(w(e.headers.location,{timeoutMs:s,maxRedirects:n}))):(v().debug("complete",{...o,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(o))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||S.write(e.body),S.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=w,t.httpRequest_=S},78932:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httping=void 0;const r=i(19851),n=i(50213),s=i(34238),o=i(4988),a=(0,r.lazy)((()=>(0,n.mkLogger)("net.httping")));t.httping=function(e,t,i,r){return(0,o.get_)(s.URI.from({scheme:"http",authority:e+":"+t,path:i}),{timeoutMs:r}).then((e=>e.statusCode??-1),(e=>{a().warn("get() Failed",{error:e})}))}},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),n=i(19851),s=i(23838),o=i(81168),a=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,n.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,n.lazy)((async()=>{const e=(0,a.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(h(e))}));const d=(0,n.lazy)((()=>({trie:new s.MultiMap,small:[]}))),f=3;function h(e){const t=new s.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=n)return n}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),n=i(96249),s=i(23838),o=i(59455),a=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,o.toA)(u[t])],s=c(e.substring(1));return(0,n.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,a.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=r(i(48161)),s=i(19851),o=i(42659),a=i(31586),l=i(50213),u=i(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=r(i(48161)),s=i(19851),o=i(31586),a=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),f=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(r))return f().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return f().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,a.fmtBytes)(i),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),n=i(37692);let s=!1;function o(){return s}function a(e=!0){l(e),(0,n.writeStateFile)({paused:e})}function l(e){e!==s&&(s=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=o,t.pause=a,t.resume=function(){return a(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return o()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),n=i(42659),s=i(41400),o=i(31586),a=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),f=i(28874),h=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),h.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),f.Settings.cpuBusyPercent.watchLater(y),f.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,r.lazy)((()=>{const e=(0,o.clamp)(128,1024,f.Settings.maxMemoryMb.valueOrDefault)*a.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=f.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(f.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,h.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(f.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,h.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=w();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,h.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,o.gt0)(f.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),f.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=f.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),f.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const n=r(i(78474)),s=i(40958),o=i(76790),a=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),f=i(87290),h=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),v=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let w;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new n.default;let S=0;function b(){const e=(0,f.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-S>a.minuteMs;i&&(S=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(w?.nativePath)||(w?.close(),w=void 0),r&&null!=e&&(w??(w=new h.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=b()?.readJsonSync();for(const i of e?.events??[])M.get(i.e)!==i.ts&&(v().info("emitting event "+i.e),t.stateEvents.emit(i.e),M.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const M=new Map;function _(e){const i=b();if(null==i)v().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),n=function(e){const t=Date.now()-10*a.minuteMs;return(0,s.uniqByLast)((0,o.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:n};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=_,t.addStateEvent=function(e){const t=Date.now();M.set(e,t),_({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),n=i(87997),s=i(19851),o=i(42659),a=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),f=i(976),h=i(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new r.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,n.setInterval)(g,o.minuteMs).unref()));function g(){h.maxCpus.refresh(),h.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,f.rateStats)(e)),g()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{h.maxCpus.unset(),h.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),n=i(22573),s=i(50357),o=i(98553),a=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),f=i(59455),h=i(54993);function m(e){return null!=e&&(0,f.toA)(e).length>0}function p(e){return null==e||0===(0,f.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function S(e){return null==e?[]:v((0,f.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,a.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const n=[];if(et;s-=i)n.push(r(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),n=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const n of t){const t=i(n);r.includes(t)||(e.push(n),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,f.toA)(e).map((e=>(0,h.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const n=new Set(i.map(r));return e.filter((e=>!n.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),n=i(36783),s=i(41801),o=i(98553),a=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,n.copyArrayTo)(h(e,t),e)}function f(e,t){const i=new Map;for(const r of e)(0,a.getOrSet)(i,(0,o.stringify)(t(r)),(()=>r));return h(i.values(),t)}function h(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=f,t.sortUniq=function(e){return f(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(f(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=h,t.deepSortBy=function e(t,i){return h(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),n=i(31586),s=i(13538),o=i(41583);t.retryOnReject_=async function(e,t){const i=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const a=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(55938),a=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,o.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,o.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,n.blank)(e)?"":"```"+(0,a.toS)(e)+"```"},t.b=function(e){return"**"+(0,a.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,a.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),n=i(42279),s=i(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return a(i)?t(i):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),n=i(22573),s=i(30301),o=i(55835),a=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),f=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function h(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?f().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=h,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=h(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),n=i(),s=i(),o=i(),a=i(),l=i();return new Date(t,l-1,a,o,s,n,r)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,n.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/r.ms);e-=s*r.ms,s>0&&(r.ms>=t.dayMs?i:n).push(s+r.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),n=i(73872);function s(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function o(e,t,i,r){if(null==i||y(e)||y(t))return;let n=i.get(e);null!=n?n.set(t,r):(n=new WeakMap,n.set(t,r),i.set(e,n))}function a(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const n=l(e,t);return null!==n?n:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,h=s(e,t,u);if(null!==h)return h;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return o(e,t,u,i),i;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(f(e),f(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],n=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(r.sort(),n.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return o(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let n=-1;for(;++n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const n=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return n.prior=()=>t,n.hasPrior=()=>r,n}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),n=i(35556),s=i(31586),o=i(68708);function a(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=n.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return n.isBrowser||t<=r.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),n=i(21605),s=i(12168);function o(e){return{width:e.height,height:e.width}}function a(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=o,t.maybeDimSwap=function(e,t){return(0,n.swappableRotation)(t)?o(e):e},t.maybeFlipInPlace=function(e,t){(0,n.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(a(e))},t.pixels=a},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),n=i(68708),s=i(34666),o=i(32639);function a(e,t){return(0,r.deepEql)(e,t,{comparator:f})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const i of(0,n.keys)(e))if(!a(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function f(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),n=i(22573),s=i(96249),o=i(31586),a=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const f=/shortStack|errorToVerbose/;function h(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,s.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return h(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==f.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=h,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),n=i(42659),s=i(55835),o=i(31586),a=i(12168),l=[{ms:n.yearMs,s:"year",p:"years"},{ms:n.yearMs/12,s:"month",p:"months"},{ms:n.weekMs,s:"week",p:"weeks"},{ms:n.dayMs,s:"day",p:"days"},{ms:n.hourMs,s:"hour",p:"hours"},{ms:n.minuteMs,s:"minute",p:"minutes"},{ms:n.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,n){if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,a.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(n,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function n(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),n=i(38639),s=i(68708),o=i(62220),a=i(50989);t.HealthCheckSections=(0,a.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,a.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&o.RunStates.has(e.state)&&(0,n.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const n=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,n){if((0,isFunction_1.isFunction)(r))return;let s,o,a,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),n=i(50357),s=i(31586),o=i(65812);t.lazy=function(e,t){let i,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const s=await e,a=await i;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),n=i(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,i){return null==e||null==t?void 0:i(e,t)}function a(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=a,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return a(o(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),n=i(76790),s=i(50357),o=i(98553),a=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,a.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,s.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),n=null==i?[]:e(t,i);(0,r.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,n]of this.store.entries()){const s=(0,r.findIndexes)(n,(t=>!e(i,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=i;return e}}function f(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=f,t.groupByValues=function(e,t){const i=f(e,t);return(0,n.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),n=i(22573),s=i(42279),o=i(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const f=e=>(t,i)=>a(t)&&a(i)&&e(t,i);function h(e,i,n){return!(null==n||!a(n))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,n)&&(0,t.gte)(i,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function M(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function _(e,t,i){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return a(i)?it?t:i:(e+t)/2}t.lt=f(((e,t)=>ee<=t)),t.gt=f(((e,t)=>e>t)),t.gte=f(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return h(t-r,t+r,e)},t.within=h,t.max_=function(...e){let t;for(const i of e)a(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,i){return b(e,(e=>b(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return a(e)?t(e):i},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=M,t.toPrecisionMaybe=function(e,t){return d(e,(e=>M(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=_,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return _(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||h(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!a(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),n=i(76790),s=i(22573),o=i(32639),a=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function f(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function h(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!h(e)}function p(e){return f(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??f(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,n.sort)(f(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const n={};for(const e of(0,r.uniq)((0,r.flatMap)(i,f)))n[e]=S(...i.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of f(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=f,t.keysWithDefinedValues=function(e){return null==e?[]:f(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=h,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,n]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==n&&!0!==i?.assignNullish||(e[r]=n));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,a.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,s.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=a.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function n(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:S(i,t)}for(const r of i){const[i,o]=(0,c.splitFirst)(r,"."),a=b(t,i);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const r of f(t))((0,l.toInt)(r)??-1)>=0&&n(r,e(t[r],...i));return r},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const n=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(n)?void 0:{key:n[0].key,value:(0,r.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(i,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=f(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,o.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of f(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>r(this.a,e,t,i)))))))}}function n(e){return e instanceof r||e===t.None}function s(e){return n(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=n,t.opt=s},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),n=i(30976),s=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,n.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,s.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),n=i(54993),s={};function o(e,t){if(t<1)return"";if(!(0,r.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),n=i(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return o(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,s=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==s&&"symbol"!==s)){const r=(0,n.toS)(e),s=(0,n.toS)(i),o=r.localeCompare(s);return r[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==s?a.indexOf(r)-a.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const n of(0,r.toA)(await e))if(null!=n){const e=await n;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),n=i(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,i){return null==i||0===i.length?s(e,t):a(e,t,1,i)[0]}function a(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(r??[]);if(t===e&&0===n&&0===o.size&&1===i)return[e];const a=n-o.size;if(i>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:i,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of a(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let n=null;for(;null!=(n=t.exec(e));)n.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,n.index)+i(n)+r.slice(n.index+n[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function n(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=n,t.swappableRotation=function(e){const t=n(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),n=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?i[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),r=o(t);return null==i||null==r?void 0:i>r?1:i{const i=o(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),n=i(17586),s=i(22573),o=i(96249),a=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let f;function h(){if(void 0===f)try{f=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{f=null}return f??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=h();return null!=r?(0,a.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=h();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),n=(0,c.toS)(t);return r.length===n.length&&(r===n||r.toLowerCase()===n.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=h();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const r=i?.maxLineLen??80,n=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),n).trim()).length<=r)return[t];const s=S(t," ",r);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),i)];{const r=t.indexOf(" ",n.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),n=i(68708),s=i(42279),o=i(83104),a=i(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,i(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,i(t))}catch(e){n&&(n=!1,r(e))}finally{clearTimeout(s)}}))}async function c(e,t,i=!0){const n=await u(e,t,i);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?o.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{r(await i())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),r(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,r.fmtHMS)(n)+")");return c(e,n,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,s.tot)(i);const n=await u(e,t,r);return n===o.Timeout?(0,s.tot)(i):n}},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),n=i(22573),s=i(54993);function o(e){return"URLSearchParams"===e?.constructor?.name}function a(e){return null==e?void 0:o(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(a)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=o,t.toURLSearchParams=a,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,n.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,n.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),n=i(30301),s=i(31586),o=i(46891),a=i(50989),l=i(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,s.isNumber)(r)&&(i+=r/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],f=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function h(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),n=Math.pow(10,3*r),o=d[r];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,i=3){return h(e*t.MB,i)},t.fmtBytes=h,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),n=Math.pow(2,10*r),o=f[r];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,n=/\bFirefox\b/,s=/\biPad\b/,o=/\biPhone\b/;function a(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return a(e,i)}function u(e){return a(e,n)}t.isChrome=l,t.isSafari=function(e){return a(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return a(e,s)},t.isIphone=function(e){return a(e,o)}},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),n=i(22573),s=i(98553),o=i(31586),a=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,o.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,o.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,o.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,o.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,s.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,n.notBlank)(e.name)},t.TagRoots=(0,a.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),n=i(30301),s=i(31586),o=i(97238),a=i(29652);function l(e,i){const r=(0,a.toURLSearchParams)(e);if(i||!(0,s.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,a.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,n.lazy)(o.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),n=i(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),n=i(23541),s=i(59455),o=i(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,r.compact)((0,s.toA)(e).map(a))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,r.stringify)(e)}}t.toStr=s},61209:function(e,t,i){"use strict";var r,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainService=void 0;const d=c(i(1708)),f=i(19851),h=i(50213),m=i(54826),p=i(22911),g=i(27395),y=i(78406),v=i(25764),w=i(38836),S=i(99331),b=i(45608),P=i(73614),M=i(86335),_=i(55534),E=i(38835),T=i(70025),x=i(8769),D=i(83278),k=i(19652),C=i(85021),O=i(28874),I=i(2858),F=i(34238),L=i(51140),A=c(i(98604)),R=i(78932),N=i(69385),j=i(22573),B=i(38639),z=i(42659),V=i(26905),W=i(98553),U=i(55835),H=i(31586),G=i(68708),q=i(54993),$=i(37158);class J{constructor(){r.add(this),this.start=Date.now(),n.set(this,(0,f.lazy)((()=>(0,h.mkLogger)("MainService")))),this.httpPort=new p.Deferred("MainService.httpPort"),this.libraryDir=new p.Deferred("MainService.libraryDir"),s.set(this,void 0),o.set(this,void 0),this.setup=(0,f.lazy)((async()=>{await this.service.ready.catch((e=>(0,m.consoleError)("MainService.setup() failed: "+(0,V.errorToS)(e)))),l(this,s,await M.ChildService.mk_("web",{onStdout:e=>this.onWebout("stdout",e),onStderr:e=>this.onWebout("stderr",e),onData:e=>this.onWebData(e),onRestartPaused:()=>(0,b.exit)({reason:"Too many web service fatal errors",status:13})}),"f"),await(0,j.mapNotBlank)(O.Settings.pidFile.value,(async e=>{const t=D.BaseFile.for(e);u(this,n,"f").call(this).info("Writing to pidfile "+t,{pid:d.default.pid}),await t.writeText_((0,q.toS)(d.default.pid)),new w.EndableWrapper("remove pidfile",(()=>t.unlink()),v.EndableRanks.postdb)})),await this.service.ready;try{await(0,k.externalDirectoryCheck)()}catch(e){u(this,n,"f").call(this).warn("Failed to check external directory permissions",{error:e})}if(this.service.setInputHandler("--restart-sync",(()=>this.restartSync())),this.service.setInputHandler(C.HealthCheckCommand,(()=>u(this,r,"m",a).call(this))),null==u(this,s,"f"))return(0,x.onError)("Failed to start webservice"+E.FatalErrorFlag);this.httpPort.promise.then((e=>{const t=(0,A.default)(e),i=(1===t.length?" ":"\n - ")+t.map((e=>`${e}`)).join("\n - ");(0,m.consoleLog)(`PhotoStructure is ready:${i}`),O.Settings.exposeNetworkWithoutAuth.valueOrDefault||(0,m.consoleLog)("See https://photostructure.com/faq/remote-access/ to enable non-localhost access.")})),this.libraryDir.promise.then((e=>{(0,m.consoleLog)(`Your library is at <${F.URI.file(e)}>`)})),new w.EndableWrapper("shutdown notice",(()=>(0,m.consoleLog)("\nShutting down PhotoStructure...")),v.EndableRanks.first),(0,H.gt0)(O.Settings.healthCheckIntervalMs.valueOrDefault)&&new y.EndableInterval({name:"webSyncHealthChecks",intervalMs:O.Settings.healthCheckIntervalMs.valueOrDefault,callback:()=>u(this,r,"m",a).call(this)})})),this.service=new $.Service("main"),this.setup(),(0,P.setUnrefTimeout)((()=>{this.httpPort.isPending&&!(0,S.ending)()&&(0,m.consoleLog)("Please wait, setting up...")}),4*z.secondMs)}async webHealthCheck(){const e=this.httpPort.value;if(null!=e)try{const t=await(0,R.httping)("localhost",e,"/ping",3*z.secondMs);return!!L.HttpStatusIs.success(t)||(u(this,n,"f").call(this).warn("webHealthCheck(): web service returned "+t),!1)}catch(e){return u(this,n,"f").call(this).warn("webHealthCheck(): httping error: "+e),!1}else u(this,n,"f").call(this).info("webHealthCheck(): no-op, no http port set (web is starting up still)")}onWebout(e,t){return u(this,n,"f").call(this).info("onWebout",{pipe:e,error:t}),t===_.ServiceExitCommand?(0,b.exit)({reason:"Web service exit command",status:0}):(t??(t=""),/EADDRINUSE/i.test(t)||t.includes(E.WebFatalErrorFlag)||(0,T.isFatalError)(t)?(0,b.exit)({status:1,reason:"Web service error",error:t}):this.onWebData((0,W.parseJSON)(t)))}async onWebData(e){(0,j.blank)(e)||(u(this,n,"f").call(this).info("onWebData",{input:e}),(0,U.map)(e[O.Settings.httpPort.key],(e=>{u(this,n,"f").call(this).info("Got HTTP port number from web service:"+e),O.Settings.httpPort.envValue=e,this.httpPort.maybeResolve(e)})),(0,B.mapBoolean)(e.pause,(e=>e?(0,N.pause)():(0,N.resume)())),await(0,B.mapTrue)(e.shutdown,(()=>(0,b.exit)({reason:"shutdown requested",status:0}))),await(0,B.mapTrue)(e.shutdownSync,(()=>this.shutdownSync())),(0,B.isTrue)(e.forceRestartSync)?await this.forceRestartSync():(0,B.isTrue)(e.restartSync)&&await this.restartSync())}async shutdownSync(){const e=u(this,o,"f");return l(this,o,void 0,"f"),u(this,n,"f").call(this).info("shutdownSync()",{syncWasDefined:null!=e}),(0,g.end)(e)}async forceRestartSync(){return this.restartSync()}async restartSync(){const e=(0,h.mkLogger)("MainService.restartSync()");if((0,S.ending)())return void e.info("ending, no-op");const t=u(this,o,"f");if(e.info("priorSync",(0,U.map)(t,(e=>(0,G.pick)(e,"pid","name")))),await(0,g.end)(t),l(this,o,void 0,"f"),await(0,I.readSystemSettings)(),!I.libraryHasSettings.refresh())return void e.info("restartSync(): no library settings",{libraryDir:O.Settings.libraryDir.value});const i=l(this,o,await M.ChildService.mk_("sync"),"f");e.info("Started sync",(0,U.map)(i,(e=>(0,G.pick)(e,"pid","name"))))}}t.MainService=J,n=new WeakMap,s=new WeakMap,o=new WeakMap,r=new WeakSet,a=async function(){!1===await this.webHealthCheck()?await u(this,s,"f").restart():u(this,s,"f").runHealthCheck(),u(this,o,"f")?.runHealthCheck()},J.instance=(0,f.lazy)((()=>new J))},18449:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(7282),n=i(96706),s=i(29325),o=i(28874);t.sentryEnabled=function(){return(0,n.isEnvTrue)("ENABLE_SENTRY")||(0,r.isProd)()&&(0,s.isPacked)()&&!0===o.Settings.reportErrors.value}},95629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const a=s(i(16436)),l=o(i(48161)),u=o(i(1708)),c=i(19851),d=i(19043),f=i(50213),h=i(31578),m=i(7282),p=i(96175),g=i(23560),y=i(84968),v=i(81168),w=i(37805),S=i(25764),b=i(38836),P=i(99331),M=i(85100),_=i(98314),E=i(68301),T=i(70025),x=i(8769),D=i(34102),k=i(34592),C=i(42042),O=i(34474),I=i(20839),F=i(57902),L=i(45969),A=i(43334),R=i(40958),N=i(22573),j=i(42659),B=i(41400),z=i(98553),V=i(55835),W=i(12168),U=i(59455),H=i(54993),G=i(18449),q=(0,c.lazy)((()=>(0,f.mkLogger)("Sentry")));function $(e){(0,G.sentryEnabled)()&&null!=e&&!0!==(0,T.isDoNotSendError)(e)&&a.captureException(e)}t.installSentry=async function(e){try{return!!(0,G.sentryEnabled)()&&(a.init({dsn:A.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:w.release,environment:(0,m.nodeEnv)(),maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,x.onError)("sentry.onFatalError",e)}),q().info("Sentry initialized",{isElectron:A.isElectron}),!0)}catch(e){return q().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,G.sentryEnabled)())return q().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(E.ErrorStore.instance()?.eventQuotaExceeded(e)))return q().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,T.isDoNotSendError)(i))return q().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await X(e);return await(E.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,D.ee)().on("fatal",$),(0,D.ee)().on("nonFatal",$),new b.EndableWrapper("EventFilter",(()=>this.end()),S.EndableRanks.first)}end(){return(0,V.map)(a.getCurrentHub().getClient(),(e=>e.close(5*j.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Z(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Z(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,H.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,L.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,h.memoryUsageMb)(),i.memoryUsageRssMb=(0,h.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,k.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/j.secondMs,...e}}async function Q(){await(0,B.delay)(3*I.DefaultLogFlushMs);const e=await(0,O.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/j.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Z,t.sentryExceptionToS=Y,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[F.LogLevels.fatal,"fatal"],[F.LogLevels.error,"error"],[F.LogLevels.warn,"warning"],[F.LogLevels.info,"info"],[F.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},37158:function(e,t,i){"use strict";var r,n,s,o,a,l,u,c,d,f=this&&this.__classPrivateFieldSet||function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,i):n?n.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const p=m(i(29907)),g=m(i(1708)),y=i(57206),v=i(19851),w=i(50213),S=i(59880),b=i(23560),P=i(19913),M=i(71567),_=i(37805),E=i(38836),T=i(99331),x=i(45608),D=i(56038),k=i(55534),C=i(42499),O=i(49776),I=i(96706),F=i(98314),L=i(38835),A=i(70025),R=i(8769),N=i(57159),j=i(34102),B=i(33456),z=i(87408),V=i(85021),W=i(17181),U=i(86941),H=i(28874),G=i(41692),q=i(2858),$=i(69385),J=i(22573),K=i(42659),Z=i(41400),Y=i(56409),X=i(55835),Q=i(41583),ee=i(54993),te=i(95629);t.setupEventHandlers=(0,v.lazy)((()=>{(0,j.ee)().on("resume",(()=>(0,$.resume)())),(0,j.ee)().on("pause",(()=>(0,$.pause)()))}));class ie extends E.EndableWrapper{constructor(e){super(e),r.add(this),n.set(this,void 0),s.set(this,new Y.Latch),o.set(this,new Map),this.setup_=(0,v.lazy)((()=>(0,D.time)("Service.setup",(()=>h(this,r,"m",a).call(this))))),u.set(this,(0,v.lazy)((()=>{const e=g.default.stdin.pipe(new B.LineReader);return e.on("data",(e=>h(this,r,"m",d).call(this,(0,ee.toS)(e)))),e}))),(0,b.isBillingService)()||(0,G.setSettingsDefaults)(),f(this,n,(0,w.mkLogger)("Service("+this.name+")"),"f"),h(this,r,"m",c).call(this),this.setup_()}get name(){return super.name}get ready(){return h(this,s,"f").promise}get isReady(){return h(this,s,"f").isResolved()}setInputHandler(e,t){h(this,o,"f").set(e.trim().toLowerCase(),t)}}t.Service=ie,n=new WeakMap,s=new WeakMap,o=new WeakMap,u=new WeakMap,r=new WeakSet,a=async function(){try{(0,J.mapNotBlank)((0,I.getEnv)("PS_FATAL_"+this.name),(e=>{throw new N.WrappedError(e,{fatal:!0})})),(0,J.mapNotBlank)((0,I.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new N.WrappedError(e)}),5*K.secondMs)})),(0,P.setServiceName)(this.name),(0,S.setProcessTitle)(),(0,b.isMainService)()&&await(0,U.mergeUserDataDirs_)(),await(0,q.readSettings)(),await h(this,r,"m",l).call(this),(0,W.setupLogger)(),(0,y.addDefaultJsonRevivers)(),(0,O.cacheDir)(),(0,t.setupEventHandlers)(),h(this,u,"f").call(this),await(0,C.setupLuxon)(),H.Settings.startPaused.valueOrDefault&&(0,$.pause)(),(0,T.ending)()?h(this,s,"f").reject():h(this,s,"f").resolve()}catch(e){console.error((0,F.errorToS)(e)),h(this,s,"f").reject((0,Q.toErr)(e)),(0,x.exit)({reason:(0,A.addErrorFlags)(this.name+" setup failed: "+(0,F.errorToS)(e),L.FatalErrorFlag),status:14})}},l=async function(){(0,b.isPermaService)()||(0,j.ee)().on("fatal",(e=>(0,x.exit)({error:e,status:12}))),g.default.on("unhandledRejection",(e=>(0,X.map)(e,(e=>(0,R.onError)("unhandledRejection",e))))),g.default.on("uncaughtException",(e=>(0,X.map)(e,(e=>(0,R.onError)("uncaughtException",e))))),g.default.on("SIGINT",(()=>(0,x.exit)({reason:"SIGINT",status:0}))),g.default.on("SIGHUP",(()=>(0,x.exit)({reason:"SIGHUP",status:0}))),g.default.on("SIGTERM",(()=>(0,x.exit)({reason:"SIGTERM",status:0}))),p.default.isWorker&&g.default.on("disconnect",(()=>(0,x.exit)({reason:"disconnect",status:0}))),await(0,te.installSentry)(this)},c=function(){this.setInputHandler("--version",(()=>(0,M.stdoutWrite)({version:_.version}))),this.setInputHandler(k.ServiceExitCommand,(()=>(0,Z.later)((()=>(0,x.exit)({reason:k.ServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,M.stdoutWrite)(D.PromiseTimer.instance().report()))),this.setInputHandler(V.HealthCheckCommand,(async()=>(0,M.stdoutWrite)(await(0,z.getStatusSummary)({refresh:!0}))))},d=async function(e){if(h(this,n,"f").debug("onLine()",{line:e,ending:this.ended||(0,T.ending)()}),await this.setup_(),e.startsWith("--")){const t=e.split(/\s+/,1)[0],i=h(this,o,"f").get(t);null==i?(h(this,n,"f").error("onLine(): unknown command",{line:e,knownCommands:[...h(this,o,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else h(this,n,"f").error("onLine(): failed to process",{line:e})}},38530:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DaemonArgs=void 0;const n=i(58587),s=i(31421),o=r(i(1708)),a=i(9727),l=i(83278),u=i(95402),c=i(28874),d=i(2858),f=i(22573),h=i(38639),m=i(31586);t.DaemonArgs={beforeParse:e=>e.option("-p, --pidfile PIDFILE","Write a pidfile of the main process.").option("--stop","Shutdown daemonized PhotoStructure. Requires --pidfile").option("-d, --daemon","Run PhotoStructure as a daemon. Enabled by default when --pidfile is provided."),afterParse:async e=>{if((0,f.mapNotBlank)(e.pidfile,(e=>c.Settings.pidFile.envValue=e)),(0,h.isTrue)(e.stop)){if(!c.Settings.pidFile.hasValue()&&(await(0,d.readSystemSettings)(),!c.Settings.pidFile.hasValue()))return console.error("--stop requires --pidfile to be set."),o.default.exit(1);const e=l.BaseFile.for(c.Settings.pidFile.value);if(await e.notExists())return console.error("Pidfile "+e+" does not exist."),o.default.exit(1);const t=(0,m.toInt)(await e.readTextFile());return(0,m.gt0)(t)?(0,n.pidExists)(t)?(await(0,u.killPid)(t),o.default.exit(0)):(console.error("Pid "+t+" does not exist."),o.default.exit(1)):(console.error("Pidfile "+e+" is invalid."),o.default.exit(1))}if(!(0,h.isTrue)(o.default.env.__is_daemon)&&((0,h.isTrue)(e.daemon)||c.Settings.pidFile.hasValue())){const e=o.default.argv.findIndex((e=>!e.includes("npx")&&!e.includes("node"))),t=o.default.argv.slice(-1===e?0:e),i=process.execPath,r={...(0,a.childEnv)(),__is_daemon:"1"},n=(0,s.spawn)(i,t,{env:r,detached:!0,shell:!0});return n.unref(),console.log("Daemonized PhotoStructure.",{pid:n.pid,args:t}),o.default.exit(0)}}}},98392:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExposeArg=void 0;const r=i(28874),n=i(38639);t.ExposeArg={beforeParse:e=>e.option("--expose","The web service is only accessible to the computer running PhotoStructure by default. Providing this option will expose your library to all computers on your network. See https://photostructure.com/faq/remote-access/ ."),afterParse:e=>{(0,n.isTrue)(e.expose)&&(r.Settings.exposeNetworkWithoutAuth.envValue=!0)}}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),n=i(83210),s=i(28874),o=i(38639);function a(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(a()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return a()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),a()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,o.isTrue)(e.error),i=(0,o.isTrue)(e.warn),r=(0,o.isTrue)(e.info)||(0,o.isTrue)(e.verbose)||(0,o.isTrue)(e.v),l=(0,o.isTrue)(e.debug),u=(0,o.isTrue)(e.trace);u?s.Settings.logLevel.envValue="trace":l?s.Settings.logLevel.envValue="debug":r?s.Settings.logLevel.envValue="info":i?s.Settings.logLevel.envValue="warn":t&&(s.Settings.logLevel.envValue="error"),(0,n.isDaemon)(e)?(s.Settings.tailLogs.envValue=!1,s.Settings.logStdout.envValue=!1):((0,o.isTrue)(e.tail)&&(s.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(s.Settings.logStdout.tmpValue=!0,a()&&(s.Settings.tailLogs.tmpValue=!0)),(s.Settings.tailLogs.valueOrDefault||s.Settings.logStdout.valueOrDefault)&&s.Settings.logLevel.isUnset()&&(s.Settings.logLevel.envValue="info"))}}},12195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoFilterArg=void 0;const r=i(4175),n=i(38639);t.NoFilterArg={beforeParse:e=>e.option("--no-filter","Disables import filters. All paths will try to be imported, even if they are too small or are missing tags. See https://photostructure.com/faq/why-is-my-file-missing/ ."),afterParse:async e=>{(0,n.isFalse)(e.filter)&&(0,r.disableAllFilters)()}}},33321:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PauseSyncArg=void 0;const r=i(28874),n=i(38639);t.PauseSyncArg={beforeParse:e=>e.option("--pauseSync","Pause sync processing until manually resumed via the system tray or nav menu."),afterParse:e=>{(0,n.isTrue)(e.pauseSync)&&(r.Settings.startPaused.envValue=!0)}}},51088:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MainArgs=void 0;try{i(93944).install()}catch{}const r=i(69554),n=i(43380),s=i(28874),o=i(38639),a=i(5670),l=i(61209),u=i(38530),c=i(98392),d=i(31503),f=i(12195),h=i(33321);t.MainArgs={beforeParse:e=>e.option("--quiet","Don't emit lifecycle messages to stdout from the main service."),afterParse:e=>{(0,o.isTrue)(e.quiet)&&(s.Settings.quiet.tmpValue=!0)}},async function(){try{await new r.CLI(a.ServiceNames.main).add(t.MainArgs,c.ExposeArg,h.PauseSyncArg,u.DaemonArgs,f.NoFilterArg,n.WriteSettingsArg,d.LogArgs).parse(),new l.MainService}catch(e){console.error("Failed to start:")}}()},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},16436:e=>{"use strict";e.exports=require("@sentry/node")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},51168:e=>{"use strict";e.exports=require("luxon")},4927:e=>{"use strict";e.exports=require("papaparse")},22915:e=>{"use strict";e.exports=require("platform-folders")},57272:e=>{"use strict";e.exports=require("plist")},85949:e=>{"use strict";e.exports=require("process")},57160:e=>{"use strict";e.exports=require("punycode.js")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},93944:e=>{"use strict";e.exports=require("source-map-support")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},29907:e=>{"use strict";e.exports=require("cluster")},76982:e=>{"use strict";e.exports=require("crypto")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.exports}var __webpack_exports__=__webpack_require__(51088);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/photostructure.js b/bin/photostructure.js index 3558f03..9ef76a2 100755 --- a/bin/photostructure.js +++ b/bin/photostructure.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={37975:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const i=r(1708),n=r(22573),s=r(38639);function o(){return(0,s.toNotBoolean)(i.env.PS_LOG_COLOR)??(!(0,n.blank)(i.env.NO_COLOR)||["dumb","unknown"].includes(i.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(r){return l()?`[${e}m${r}[${t}m`:r}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const i=r(19851),n=r(7282),s=r(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,i.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,i.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const i=r(40958),n=r(36783),s=r(76790),o=r(22573),a=r(50357),l=r(98553),u=r(55835),c=r(31586),d=r(68708),h=r(34666),f=r(59455),m=r(84885);var g=r(40958);function p(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,r=i.primitiveValueOfOrElse){const n=new Set(t.map(r));return e.filter((e=>n.has(r(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],r=e.lastIndexOf(t);return[{t,count:r+1},...v(e.slice(r+1))]}function w(...e){const t=[],r=Math.max(...e.map((e=>e?.length??0)));for(let i=0;ie?.[i])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function E(e,t){return(0,i.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,r){return C(e,t,r).index}function C(e,t,r){if((0,i.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let i=0;ie.slice(r,r+t)))}async function x(e,t){return(0,i.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return g.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return g.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return g.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=p,t.mapAllDefined=function(e,t){return p(e)?t(e):void 0},t.mapAll=function(e,t){return p(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const r of(0,f.toA)(e))if(null!=r&&!0===await t(r))return r},t.findLastAsync=async function(e,t){for(let r=(e=(0,f.toA)(e)).length-1;r>=0;r--){const i=e[r];if(null!=i&&!0===await t(i))return i}},t.first=function(e,t){if(null!=e)for(const r of(0,f.toA)(e))if(null!=r){const e=t(r);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null!=i){const e=await t(i,r);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,i.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,r){for(let i=r;i<=e.length-1;i++)if(t(e[i]))return i},t.findLast=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},t.findLastIndex=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},t.concat=function(...e){const t=[];for(const r of e)if(Array.isArray(r))for(const e of r)null!=e&&t.push(e);else null!=r&&t.push(r);return t},t.moveToEnd=function(e,t){return(0,i.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const r=e[t];if(null==r)return e;e.push(r);for(let r=t;r(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const r=e.findIndex(t);return r>=0?e.splice(r,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,i.uniqBy)(e,t),e)},t.partition=function(e,t){const r=[],i=[];let n=0;for(const s of e)(t(s,n++)?r:i).push(s);return[r,i]},t.isUniq=function(e){return e.every(((t,r)=>e.indexOf(t)===r))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,i.compact)((0,i.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),r=[];return(0,c.times)(t,(t=>e.map((e=>r.push(e?.[t]))))),r},t.unFlatZip=function(e,t){const r=e.length/t;if(r!==Math.round(r))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const i=(0,c.times)(t,(()=>new Array(r)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=E,t.least=function(e){return E(e,(e=>e))},t.greatestBy=function(e,t){return(0,i.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const r=C(e??[],t,h.lt);return null==e||null==r||r.index<0||null==r.value?void 0:{result:e[r.index],index:r.index,value:r.value}},t.reverse=function(e){const t=[];for(let r=e.length-1;r>=0;r--)t.push(e[r]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(r(s)));return n},t.collectBatchedAsync=async function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(await r(s)));return n},t.contextFilter=function(e,t){let r;return e.filter(((e,i)=>(0,d.tap)(t(e,i,r),(t=>{t&&(r=e)}))))},t.clusterSome=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.some((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterEvery=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.every((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterAsync=async function(e,t){const r=[];e:for(const i of e){for(const e of r)if(null!=i&&await x(e,(e=>t(i,e)))){e.push(i);continue e}null!=i&&r.push([i])}return r},t.someAsync=async function(e,t){if(null!=e)for(let r=0;r=0&&!0===(0,u.map)(e[i],(e=>r(e,i))))return i}{const i=t+n;if(ie+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,r){return e.lengthr))),e}},36557:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=r(77988),l=o(r(1708)),u=r(19851),c=r(42659),d=r(55835),h=r(31586),f=r(85556),m=r(54993),g=r(50213),p=r(79089),y=r(45255),v=r(25764),w=r(38836),S=r(99331),b=r(95937),P=r(98314),_=r(38835),E=r(70025),M=r(8769),C=r(43334),T=r(95402),x=r(28874),D=r(63870);class k extends w.EndableWrapper{constructor(e,t,r=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,i,"m",n).call(this)),r,"worker"===e?(0,D.commandTimeoutMs)():y.ShortCommandTimeoutMs),i.add(this),this.t=t;const o=t;o.on("childStart",(async r=>{null!=r.pid?(this.logger.info("Started child process",{pid:r.pid}),(0,p.renice)(r.pid).catch((e=>this.onError("renice failed",e))),(0,T.addPid)({pid:r.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,r,i)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&T.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,E.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=k,i=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(C.isWin?3:1)*c.minuteMs,maxTasksPerProcess:x.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:x.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:x.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,g.mkLogger)(t))),spawnTimeoutMillis:(0,D.commandTimeoutMs)(),taskTimeoutMillis:x.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=r(92460),d=r(31586);class h{constructor(e){if(i.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,r;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,i,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,r;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,i,"m",a).call(this,0,(e=>{var t,r;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(r=u(this,s,"f"),--r),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,i,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const r=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=r}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const i=r(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:r}of n)if(o(e,t))return e.subarray(t.length).toString(r);return e.toString()}function o(e,t){return t.every(((t,r)=>e[r]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,i.toS)(e)},t.bufferStartsWith=o},9092:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,r]of e)this.set(t,r)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const r=this.normalizer(e);return null!=e&&null!=r&&this.store.set(r,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=r(40958),a=r(23838),l=s(r(68708)),u=r(59455),c=r(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const r of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(r,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const r=this.lookup(e);if(null!=r)return r;let i,n=-1;for(const[r,s]of this.m.entries()){const o=(0,c.diceCoeff)(r,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(i=e,n=o)}}return i}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),r=this.m.get(t);if(null!=r){for(const e of r)delete this.obj[e];this.m.delete(t)}return r}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const i=r(76790),n=r(31586),s=r(68708),o=r(54993),a=r(82647),l=r(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const r=this.get(e)+t;return 0===r?this.m.delete(e):this.m.set(e,r),r}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,r]of this.m.entries())e[(0,o.toS)(t)]=r;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,i.sortBy)([...this.entries()],(([t,r])=>[-r,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,r]of(0,i.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,r);return e}addAll(e){for(const[t,r]of e.entries())this.incr(t,r);return this}get toS(){return(0,i.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let r=0;for(const[i,n]of this.m.entries()){const s=e(i);t.fill(s,r,r+n),r+=n}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const i=r(19851),n=r(72993),s=r(45969),o=r(43334);t.EditionType=(0,i.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,i.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const i=r(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),r=t-this.ts;this.ts=t,(0,i.map)(this.listener,(t=>t(e,r))),r>2&&this.l.log(r>500?"warn":r>100?"info":"debug",e,{elapsedMs:r})}},t.elapsed=function(e){const t=Date.now(),r=e();return{elapsedMs:Date.now()-t,result:r}},t.thenElapsed=async function(e){const t=Date.now(),r=await e;return{elapsedMs:Date.now()-t,result:r}}},23467:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const i=r(50357),n=r(55835),s=r(68708);var o=r(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,i.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,i.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,i.eql,(()=>!1))},t.eqlPicked=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))},t.eqlOmit=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.omit)(e,...r),(0,s.omit)(t,...r))},t.eqlAsyncPicked=async function(e,t,...r){return(0,n.map2Or)(await e,await t,((e,t)=>(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))),(()=>!1))}},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(31586),a=r(54993),l=r(77377),u=r(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const r of this.expireListeners)r(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[i.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const r of this.expireListeners)r(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const r of this.expireListeners)r(e,t)}const r=this.priorCache[e];if(void 0!==r&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,r)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const r=this.currentCache[t]??this.priorCache[t];null!=r&&e(t,r)}}deleteIf(e){for(const t of this.keys()){const r=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=r&&e(t,r)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const r=t();return this.set(e,r),r}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=r(31586),d=r(85556),h=r(54993),f=r(54557),m=r(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,i.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,i,l(this,i,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,i,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,r,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(r=l(this,n,"f"),++r),"f"),c.promise):(u(this,i,(o=l(this,i,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,i,(a=l(this,i,"f"),++a),"f"),c}get(e){var t,r;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,i,(r=l(this,i,"f"),++r),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,i,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const r=this.get(e);if(null!=r){if(r instanceof Error)throw r;return r}return this.set(e,t())}getOrSetAsync(e,t){const r=(0,h.toS)(e);{const e=this.get_(r);if(null!=e)return e instanceof m.Deferred?e.promise:e}const i=new m.Deferred(this.opts.name).observe(t());return this.cache.set(r,i),(0,c.gt0)(this.opts.timeoutMs)&&i.setTimeout(this.opts.timeoutMs),i.promise.then((e=>{this.set(r,e)}),(e=>{var t,i;this.cache.set(r,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(i=l(this,a,"f"),++i),"f")})),i.promise}},i=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class i{constructor(e){this.maxSize=e,this[r]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(r=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=i},53507:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(31586),a=r(68708),l=r(50213),u=r(68852),c=r(81168),d=r(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,i.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,r=!0){return new m(e,t,r).entries};class m{constructor(e,t,r=!0){this.warnIfMissingHeaders=r,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const i=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,i).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let r=e;r!==t;t>e?r++:r--)if(this.blankColumns.has(r))return r;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),r=[];let i,a=0;for(;null!=(i=t.exec(this.headerRow));){const l=this.headerRow.substring(a,i.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:i.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(i.index,t.lastIndex),d=i.index+((0,c.indexOfNonSpace)(u)??0),h=i.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),g=e.find((e=>e.text===m));if(null==g||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:i,left:d,right:h});else{const e=(0,n.last)(r);if(r.push(g),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=g.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,i.index-((0,c.lastIndexOfNonSpace)(l)??l.length));g.leftIdx=g.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),g.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(r);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),r}}t.Fixed=m},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const i=r(51455),n=r(98553);var s=r(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const r=(0,n.parseJSON)(e);return null==r?void 0:t(r)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,i.readFile)(e)).toString())}},19851:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=r(57975),a=r(40958),l=r(50357),u=r(31586),c=r(65812),d=r(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),i.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,i,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const r=await e,i=await t;if(!(0,l.eql)(r,i))for(const e of this.watchers)e(i);null!=this.ttlMs&&this.ttlMs>0&&void 0!==i&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(42659),a=r(50213),l=r(81168),u=r(5916),c=r(56519),d=r(84777),h=r(44198),f=r(6012),m=r(43334),g=r(24399),p=r(63870);t.DefaultLocale="en";const y=(0,i.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?E():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,p.commandTimeoutMs)()}),t.envLocale=(0,i.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const r=w.exec(e.trim())?.groups;return null==r?void 0:(0,n.compact)([r.lang,r.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(g.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function E(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=E,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},50213:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const i=r(19851),n=r(32105),s=r(14593);t.rootLoggers=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},9103:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const i=r(98553),n=r(54557);t.memoize=function(e,t){let r=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return r++,s.getOrSet((0,i.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,i.stringify)(e)),o.size=()=>s.size,o.callCount=()=>r,o}},7282:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=i(r(1708)),s=r(38639),o=r(54993),a=r(19851),l=r(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(55835),a=r(31586),l=r(39926),u=r(54993),c=r(20014);var d=r(31586);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,r){return(0,o.orElse)(h(e,t),r)},t.mapGte0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>=0?t(r):void 0},t.mapGt0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>0?t(r):void 0},t.mapGt0=function(e,t){const r=(0,a.toInt)(e);return null!=r&&r>0?t(r):void 0},t.map2Gt0=function(e,t,r){const i=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=i&&i>0&&null!=n&&n>0?r(i,n):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(f.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(m(e))}function p(e,t){if(null==e||null==t)return;const r=[e,t].map((e=>e.toString(2))),i=Math.max(...r.map((e=>e.length)));return r.map((e=>(0,l.leftPad)(e,i,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let r=0;for(let i=0;ie/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,r){this.store[e*this.columns+t]=r}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(p(e,t),(([e,t])=>(0,i.count)([...e],((e,r)=>e!==t.charAt(r)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(p(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,i.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,r){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let i=0;const n=r*e.length;for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const i=r(40958),n=r(42659),s=r(96249),o=r(55835),a=r(31586),l=r(68708),u=r(34666),c=r(41583),d=r(48884),h=r(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const r={};for(const[i,n]of(0,l.entries)(e)){const e=t(i,n);null!=e&&(r[i]=e)}return r}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const r of e){const e=r();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(r=>t(r,e[r])?e[r]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,r){if(null!=e)return t(e);throw new Error(r)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,i.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[r,i]of m(t))null==e[r]&&(e[r]=i);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[r,i]of(0,l.entries)(t))null==e[r]&&(e[r]=i);return e},t.pickMap=function(e,t,r){const i={};for(const n of t)i[n]=r(n,e[n]);return i},t.mapEntries=g,t.mapNullEntries=function(e,t,r){const i={};let n=0;for(const s of(0,l.keys)(e))if(i[s]=t(s,e[s]),n++,(0,a.gt)(n,r))break;return i},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const r={};for(const i of(0,h.sortIgnoreCase)((0,l.keys)(t)))r[i]=e(t[i]);return r}return t},t.deepDelete=function e(t,...r){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...r))):g(t,((t,i)=>r.includes(t)?void 0:e(i,...r)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const r of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[r])return e[r]}},t.pairToObject=function(e,t){const r={};return r[e]=t,r},t.zipPojos=function(...e){const t={};for(const r of(0,i.uniq)((0,s.flatten)(e.map(l.keys))))t[r]=e.map((e=>e?.[r]));return t}},12801:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=i(r(48161)),s=r(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const i=r(41400),n=r(56409),s=r(31586),o=r(22911),a=r(73614),l=r(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:r,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const g=[];function p(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...i){f=!0,m=Date.now()+(0,s.max_)(t,r);const n=d=new o.Deferred(c);(0,s.gt0)(r)&&n.setTimeout(r);try{n.resolve(await e(...i))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),g.forEach((e=>e.resolve())),g.length=0}return n.promise}const w=(...e)=>{if(p()){if(!0===u)return null;const t=d?.promise;return h=e,(0,i.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return g.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>p(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const i=r(68708),n=r(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const r=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:r.push((0,i.pick)(n,"index","groups"));return r},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,r){const i=[];for(const t of e)try{i.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{i.push(s(t))}const n=0===i.length?t.NothingRegExp:i.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,r)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let r="",i=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(r+=t.source,i||(i=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):r+=s((0,n.toS)(t));return new RegExp(r,t??(i?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=i(r(48161)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(42659),u=r(41400),c=r(96249),d=r(31586),h=r(51926),f=r(54993),m=r(50213),g=r(12801),p=r(22277),y=r(84777),v=r(34102),w=r(43334),S=r(24399),b=r(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let E=!0;const M=(0,o.lazy)((()=>new p.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const r=(0,g.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=g.PriorityClassToNode[r]),E)try{return n.default.setPriority(e,t),t}catch(r){const i=-13===r?.errno||"EACCES"===r?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:i,error:r}),i)return;E=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&g.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,r):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,g.PriorityClassToPosix[r]??g.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+r),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=i(r(1708)),s=r(19851),o=r(40958),a=r(5670),l=r(54993),u=r(7282),c=r(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function g(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=g,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||g())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||g())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const i=r(59455);function n(e){return e instanceof Set?e:new Set((0,i.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,i.toA)(e.keys()).every((e=>t.has(e)))&&(0,i.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,r){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),r())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const r=n(t);return new Set([...e].filter((e=>r.has(e))))},t.diff=function(e,t){const r=n(t);return new Set([...e].filter((e=>!r.has(e))))}},12089:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=r(98553),d=r(34666),h=r(54993),f=r(62344),m=r(56038);t.shim1=function(e){return new g(e.name,e.impl,e.cache,e.toKey)};class g extends f.ExtensibleFunction{constructor(e,t,r,o){super(),i.add(this),this.impl=t,this.cache=r,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,i,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,i,"m",o).call(this,e),(()=>u(this,i,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,i,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,i=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const i=r(42659);t.ShortCommandTimeoutMs=7*i.secondMs},92322:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=r(76790),o=r(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,i.set(this,[])}[(i=new WeakMap,Symbol.iterator)](){return n(this,i,"f")[Symbol.iterator]()}get length(){return n(this,i,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,r=n(this,i,"f").length-1;for(;t<=r;){const s=t+Math.floor((r-t)/2),o=this.valueOf(n(this,i,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:r=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,i,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:r}){if(t>=this.length)return[...n(this,i,"f")];const o=t=>t<0||t>n(this,i,"f").length-1?null:(r??this.diff)(n(this,i,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return n(this,i,"f").shift()}at(e){return(0,o.at)(n(this,i,"f"),e)}toA(){return[...n(this,i,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,i,"f").length-1){const e=[...n(this,i,"f")];return n(this,i,"f").length=0,e}return n(this,i,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,i,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},82328:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const i=r(1708),n=r(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(i.stdout)}},71567:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=i(r(1708)),s=r(22573),o=r(98553),a=r(23560),l=r(82328),u=r(38835),c=r(70025),d=r(95705);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:r,stream:i}){if(null==i||(0,d.streamEnded)(i))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);i.write(n+"\n"),(0,a.isWorkerService)()&&null!=r&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?i.write(u.FailStr+"\n"):i.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const r of e)r.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(55835),a=r(31586),l=r(39926),u=r(34666),c=r(51926),d=r(59455),h=r(54993),f=r(48884),m=r(68852),g=r(38835);var p=r(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return p.splitFirst}});var y=r(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=r(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,r){if(0===r.length)throw new Error("rightPad() given empty pad");const i=String(e);return i+(0,l.padding)(r,t-i.length)},t.padReplace=function(e,t,r,i){return(0,c.strslice)(e,0,t)+(0,l.padding)(i,r)+(0,c.strslice)(e,t+r)},t.contains=function(e,t,r){return(0,h.toS)(e).indexOf((0,h.toS)(t),r)>-1},t.countChars=function e(t,r,i=0){if(null==r||0===r.length)return 0;const n=t.indexOf(r,i);return-1===n?0:1+e(t,r,n+r.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,r){const i=Math.min(Math.ceil(e.length/t),r??e.length)-1;return i<=0?[e]:[...(0,a.times)(i,(r=>e.slice(r*t,(r+1)*t))),e.slice(i*t)]},t.spliceCapture=function(e,t){const r=t.exec(e);if(null==r||null==r[1])return;const i=r[0].indexOf(r[1])+r.index;return{captured:r[1],uncaptured:e.substring(0,i)+e.substring(i+r[1].length),unmatched:e.substring(0,r.index)+e.substring(r.index+r[0].length),matchedIndex:i}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,r={}){if(null==t)return e;const i=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(i.slice(-n.length),n,r)?i.slice(0,-n.length):i},t.gist=function(e,t=80,r=80){const i=(0,h.toS)(e),n=i.length-(t+r);return n<=0?i:i.slice(0,t).trim()+" …(+"+n+" chars)…"+i.slice(-r).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const r=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===r?e.localeCompare(t):r}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,i.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,o.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const r=S(e.cmp[0],t.cmp[0]);return 0!==r?r:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,i.isEmpty)(e)||(0,s.blank)(t))return;for(const r of e)if((0,c.equalsIgnoreCase)(r,t))return{index:0,match:r};for(const r of e){const e=t.indexOf(r);if(e>=0)return{index:e,match:r}}const r=t.normalize();for(const t of e){{const e=r.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=r.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=r.toLowerCase(),i=e.toLowerCase(),n=t.indexOf(i);if(n>=0)return{index:n,match:i}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function E(e){return _.reduce(((e,[t,r])=>e.replace(t,r)),e).normalize()}t.dumbquote=E;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(E(e))&&(e=e.slice(1,-1).trim())),e};const C=/^['‘’].*['‘’]$/,T=/^["“”„«»〃].*["“”„«»〃]$/;function x(e,t){const r=D(e,t);return(0,f.flatZip)(r.nonSeparators,r.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+g.NonRetriableErrorFlag);const r=[],i=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,r.push(e.substring(s,n.index)),i.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),C.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const r=(0,i.compactBlanks)(e),n=Math.max(...r.map((e=>e.length)));for(let e=0;e(0,o.map)(r[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,i.compactBlanks)(e)),r=t.filter(((e,r)=>!P(t[r+1],e)));return(0,n.sortBy)(r,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const r=Math.min(e.length,t.length);for(let i=0;i4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const r=new Set;for(const i of(0,d.toA)(e))if(null!=i&&!(0,s.blank)(i))for(const e of i.split(t))(0,s.blank)(e)||r.add(e);return[...r].join(t)},t.dedupeNeedle=function(e,t,r){if((0,s.blank)(t))return e;const i=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>i.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(r)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const i=r(54993);function n(e){return(0,i.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>"_"+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>" "+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=i(r(77598)),s=r(73913),o=r(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,r=o.Radix58,i=224){return r.encodeBuffer(a(e,i)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,r=o.GeoRadix,i=224){return l(e,t,r,i)}},94863:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const i=r(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,i.toS)(e).toLowerCase().normalize()}},96859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(31586),a=r(39926),l=r(51926),u=r(54993),c=r(55222),d=r(97352),h=r(88158),f=r(77377),m=r(81168);function g(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const r=new d.Array2D(e.length);let i=0,n="";for(let s=0;s=i&&(i=r.get(s,o),n=(0,l.substr)(e,s-i+1,i)));return n}function p(e,t){if(null==e||null==t)return;if(e===t)return 0;const r=y(e,t);if(null!=r)return r;const i=e.normalize(),n=t.normalize();return e!==i||t!==n?y(i,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,r,i)=>r===t.charAt(i)?e:e+1),0)}function v(e,t){const r=e.toUpperCase().normalize(),i=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>r===i?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(r),t=w(i);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,r)=>e+t[r+1]))}function S(e,t){const r=(0,f.intersection)(e,t),n=[];return r.forEach((r=>{const s=Math.min((0,i.count)(e,(e=>e===r)),(0,i.count)(t,(e=>e===r)));(0,o.times)(s,(()=>n.push(r)))})),n}function b(e,t,r){const n=(0,i.commonPrefixLength)(e,t);return r((0,l.strslice)(e,n))-r((0,l.strslice)(t,n))}function P(e){const t=(0,i.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[r,i]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(r,i,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:g(e,t).length/Math.max(e.length,t.length)},t.lcs=g,t.hamming=p,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const E=/[^\da-z]+/gi;function M(e,t){const[r,i]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(E,"").toLowerCase()));return b(r,i,(e=>c.RadixAlphaNum.decode(e)))}function C(e,t){let r;for(let i=Math.max(e.length,t.length);i>=0;i--){const n=(0,o.mapNumericOr)(e.charCodeAt(i),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(i),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);r=null==r?a:(r+a)/2}return r}t.radixDiff=M,t.str=function(e,t){return{pref:(0,i.commonPrefixLength)(e,t),ham:p(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,i.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=C,t.paddedPositionalDiff=function(e,t,r=8){return C((0,a.leftPad)(e,r," "),(0,a.leftPad)(t,r," "))}},84885:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const i=r(98553),n=r(88158);t.stringifySorted=function(e){return(0,i.stringify)((0,n.sortedKeys)(e))}},22277:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=r(73614);class u{constructor(e,t=!1){i.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,i,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,i,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const r=this.delegate.get(e);return null==r||a(this,i,"m",n).call(this,e,r)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,r]of this.delegate)a(this,i,"m",n).call(this,t,r)||e(t,t,this)}has(e){return null!=e&&!a(this,i,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield[t,t])}()}toA(){return a(this,i,"m",s).call(this),[...this.delegate.keys()]}[(i=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const r=t<=Date.now()-this.ttlMs;if(r){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return r},s=function(){for(const[e,t]of this.delegate)a(this,i,"m",n).call(this,e,t)}},94174:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(38639),c=r(31586),d=r(50213),h=r(45255),f=r(84777),m=r(96706),g=r(43334),p=r(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>g.isWin?p.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>g.isWin?g.isWin?p.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const i=r(42659),n=r(55835),s=r(31586),o=r(97790),a=r(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const r=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(r))return;const[o,a,u,c,d,h,f]=r,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*i.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+i.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class r extends Error{}t.AbortError=r},76740:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=r(45599),l=r(56409),u=r(73568);t.Abortable=class{constructor(){this._aborted=!1,i.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,i,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,i,"f")&&clearTimeout(s(this,i,"f")),o(this,i,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},i=new WeakMap,n=new WeakMap},22911:function(e,t,r){var i,n,s,o,a,l,u,c,d,h,f,m,g=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(r(87997)),w=y(r(57975)),S=r(45599),b=r(26905),P=r(55835),_=r(31586),E=r(68708),M=r(20214),C=r(57153),T=r(85556),x=r(50213),D=r(70025),k=r(95937),O="TIMEOUT",I=(0,S.defer)((()=>(0,x.mkLogger)("async.Deferred")));class A{static async*toAsyncIterable(e,t){const r=[...e].reverse(),i=(0,_.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=i&&r.push(i);;){for(let i=r.length-1;i>=0;i--){const n=r[i];if(n.isSettled){if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});r.splice(i,1),yield n.value}}if(r.every((e=>e.name===O)))break;try{await Promise.race(r)}catch{}}i?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var r,m,y;i.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,C.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(p(r=n,n,(y=g(r,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{p(this,u,e,"f"),p(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return g(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:g(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,E.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return g(this,o,"f")}get elapsedMs(){return(g(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,i=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=g(this,h,"f")&&(v.default.clearTimeout(g(this,h,"f")),p(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(p(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),g(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return g(this,a,"f")===C.PromiseStates.pending}get value(){return this.isResolved?g(this,l,"f"):void 0}get error(){return g(this,d,"f")}get isSettled(){return g(this,a,"f")!==C.PromiseStates.pending}get isResolved(){return g(this,a,"f")===C.PromiseStates.resolved}get isRejected(){return g(this,a,"f")===C.PromiseStates.rejected}get settledMs(){return null==g(this,o,"f")?void 0:g(this,o,"f")-this.startedAt}resolve(e){return g(this,i,"m",m).call(this,(()=>{p(this,a,C.PromiseStates.resolved,"f"),p(this,l,e,"f"),g(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return g(this,i,"m",m).call(this,(()=>{p(this,d,t,"f"),p(this,a,C.PromiseStates.rejected,"f"),g(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=A,n=A,m=function(e){if(g(this,a,"f")===C.PromiseStates.pending){(0,P.map)(g(this,h,"f"),v.default.clearTimeout),e(),p(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:g(this,l,"f")});return this},s={value:0}},27395:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const i=r(19851),n=r(40958),s=r(42659),o=r(23838),a=r(13538),l=r(50213),u=r(7282),c=r(97352),d=r(77740),h=r(25764),f=r(99331),m=r(73614),g=(0,i.lazy)((()=>(0,l.mkLogger)("async.Endable"))),p=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const r=await e;if(null==r||!0===r?.ended)return;const i=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,r.endTimeoutMs,y);g().trace(r.name+" ending...",{timeoutMs:i});try{await(0,a.thenOrTimeoutError)(r.end(),i,(0,u.isTest)())}catch(e){try{g().warn(r.name+".end() failed",e)}catch{}}}function w(){p.filterInPlace(((e,t)=>!0!==t.ended)),g().debug("vacuumEndables()",p.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),p.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,i.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;g().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const r=p.get(t)??[];(0,n.isNotEmpty)(r)&&(g().debug("endEndables(): ending "+t),await Promise.allSettled(r.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,n.compact)(p.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const r=p.get(t)??[];e[t]=r.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,r){var i,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=r(87997),h=r(55835),f=r(31586),m=r(68708),g=r(25764),p=r(38836),y=r(99331);class v extends p.EndableWrapper{constructor(e){super(e.name,(()=>u(this,i,"m",o).call(this)),e.rank??g.EndableRanks.first,e.endTimeoutMs),i.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,r=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!r&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,i,"m",o).call(this);const h=()=>{u(this,i,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,i,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,i=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const i=r(50989);t.EndableRanks=(0,i.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=r(19851),l=r(45599),u=r(56409),c=r(50213),d=r(27395),h=r(25764),f=r(99331),m=r(56519);t.EndableWrapper=class{constructor(e,t,r=h.EndableRanks.first,o){this.endTimeoutMs=o,i.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(r,this)}setName(e){o(this,i,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,i,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},i=new WeakMap,n=new WeakMap},99331:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const i=r(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,i.isTest)()?e:e||n}},45608:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=i(r(1708)),s=r(22573),o=r(45599),a=r(37975),l=r(50213),u=r(71567),c=r(57159),d=r(57902),h=r(28874),f=r(27395),m=r(99331),g=r(56038),p=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(g.PromiseTimer.instance().report())}));async function v(e){p().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const r=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==r.errno||!0===r.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const i=(0,s.toNotBlank)(e?.reason)??r.toString();for(const e of t.onFatalHandlers)await e(i)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(r=>{v({reason:`${e}:${t}`,status:0,error:r})}))}))},5916:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=r(45599),f=r(50357),m=r(31586),g=r(41583),p=r(62344),y=r(50213),v=r(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:r,timeoutMs:i}){return new S(e,t,r,i)};class S extends p.ExtensibleFunction{constructor(e,t,r,l){super(),i.add(this),this.later=e,this.desc=t,this.ttlMs=r,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,i,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,i,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,i,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=async function(e,t){var r;try{const r=await t;if(!(0,f.eql)(e?.value??await(e?.promise),r))for(const e of c(this,a,"f"))await e.onChange(r)}catch(e){const t=(0,g.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(r=c(this,s,"f"),++r),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,i,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},56519:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const i=r(40958),n=r(76790),s=r(38639),o=r(42659),a=r(41400),l=r(31586),u=r(20214),c=r(13538),d=r(42279),h=r(32639),f=r(59455),m=r(41583),g=r(48884),p=r(50213),y=r(88158),v=r(15674),w=r(42638);var S=r(20214);async function b(e){if(null==e)return[];const t=(0,i.compact)(await e);return(0,i.isEmpty)(t)?[]:(0,i.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:r,timeoutMs:n}){const s=[];for(const o of(0,i.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(r(o),n):r(o));null!=e&&s.push([e,o])}catch(t){(0,p.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:r,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,i.compact)(await e);if((0,i.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:r,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(r,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(r,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,p.mkLogger)(r).warn("failed to apply",{ea:e,error:t})}})));return(0,i.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,r){const i=[];for(const n of(0,g.batches)((0,f.toA)(await e),t)){const e=await b(n);i.push(...await b(r(e)))}return i},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const r of(0,i.compact)(e)){const e=await r();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;if(null!=e)if(Array.isArray(e))for(const r of e){const e=await r;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;null!=e&&t.push(e)}return(0,i.uniq)(t)},t.asyncFind=async function(e,t){for(const r of e)if(await t(r))return r},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:r,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,i.compact)(t),f:r,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const r=await E({name:"partitionAsync",arr:e,f:t});return[r.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),r.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,r=(e=>console.error(e)),i=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,i)}catch(e){r((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),r=(()=>{})){let i,n=null;try{i=await((0,h.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await r(n??i)}catch{}if(null!=n)throw n;return i},t.thenNot=async function(e,t=!0){if(null==e)return t;const r=await e;return null==r?t:!(0,s.isTrue)(r)},t.thenMap2=async function(e,t,r){const i=await e;if(null==i)return;const n=await t;return null!=n?r(i,n):void 0},t.thenMapOr=async function(e,t,r){const i=await e;if(null==i)return r();const n=await t(i);return null==n?r():n},t.thenMap2Or=async function(e,t,r,i){const n=await e;if(null==n)return i();const s=await t;if(null==s)return i();const o=await r(n,s);return null==o?i():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null==i)continue;const e=await t(i,r);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const r of e){const e=await r();if(null!=e){const r=await t(e);if(null!=r)return r}}},t.firstResolvedDefinedPromise=async function(e,t){for(const r of e)try{const e=await r();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const r of t)try{const t=await r();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:r}){const i=await E({name:e,arr:t,f:r});return(0,n.sortBy)(i,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const i=r(19851),n=r(40958),s=r(76790),o=r(42659),a=r(49769),l=r(31586),u=r(68708),c=r(42279),d=r(41583),h=r(22454),f=r(14121),m=r(50213),g=r(7282),p=r(34102),y=r(82647),v=r(25764),w=r(38836),S=r(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,r){const i=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-i)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-i;return r?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),r?.((0,d.toErr)(t),Date.now()-i),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),r=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),i=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",r.stats()],...i])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:r.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:(0,l.mapFinite)(r.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:r.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:{sumSec:(0,l.sigFigs)(r.sum/o.secondMs,3),...(0,u.omit)(r.stats(),"sum")}})),{})}}function _(e,t,r){return P.instance().time(e,t,r)}function E(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,i.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.isTest)()&&(0,p.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const r=Date.now(),i=t();return E(e,Date.now()-r),i},t.pushTime=E,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,r){return(0,i.lazy)((async()=>_(e,t)),r)}},42638:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(r(66261)),m=r(40958),g=r(55835),p=r(31586),y=r(42279),v=r(54993),w=r(89788),S=r(82647),b=r(15674),P=r(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){i.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,p.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:r,serialId:n}){const s=d(this,i,"m",l).call(this,{name:e,l:t,payload:r,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const r=t.map((t=>d(this,i,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(r)}serial(e,t,r){return this.enqueue({name:e,l:t,serialId:e,payload:r})}push(e,t,r){return d(this,i,"m",u).call(this,new P.Deferred(e,{payload:r}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),r=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,p.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=function({name:e,l:t,payload:r,serialId:i}){const n=new P.Deferred(e,{payload:r,serialId:i});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const r=Date.now();return this.lastWorkTs=r,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-r),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const r=new _(e);return()=>r.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:r}){return new _(e,(0,g.map)(r,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class r extends Error{}t.RedoableError=r},4867:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const i=r(40958),n=r(34546),s=r(41400),o=r(31586),a=r(83104),l=r(85556),u=r(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:r}){let a=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,r?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:r}){let l=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,r?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let r=e=>null;t.setTimeoutHandler=function(e){r=e},t.onTimeout=function({soft:e}={}){r(e)}},73614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const i=r(87997);t.setUnrefTimeout=function(e,t,...r){return(0,i.setTimeout)(e,Math.round(t),...r).unref()},t.setUnrefInterval=function(e,t,...r){return(0,i.setInterval)(e,Math.round(t),...r).unref()}},31562:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const i=r(38639),n=r(42659),s=r(41400),o=r(32639),a=r(31586),l=r(45255),u=r(95937);async function c(e,{timeoutMs:t,intervalMs:r,acceptable:i,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const i=r??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(i,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:i.isTrue,timeoutResult:!1})}},9727:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=i(r(1708)),s=r(45599),o=r(41400),a=r(50357),l=r(68708),u=r(48884),c=r(36638),d=r(44198),h=r(59958),f=r(96706),m=r(34102),g=r(19851),p=r(19043),y=r(66184),v=r(50213),w=r(7282),S=r(88158),b=r(45969),P=r(43334),_=r(28874),E=r(3790);function M(e){return C().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const C=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const r of t.names)e.add(r);for(const r of t.keys)e.add(r)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const T=["HOME","LANG","USER"],x=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],D=(0,g.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?T:x),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function k(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const r of(0,_.persistedSettings)()){const i=e?r.value:r.envValue;null==i||(0,a.eql)(i,r.defaultValue)||r.addToEnv(t)}return t}t.sanitizedEnv=(0,g.lazy)((()=>(0,l.filter)(n.default.env,(e=>M(e)||!(0,E.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=k,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:I({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function I({overrides:e,forceCLocale:r=!0,forWorker:i=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...D(),...r?(0,p.childProcLocale)():{},...k(i),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,E.isHiddenEnvKey)(e)?"(hidden)":t])),[r,i]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(r)),e.debug("non PS env:",(0,l.fromEntries)(i))}return n}t.childEnv=I},84777:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=i(r(31421)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(42659),c=r(98553),d=r(56409),h=r(31586),f=r(68708),m=r(51926),g=r(50213),p=r(7282),y=r(88158),v=r(79089),w=r(45255),S=r(22911),b=r(4867),P=r(73614),_=r(70025),E=r(57159),M=r(36868),C=r(66184),T=r(45643),x=r(95402),D=r(9727),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const r=e.pid;if(null==r||r<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(r===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(r===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+r+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,x.killPid)(r).catch((e=>{k().warn("endProcess(): kill("+r+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,p.isSingleSpecTests)())return!0;if(await(0,T.waitForPidExit)(r,t))return k().debug("endProcess(): exitted",O(e)),!0;{x.Pids.instance()?.onKill(r);const t=e.kill("SIGKILL");k().warn("endProcess("+r+") had to resort to SIGKILL",{killResult:t}),t||await(0,x.killPid)(r,!0).catch((e=>{k().warn("endProcess(): kill("+r+",true) failed: "+e)}))}return(0,T.waitForPidExit)(r,5e3)}function A(e,r,i,n=0){const o=new Date,a=[];return(0,v.niceable)(r,i)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,x.addPid)({pid:e.pid,cmd:r,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function F(e,t,r,i){const s=(0,D.spawnOptions)(i);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:r,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:r}),A(n.default.execFile(e,t,s),e,t,r)}async function N(e,t,r){const i=r.quiet??!1,n=r.ignoreStderr??!1,s=r.ignoreExitCode??!1,o=F(e,t,r.timeoutMs,(0,f.omit)(r,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===r.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],g=[],p=[],y=new S.Deferred(f);o.on("error",(e=>p.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>p.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>p.push(e))),o.stderr?.on("data",(e=>g.push(e))),o.stderr?.on("end",(()=>P.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:r.timeoutMs,halt:r.halt}),k().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt});const C=g.join("");(0,l.notBlank)(C)&&p.push(new Error(C)),!i&&(0,a.isNotEmpty)(p)&&k().warn(f+" resulted in errors:",p);const T=r.isIgnorableError??_.isIgnorableError,x=p.filter((e=>!0!==T(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:C}}catch(e){throw k().error("stdoutResult_() failed",e),await(0,x.killPid)(o.pid,!0),e}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,r,i){const s=(0,D.spawnOptions)(i);return k().debug("spawn()",{command:e,args:t,maxAgeMs:r}),A(n.default.spawn(e,t,s),e,t,r)},t.execFile=F,t.stdoutResult_=N,t.stdout_=async function(e,t,r){const i=await N(e,t,r);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(i.result),meta:{cmd:e,args:t,opts:r,result:i}})}},3790:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const i=r(22573),n=r(41400),s=r(19851),o=r(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,i.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},41269:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const i=r(1708),n=r(31586),s=r(51926),o=r(17344),a=r(37805),l=r(84542);function u(e,t){const r=t?.maxLineLen??(0,n.toInt)(i.env.maxLineLen)??i.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:r,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},94361:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const i=r(19851),n=r(40958),s=r(55835),o=r(31586),a=r(94174),l=r(44198),u=r(45969);function c(e,t,r){const i=(0,o.toGt0)((0,l.env)()[t]);return null==i||r.includes(i)?void 0:`WARNING: ${e} is running as ${r} but $${t}=${i}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,i.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},76596:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const i=r(51168),n=r(19851),s=r(22573),o=r(42659),a=r(55835),l=r(31586),u=r(68708),c=r(34666),d=r(50213),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,r){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=r}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const r=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),i=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(r,i)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),r=Date.now();return t<=r?0:t-r},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const i=r(22573),n=r(31586),s=r(54557),o=r(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,i.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,i.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const i=r(51168),n=r(40958),s=r(22573),o=r(42659),a=r(31586),l=r(51926),u=r(68852),c=r(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=i.Duration.fromISO(e);if(t.isValid)return t.toMillis();const r=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(r,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const r=(0,a.toFloat)(e);if(null!=r){if((0,s.blank)(t))return r;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*o.yearMs;case"weeks":case"week":case"w":return r*o.weekMs;case"days":case"day":case"d":return r*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return r*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return r*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return r*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return r;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,r=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const i=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const r=Math.floor(t/e.ms);t-=r*e.ms,r>0&&i.push(r+e.s)}return i.join(r)}},84248:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const i=r(50989);t.AutoVacuumModes=(0,i.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const i=r(50989);t.CheckpointTypes=(0,i.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const i=r(50989);t.RepairModes=(0,i.strEnum)("dump","recover")},34365:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const i=r(50989);t.SynchronousModes=(0,i.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(r(76760)),a=r(40958),l=r(22573),u=r(55835),c=r(72993),d=r(19851),h=r(97352),f=r(94174),m=r(44198),g=r(96706),p=r(8769),y=r(57159),v=r(70698),w=r(64680),S=r(29882),b=r(45969),P=r(43334),_=r(28874),E=r(41692),M=r(32774),C=r(80612),T=r(32551),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,g.getEnv)("TEMP"),(0,g.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const r of t)(0,l.blank)(r)||e.push({dir:(0,o.join)(r,".photostructure-cache"+x()),preexistingDir:r});return e}}function k(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:M.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(P.isWin?[(0,g.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,r=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return r.push(...D()),r}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,C.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,C.firstDir)({dirs:k(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,E.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(I)}));function I(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,p.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=I},46292:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const i=r(19851),n=r(45969),s=r(41692),o=r(32774),a=r(10924),l=r(84373),u=r(80612);t.configDir=(0,i.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const i=r(66430),n=r(45969),s=r(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,i.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=i(r(76760)),s=r(40958),o=r(72993),a=r(44198),l=r(96706),u=r(43334),c=r(80612),d=r(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const i=r(22573),n=r(96706),s=r(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,i.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const i=r(44652),n=r(40958),s=r(22573),o=r(66430);function a({dirs:e,desc:t}){for(const{dir:r,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(r)){if((0,o.isReadWriteableDirectorySync)(r))return r;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,i.mkdirpSync)(r),r}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const i=r(48161),n=r(76760),s=r(1708),o=r(19851),a=r(40958),l=r(68284),u=r(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,i.homedir)()}))},46296:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(55835),u=r(54993),c=r(72993),d=r(96706),h=r(45969),f=r(43334),m=r(32707),g=r(6707),p=r(49776),y=r(32774),v=r(80612),w=r(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,p.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,g.readTomlFileSync)((0,m.systemSettingsFile)()),r=(0,u.toS)(t?.logDir);return(0,a.notBlank)(r)?r:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const i=r(76760),n=r(19851),s=r(22573),o=r(44198),a=r(43334),l=r(24399),u=r(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,i.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const i=r(38639),n=r(7282),s=r(29325),o=r(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,i.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const i=r(38639),n=r(44198);t.doNotTrack=function(){return(0,i.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=i(r(73024)),s=r(76760),o=i(r(1708)),a=r(19851),l=r(40958),u=r(41400),c=r(68708),d=r(76850),h=r(7282),f=r(23560),m=r(32551),g=r(34102),p=r(53265),y=r(45969),v=r(59958),w=r(6012),S=r(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),r={...o.default.env};for(const i of e)try{const e=(0,d.debom)(n.default.readFileSync((0,p.resolve)(i))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,i]of(0,c.entries)(s))t.test(e)||(r[e]=i)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+i,e)}return r})),(0,u.later)((()=>{(0,g.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const i=r(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,i.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const i=r(50989);t.EnvKeys=(0,i.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const i=r(22573),n=r(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const r={};if((0,i.blank)(e))return r;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,i.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");r[t?e.toLowerCase():e]=o}}return r}},96706:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=i(r(1708)),s=r(19851),o=r(22573),a=r(38639),l=r(41400),u=r(40583),c=r(79840),d=r(83556),h=r(34102),f=r(44198),m=r(83373);function g(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=g,(0,l.later)((()=>{f.env.watchLater(g),(0,h.ee)().on("clearCache",g)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},98314:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const i=r(58587),n=r(19851),s=r(40958),o=r(22573),a=r(26905),l=r(96249),u=r(51926),c=r(23541),d=r(54993),h=r(89788),f=r(50213),m=r(81168),g=r(84542),p=r(41954),y=r(38835),v=r(70025),w=r(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,p.getErrorDescriptions)(e));const r=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,g.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(r)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const r=(0,s.uniqSubstrings)(b(e)),i=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(r.join(a.ErrorDelimiter)),i-o.length,n)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new i.Rate,t.fatalErrorRate=new i.Rate,t.internalErrorRate=new i.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const r=(0,d.toS)(t?.[e]);if((0,o.notBlank)(r))return r}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,r=256,i=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:r})+" at "+(0,a.shortStack)(e?.stack,i).join("; ")}},41954:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const i=r(40958),n=r(26905),s=r(55835),o=r(54993),a=r(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const r of e)(0,s.map)((0,n.errorErrno)(r),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(r),(e=>t.push(l[e]?.description)));return(0,i.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const i=r(40958),n=r(76790),s=r(50989),o=r(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,i.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const i=r(40958),n=r(38639),s=r(26905),o=r(54993),a=r(68852),l=r(73568),u=r(78656),c=r(98314),d=r(38835);function h(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const r=(0,o.toS)(e)+(0,i.compact)(t).join("");return h(r)+f(r).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const g=/Can't write [a-z\d]+ files/i,p=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const r=(0,c.errorToS)(e);return!g.test(r)&&(!!p.test(r)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const r=(0,c.errorToS)(e);return!(!r.includes("EBUSY")&&!r.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const r=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>r.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const i=r(22573),n=r(31586),s=r(68708),o=r(7282),a=r(23560),l=r(45608),u=r(34102),c=r(28874),d=r(98314),h=r(38835),f=r(70025),m=r(57159),g=r(5012);function p(e,t){try{if((0,i.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,g.stack)()),!1;const r=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===r.fatal,c=!0===r.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",r));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:r}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:r.toString(),status:r.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=p,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,r){return p(e+h.InternalErrorFlag,{cause:t,...r})}},57159:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const i=r(40958),n=r(22573),s=r(38639),o=r(26905),a=r(98553),l=r(68708),u=r(59455),c=r(41583),d=r(48884),h=r(81168),f=r(98314),m=r(38835),g=r(70025);t.toWrappedError=function(e,t){const r=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof p&&(null==t||(0,n.blank)(r.message)||e.message.includes(r.message)))return e;const i=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,r?.message);return new p(i??"(missing error message)",r)};class p extends Error{constructor(e,t={}){super(e),this.causes=(0,i.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const r=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??r.some(g.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(r.map(g.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(r.map(g.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(r.map(g.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,g.stripErrorFlags)(function(e,t){let r=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const i=t?.path;return(0,n.blank)(i)||(r=(0,h.dedupeNeedle)(r,i,"file")),(0,f.joinErrorMessages)([r[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...r.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new p(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=p},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=r(49769),a=r(55835),l=r(54993),u=r(22911),c=r(89788),d=r(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,i.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,i,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const r=this.target.emit(e,...t),o=s(this,i,"f").get(e);return null!=o&&(o.resolve(t),s(this,i,"f").delete(e)),r}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},i=new WeakMap,n=new WeakMap},34102:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const i=r(78474),n=r(19851),s=r(15197);t.ee=(0,n.lazy)((()=>{const e=new i.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=i(r(73024)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(65843),u=r(16287),c=r(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):p({stat:e,r:!0,w:!0,x:!0})}function g(e,t){return c.isWin?f(t,n.default.constants.R_OK):p({stat:e,r:!0,x:!0})}function p({stat:e,r:t=!1,w:r=!1,x:i=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(r&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!i||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=g,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const r of(0,l.selfAndAncestorG)(e)){const i=await(0,u.statMaybe)(r);if(null!=i){if(!i.isDirectory())return!1;if(t){if(!g(i,e))return!1}else if(t=!0,!m(i,e))return!1}}return!0},t.access=p},21144:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=i(r(76760)),s=r(19851),o=r(81168),a=r(57159),l=r(43334),u=r(88561),c=r(29882),d=r(65238),h=r(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const r=(0,c.parseNativePath)((0,h.resolve)(...e)),i=await m(r.dir);for(const e of await(0,d.readdir_)(i))if((0,o.equalsIgnoreCase)(e.basename,r.base))return n.default.join(i,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const i=r(73024),n=r(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,i.readdirSync)(e)}catch(e){return[]}}function l(e,t){const r=a(e);return t.every((e=>r.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,r){var i,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&l(t,e,r);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(r(44652)),g=c(r(73024)),p=r(51455),y=f(r(76760)),v=f(r(1708)),w=r(46466),S=f(r(57975)),b=f(r(38522)),P=r(19851),_=r(40958),E=r(5233),M=r(22573),C=r(42659),T=r(50357),x=r(96249),D=r(98553),k=r(55835),O=r(31586),I=r(68708),A=r(97790),F=r(39926),N=r(51926),L=r(59455),R=r(54993),j=r(48884),B=r(22911),V=r(99331),z=r(56519),W=r(56038),q=r(31562),U=r(76850),G=r(70025),H=r(34102),J=r(80875),K=r(50213),$=r(70417),Y=r(43334),Z=r(81168),X=r(96859),Q=r(65162),ee=r(94174),te=r(64660),re=r(21144),ie=r(84542),ne=r(89968),se=r(20197),oe=r(88561),ae=r(50597),le=r(33456),ue=r(29882),ce=r(78133),de=r(43899),he=r(65238),fe=r(53265),me=r(17217),ge=r(16287),pe=r(68284),ye=r(66003),ve=r(27794),we=r(73428),Se=r(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(i.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,K.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,i=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),r=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(r)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const r=(0,me.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,M.blank)(r))throw new Error("BaseFile.for(): empty nativePathOrFile");const i=be().get(r);if(null!=i)return i;const n=(0,fe.resolve)(r),s=new Pe(n,t);return be().set(r,s),be().set(n,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const r=[];for(const i of t)!0===await e(i)&&r.push(i);return r}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,i,"m",s).call(this)??await d(e=this.clearThisAndParent(),i,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const r of t)await r.visitDescendants(e),await e(r)}))}async descendants(e){const t=[];t.push(...(0,L.toA)(await this.childFiles(e)));const r=await this.childDirectories();if(null==r)return t;for(const i of r)t.push(...(0,L.toA)(await i.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const r=await d(this,n,"f").call(this)??[];for(const t of r)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const i of r)if(i.isDirectory()){const r=await this._directoryEntryChild(i).someDescendant(e,t-1);if(null!=r)return r}}descendantsSync(e){const t=this.directoryEntrySync(),r=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&r.push(this.forDirectoryEntry(t))})),r}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,re.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,r)=>this.join((0,R.toS)(e),(0,F.pad2)(t+1),(0,F.pad2)(r))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,r="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(r,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,r="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(r,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,r){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(r??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,ge.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,ge.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,C.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,ge.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>=(0,C.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(r=>Math.abs(r-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>(0,C.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,A.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,q.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*C.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,J.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,J.parseJSON)((0,g.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,g.readFileSync)(this.nativePath)}readFile_(){return(0,p.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return g.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,E.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,V.ending)()?1:3,timeoutMs:0,retryDelay:C.secondMs,errorIsRetriable:G.isRetriableError})}async gunzip(){return d(this,i,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,i,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,i,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return g.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return g.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const r=await this.children((async r=>!r.isNameHidden()&&t===r.size()&&r.nativePath!==e.nativePath));if((0,_.isEmpty)(r))return;const i=await e.sha();if(null!=i)for(const e of r.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===i)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),r=g.default.createReadStream(this.nativePath,{flags:"r"});return r.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),r.close()):t.maybeReject(e)})),r.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(r,(0,N.newlineRe)(),(i=>{const n=e.exec(i);null!=n&&(t.maybeResolve(n),r.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,r)=>{for(const i of e)for(const e of r)if((0,O.closeTo)(i,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),r=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&r.setTimeout(e.timeoutMs),_e)try{const i=(0,g.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(i,n)=>{try{const s=await e.f(i,(0,k.denull)(n));t(s)&&r.resolve(s)}catch(e){r.reject(e)}}));r.finally((()=>{i.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const i=setInterval((async()=>{try{const i=await e.f();t(i)&&r.resolve(i)}catch(e){r.reject(e)}}),e.intervalMs);e.persistent||i.unref(),r.finally((()=>{clearInterval(i)}))}return r}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const r=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([g.default.createReadStream(this.nativePath,{autoClose:!0}),t,g.default.createWriteStream(r.nativePath,{autoClose:!0})]),await this.unlink(),r}))},Pe.attrTTL=3*C.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},84542:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const i=r(40958),n=r(96249),s=r(51926),o=r(54993),a=r(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,i.compactBlanks)(l(...e))}},70698:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const i=r(76760),n=r(19851),s=r(50213),o=r(37805),a=r(29882),l=r(93854),u=r(17217),c=r(16287),d=r(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const r=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return r===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,i.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const r=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(r),await(0,d.writeTextfile_)((0,a.joinNativePath)([r,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(45969),u=r(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(r(44652)),l=o(r(73024)),u=r(76760),c=r(57975),d=r(19851),h=r(59455),f=r(50213),m=r(81168),g=r(34102),p=r(29882),y=r(65238),v=r(14427),w=r(17217),S=r(16287),b=r(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class E{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,p.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new E(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:r,base:i}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,p.parseNativePath)(e)},n=await a.stat(t);return new E(r,new P(i,n))}clear(){return(0,g.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return E.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,p.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,p.parseNativePath)(this.dir);return e.dir===this.dir?this:new E(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>E.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new E(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const r of t)r.isDirectory()&&await r.visitDescendants(e);for(const r of t)r.isFile()&&await e(r);for(const r of t)r.isDirectory()&&await e(r)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const r of t)r.isFile()&&e(r);for(const r of t)r.isDirectory()&&(r.visitDescendantsSync(e),e(r))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async r=>{!0===await e(r)&&t.push(r)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,g.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,g.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=E},20197:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=i(r(76760)),s=r(39926),o=r(29882),a=r(16287),l=r(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if(await(0,o.mkdirp_)(i.dir),!r.requireNumber&&await(0,a.isEmptyFile)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if(await(0,a.isEmptyFile)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)},t.ensureNewNativePathSync_=function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if((0,o.mkdirpSync_)(i.dir),!r.requireNumber&&(0,l.isEmptyFileSync)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if((0,l.isEmptyFileSync)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)}},88561:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=r(40958),a=r(22573),l=r(41400),u=r(68708),c=r(25764),d=r(38836),h=r(34102),f=r(80049),m=r(50213),g=r(88158),p=r(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:p.ShortCommandTimeoutMs,...e}),i.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,i,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,g.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,i=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const i=r(73024),n=r(22573),s=r(45599),o=r(96249),a=r(68708),l=r(54993),u=r(49047),c=r(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...r]of d)for(const i of r)e[i]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof i.Dirent?e.name:(0,l.toS)(e),r=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(r)?void 0:h()[r]??r}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const r of t)if(r===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const i=r(68708),n=r(17217),s=r(16287),o=r(68284);async function a(e){return(0,i.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,i.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},4001:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const i=r(22573),n=r(55835),s=r(31586),o=r(51926),a=r(54993),l=r(97352),u=r(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,i.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,r){if(t.ymdIsoRE.test(e))return e;let i=e;for(const e of r.aggressive?d:c){const t=i.match(e);if((0,s.gt0)(t?.index)){const e=i.slice(0,t.index).trim();e.length>0&&(i=e)}}return e===i?e:f(i,r)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),r=t.pop();if((0,i.blank)(r))return e;const n=(0,u.parsePosixPath)(r),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),r=h(t),i=(0,o.stripPrefix)(t.toLowerCase().normalize(),r);return(0,n.map)((0,l.extractInt)(i),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,g=/(?<=.{6})_cover$/i,p=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(g,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(p.exec(t),(e=>t=e[1].trim())),t}},50597:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=i(r(77598)),s=i(r(73024)),o=r(46466),a=r(19851),l=r(98553),u=r(68708),c=r(23467),d=r(80049),h=r(73913),f=r(50213),m=r(12089),g=r(37628),p=r(43624),y=r(17217),v=r(16287),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:r=!0}={}){const i=(0,y.toNativePath_)(e);if(r){const t=S().get(i);if(null!=t){if((0,c.eql)(t.stats,await(0,p.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:i,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:i,prior:t}),S().delete(i)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),r=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(r)),stats:(0,u.pick)(await(0,v.stat_)(r),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],r="sha512"){const i=n.default.createHash(r);return await(0,o.pipeline)([e,...t,i]),i.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,g.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},25675:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const i=r(22573),n=r(54993),s=r(7282),o=r(43334),a=r(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,i.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const i=r(57075),n=r(51926),s=r(54993);class o extends i.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,r){const i=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=i.pop();this._prior=o??"";let a=!1;for(const e of i)a||(a=!this.push(e));a?setTimeout(r,1):r()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=i(r(76760)),s=r(17217),o=r(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},29882:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(5233),u=r(22573),c=r(98553),d=r(39426),h=r(51926),f=r(48884),m=r(50213),g=r(81168),p=r(70025),y=r(43334),v=r(78133),w=r(53265),S=r(17217),b=r(16287),P=r(66430),_=r(5545);function E(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=E,t.containsHiddenPathname=function(e){return k(e).some(E)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!E(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return C((0,v.posix2native)(e))},t.extname=function(e){return C(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,g.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function C(e){const t=M.exec(e)?.groups,r=t?.ext2??"",i=s.default.parse(t?.path??e);return{...i,ext:(i.ext??"")+r,base:(i.base??"")+r}}function T(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),r=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(r))return!1;const i=e.acceptSelf??!1;return t===r?i:r.startsWith((0,g.ensureSuffix)(t,s.default.sep))}catch(r){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:r}),!1}}function D(e,t,r){if(null==t||null==r)return!1;const i=e(t),n=e(r);return null!=i&&null!=n&&(y.isLinux?i===n:(0,g.equalsIgnoreCase)(i,n))}function k(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&k(e).length===(y.isWin?1:0)}function I({p:e,maxLength:t}){const r=(0,S.toNativePath_)(e);if(r.length<=t)return r;const i=k(e),n=[],s=[i.pop()];for(;i.length>0;)if(n.length=t){i.unshift(n.pop());break}}else if(s.unshift(i.pop()),F([...n,...s]).length>=t){i.push(s.shift());break}return i.length>0&&n.push("…"),F([...n,...s])}function A(e){return e.startsWith("\\\\")}function F(e){return(0,h.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=C,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(S.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const r=(0,S.toNativePath_)(e),i=(0,S.toNativePath_)(t);if((0,u.blank)(r)||(0,u.blank)(i))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return r===i?"":(0,g.stripPrefix)((0,v.native2posix)(i).normalize(),(0,g.ensureSuffix)((0,v.native2posix)(r),"/").normalize()).normalize()},t.ellipsizePath=I,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:r=4,arrLength:i=e.length}){const n=[];for(const i of e.slice(0,r))n.push(I({p:i,maxLength:t}));return n.join(", ")+(i>r?`, and ${i-r} more…`:"")},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const r=C(e);return`${r.base}${t}${r.ext}`},t.isUNC=A,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(A(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(31586),u=r(51926),c=r(12168),d=r(59455),h=r(54993),f=r(50213),m=r(44198),g=r(96706),p=r(45969),y=r(43334),v=r(64660),w=r(21144),S=r(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const r=await(0,S.statMaybe)(e,"trace");return null!=r&&r.isFile()&&(0,l.gte)(r.size,t)&&(0,v.isStatRX)(r,e)}function E(){if(y.isWin){const e=(0,a.toNotBlank)((0,g.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,g.getEnv)("SystemDrive"))??"C:",r=(0,a.toNotBlank)((0,g.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(r,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,p.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...E()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:r}){const i=(0,o.uniq)((0,o.compactBlanks)([...M(),...(0,d.toA)(r)]));for(const r of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(r,".exe"):r;for(const t of i){const r=n.default.join(t,e);if(await _(r))return y.isLinux?r:(0,w.actualPath)(r)}}b().warn("Failed to find tool",{tool:e,dirs:i})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},78133:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=i(r(76760)),s=r(22573),o=r(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const r=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",i=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(i[0],t)&&i.unshift(),r+i.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(48884),u=r(50213),c=r(45969),d=r(29325),h=r(43334),f=r(65843),m=r(25675),g=r(53265);function p(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(n.default.join((0,g.execDir)(),"resources"),n.default.join((0,g.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,g.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const r of t){if((0,f.hasChildrenSync)(r,e))return r;for(const t of(0,f.ancestors)(r).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const i=n.default.join(r,"node_modules","photostructure");if((0,f.hasChildrenSync)(i,e))return i}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:p("bin"),Data:p("data"),ICC:p("data","icc"),Migrations:p("data","migrations"),Public:p("public"),Tools:p("tools"),Views:p("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const i=r(44652),n=r(19851),s=r(31586),o=r(50213),a=r(57902),l=r(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,i.readFile)(e)}catch(r){return void u().log(t,".readFileMaybe("+e+")",r)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const i=r(44652),n=r(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:r}){let s=-1;try{const n=r??(await(0,i.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,i.open)(e,"r"),await(0,i.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,i.close)}}},69428:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(r(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},32323:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const i=r(57075);class n extends i.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=i(r(51455)),s=r(76760),o=r(19851),a=r(76790),l=r(22573),u=r(42659),c=r(41400),d=r(31586),h=r(13538),f=r(83104),m=r(54127),g=r(50213),p=r(95937),y=r(34102),v=r(28874),w=r(63870),S=r(88561),b=r(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,g.mkLogger)("fs.Readdir")));async function _(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const E=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||E.prior()?.delete(e)}async function C(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await E().getOrSetAsync(e,(()=>async function(e){const r=Date.now()+2*(0,b.statTimeoutMs)(),i=T(e),n=await(0,h.thenOrTimeout)(i,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===f.Timeout&&(0,p.onTimeout)({soft:!1}),n!==f.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),E.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!E().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=E().get(e)},t.childDirectories_=async function(e){return(await C(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?C(e):T(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=C,t.readdirCached=function(e){return E().get(e)},t.readdirUncached_=T},53265:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=r(73024),s=i(r(76760)),o=r(40958),a=r(22573),l=r(45599),u=r(50213),c=r(43334),d=r(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function g(...e){for(const t of m()){const r=s.default.resolve(t,...e);if((0,n.existsSync)(r))return r}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?g(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=g},50274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const i=r(50989);t.SidecarExts=(0,i.strEnum)("xmp","mie","exv")},14427:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const i=r(22573),n=r(38639);t.isSimpleDirent=function(e){return null!=e&&(0,i.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=i(r(73024)),s=i(r(76760)),o=r(22573),a=r(98553),l=r(81168),u=r(43334),c=r(29882),d=r(53265),h=r(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function g(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=g,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(g(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const p=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(p)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),r=t.indexOf(s.default.sep);return r>0?t.slice(1,r):void 0}},t.findFileIndex=function(e,t){for(let r=0;r(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,p.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((r=>{y().log(t,"stat() failed",{error:r,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const r=S(e),i=S(t);if(r!==i)return"inconsistent file type: "+r+" ≠ "+i;for(const r of["size","mtime"]){const i=e[r],n=t[r],s=(0,u.diff)(b(i),b(n));if(null==s||s>1)return"unmatched "+r+": "+i+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const r=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=r&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(r)},t.isNonEmptyFile=async function(e,t=0){const r=await w(e);return null!=r&&r.isFile()&&r.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.access)({stat:r,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.isStatRWX)(r,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=i(r(73024)),s=r(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const r=o(e);return t.emptyIsNew?null==r:a(r)},t.isNonEmptyFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const i=r(28874);t.statTimeoutMs=function(){return i.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const i=r(22573),n=r(56409);t.onDataChunked=function(e,t,r){const i=new s(t,r,!0);return i.read(e),i.done};class s{constructor(e,t,r=!0){this.sep=e,this.onData=t,this.filterBlanks=r,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,i.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,i.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=i(r(57075)),s=r(41400),o=r(55835),a=r(68708),l=r(42279),u=r(99331),c=r(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((r,i)=>{!1===e.write(t,(e=>{e&&i(e)}))?e.once("drain",r):r()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:r,ea:i}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(i,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(r,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends n.default.Transform{constructor(e){super({transform:(e,t,r)=>{this.onProgress(this.bytes+=e.length),r(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=i(r(73024)),s=r(76760),o=r(22573),a=r(76596),l=r(64660),u=r(78133),c=r(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},27794:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=i(r(44652)),s=r(19851),o=r(22573),a=r(42659),l=r(31586),u=r(68708),c=r(13538),d=r(29882),h=r(17217),f=r(16287),m=r(41080);function g(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const r=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const i=(0,h.toNativePath_)(t.file);r&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(g(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),p=Math.round(g(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(i,new Date(p),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!r||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(i),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},5545:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=i(r(76760)),s=r(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const r=t.driveRe.exec(e)?.groups;return null==r?e:r.drive.toUpperCase()+(0,s.toS)(r.path??n.default.sep)}},58722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const i=r(57075),n=r(22911);class s extends i.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,r){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),r()}}t.WritableToBuffer=s},73428:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(51926),a=r(54993),l=r(34102),u=r(84542),c=r(29882);async function d(e,t){const r=s.default.dirname(e);await(0,c.mkdirp_)(r),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",r)}function h(e,t){const r=s.default.dirname(e);(0,c.mkdirpSync_)(r),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",r)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const r=(0,u.crlf)(...(0,o.wrap)(t));await d(e,r)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=i(r(73024)),s=r(76760),o=r(46466),a=r(38522),l=r(19851),u=r(40958),c=r(98553),d=r(80875),h=r(50213),f=r(57159),m=r(29882),g=r(57902),p=r(32323),y=r(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,r){const i=[],s=[n.default.createReadStream(e,{autoClose:!0,...r}).on("error",(e=>i.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>i.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>i.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(i))throw new f.WrappedError("zPipe("+e+") failed",{causes:i,path:e})}async function b(e,t){const r=new y.WritableToBuffer;return await S(e,r,t),await r.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const r=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new p.ReadableBuffer(r),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=g.LogLevels.warn){try{return await P(e)}catch(r){return void v().log(t,"readJsonGz("+e+"): failed",r)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,r=g.LogLevels.warn){try{await _(e,t)}catch(t){v().log(r,"outputJsonGz("+e+"): failed",t)}}},33866:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const i=r(50989);t.HealthCheckIds=(0,i.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},52086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const i=r(50989);t.CropStrategies=(0,i.strEnum)("center","entropy","attention")},48584:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const i=r(50989);t.SharpFailOns=(0,i.strEnum)("none","truncated","error","warning")},32105:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const i=r(19851),n=r(23560),s=r(66184),o=r(72210);class a{log(e,t,r,i){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:r,meta:i})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,i.lazy)((()=>new a))},14593:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const i=r(57975),n=r(22573),s=r(26905),o=r(55835),a=r(68708),l=r(13538),u=r(50213),c=r(97352),d=r(45255),h=r(76740),f=r(57159),m=r(57902),g=/logger|lazy/i;class p{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!g.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[i.inspect.custom](){return this.toLogJSON()}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const r=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(r),this.log(!0===r.ignorable?"warn":"error",".throw() "+r.message,{stack:r.stack,...t}),r}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let r;try{r=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const i=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:i,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(r,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const r of this.loggers())if(r.enabled(e,t??this.context))return!0;return!1}log(e,t,r){for(const i of this.loggers())i.log(e,this.context,t,r)}elapsed(e,t,r){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...r})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=p},28981:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const i=r(19851),n=r(51879);t.DefaultLogFormatter=(0,i.lazy)((()=>new n.PlaintextLogFormatter))},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},4904:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const i=r(76790),n=r(31586),s=r(51926),o=r(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,i.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const i=r(19851),n=r(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,i.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,i.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,r){return(0,t.logFilter)().enabled(e)?r():void 0},t.isLogged=function(e,r){return(0,t.logFilter)().enabled(e,r)}},57902:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const i=r(31586),n=r(50989),s=r(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,r){return(0,i.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(r))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},72210:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const i=r(92322),n=r(82328),s=r(28981),o=r(20839),a=r(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new i.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const r of e)l?t.logEntries.add(r):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(r))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},51879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(68708),a=r(54993),l=r(23560),u=r(81168),c=r(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,i.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:r,meta:i})}}},82647:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=r(57975),a=r(40958),l=r(96249),u=r(55835),c=r(31586),d=r(68708),h=r(59455),f=r(48884),m=r(89788),g=r(22454),p=r(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const r=t.clone();return r.pushAll(e.samples),r}if(t.n<=t.maxSamples){const r=e.clone();return r.pushAll(t.samples),r}{const r=new y(Math.max(e.maxSamples,t.maxSamples));r._n=e.n+t.n,r._min=Math.min(e._min,t._min),r._max=Math.max(e._max,t._max),r._m=e._m*e.n/r.n+t._m*t.n/r.n,r._s=e._s*e.n/r.n+t._s*t.n/r.n;const i=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return r._samples.push(...i),r._weightedTotalAvg=(0,p.weightedAvg)([r._m,...i]),r}}constructor(e=20){i.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(i=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,p.min)([this._min,e.min]),this._max=(0,p.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),r={};return r.k=t(this.n),this.empty||(r.mean=t(this.avg),r.sum=t(this.sum),r.sd=t(this.stdDev),r.max=t(this.max),r.min=t(this.min)),r}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,i,"m",n).call(this,-1)}get p29(){return s(this,i,"m",n).call(this,-.5)}get p38(){return s(this,i,"m",n).call(this,-.25)}get p69(){return s(this,i,"m",n).call(this,.5)}get p84(){return s(this,i,"m",n).call(this,1)}get p98(){return s(this,i,"m",n).call(this,2)}get p99(){return s(this,i,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new g.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,p.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,p.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,p.avg)}get sampleSlope(){return(0,p.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,p.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const i=r(40958),n=r(55835),s=r(31586),o=r(30976),a=r(48884),l=r(70417);function u(e,t){const r=Math.pow(2,t),i=[];for(;e>0;)i.unshift(e%r),e=Math.floor(e/r);return i}t.concatBits=function(e,t){const r=Math.pow(2,t);return e.reduce(((e,t)=>e*r+(0,s.clamp)(0,r,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,r){return(0,n.map2)(e,t,((e,t)=>(0,i.sum)((0,a.zip)(u(e,r),u(t,r)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,r[t]=o):i[t]=o}return s}unzip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max));for(let n=0;n(r[e]+i[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,r){return!0!==r&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let r=0;rs?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const r=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,i.sum)(e,((r,i)=>t(r,i)?Math.pow(2,e.length-i-1):0))}},55222:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const i=r(77598),n=r(22573),s=r(55835),o=r(32639),a=r(88158),l=r(81168),u=BigInt(0);function c(e,t,r=0){if(!isFinite(t)||e<=1)return[];const i=[];if(0===t)i.unshift(0);else for(;t>0;)i.unshift(t%e),t=Math.floor(t/e);for(;i.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const r=e<0;return r&&(e=Math.abs(e),t--),(r?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],r=BigInt(this.base);let i=e;for(;i>u;)t.push(Number(i%r)),i/=r;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let r of e)for(t.forEach(((e,i)=>{r+=e<<8,t[i]=r%this.base,r=Math.floor(r/this.base)}));r>0;)t.push(r%this.base),r=Math.floor(r/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const r=BigInt(this.base);let i=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;i=i*r+BigInt(e)}return t?BigInt(-1)*i:i}randomChars(e){return this.encodeBuffer((0,i.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,r="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(r)}tokenEql(e,t,r){const i=this.normalizeToken(e),n=this.normalizeToken(t);return i.length>=r&&i===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const i=r(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,i.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},70417:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=r(40958),l=r(55835),u=r(31586),c=r(59455),d=r(22454),h=r(77377),f=r(82647);function m(e){let t;for(const r of e)null!=r&&(null==t||rt)&&(t=r);return t}function y(e,t){const r=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&r.incr(t);return r.topKeys(t)}function v(e,t){let r=0,i=0;for(const n of e){if(null!=n){const e=t(n,r);(0,u.isNumber)(e)&&(i+=e)}r++}return i}t.min=m,t.max=p,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,r)=>e-t[r]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const r of e)(0,u.isNumber)(r)&&(t+=r);return t},t.sumf=v;class w{constructor(){i.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,i,"f")/(s(this,i,"f")+1)+e/(s(this,i,"f")+1),"f"),o(this,i,(t=s(this,i,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const r of e)t.push(r);return t.mean}function b(e){const t=S(e);if(null==t)return;let r=0,i=0;for(const n of e)(0,u.isNumber)(n)&&(i++,r+=(n-t)*(n-t));return r/i}function P(e){let t=0;for(const r of e)t+=r*r;return Math.sqrt(t)}function _(e,t){let r=0;for(let i=0;i(1-t)*e+t*(r+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),r=S(t);if(null!=r){const e=(t.length-1)/2,i=v(t,((t,i)=>(t-r)*(i-e))),n=v(t,(e=>(e-r)**2));return 0===n?0:i/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let r;t=(0,u.clamp)(0,1,t);for(const i of e)r=null==r?i:r*t+i*(1-t);return r},t.centroid=function(e){const t=e[0].length,r=[];for(let i=0;ie[i]))));return r},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},45969:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const i=r(73024),n=r(38639),s=r(19851),o=r(59958),a=r(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,i.existsSync)("/.running-in-container"))))},29325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const i=r(76760),n=r(19851),s=r(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,i.join)("core","platform","IsPacked"))))},43334:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(22573),a=r(38639),l=r(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=i(r(73024)),s=r(19851),o=r(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const i=r(58587),n=r(59455),s=r(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(i.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,i.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=r(58587),d=u(r(31421)),h=u(r(1708)),f=r(40958),m=r(22573),g=r(42659),p=r(55835),y=r(31586),v=r(97790),w=r(59455),S=r(54993),b=r(54557),P=r(19851),_=r(50213),E=r(88158),M=r(409),C=r(78406),T=r(25764),x=r(99331),D=r(56519),k=r(46292),O=r(8769),I=r(83278),A=r(32144),F=r(29882),N=r(43334),L=r(24399),R=r(58261),j=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),B=10*g.secondMs;function V(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const r=(0,p.map)(t.start,(e=>e.getTime())),i=e.startTime;return(0,y.gt0)(r)&&(0,y.gt0)(i)&&Math.abs(r-i){const e=Date.now()-2*g.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,A.isJsonExt)(t)&&(0,F.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:g.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,r=e.force??N.isWin,i=await this.pidfiles(),n=await this.pids(i??[]);if((0,f.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,R.pidInfos)(n);if(null!=a){for(const n of i){const i=await n.readJson();if(null==i){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=i.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:i,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!V(i,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:i,pidEntry:u}),await n.unlink("debug"),s.push(i);continue}const c=(0,y.gt0)(i.timeoutMs)?i.startTime+i.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(i.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:i}),o.push(W(l,r,!1)),s.push({...i,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,r=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(r&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const r=a(this,i,"m",s).call(this,e.pid),n=(0,v.opt)((0,E.Try)((()=>(0,F.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await r.writeJson_(l),j().debug("addPid() wrote "+r,l),r}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,i,"m",s).call(this,e);return(0,D.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,g.ago)(g.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new C.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*g.minuteMs,rank:T.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=q,n=new WeakMap,o=new WeakMap,i=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},q.instance=(0,P.lazy)((()=>(0,p.map)((0,k.configDir)(),(e=>new q(I.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return q.instance()?.addPid_(e,t)}},58261:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=r(31421),s=r(48161),o=i(r(1708)),a=r(40958),l=r(22573),u=r(42659),c=r(31586),d=r(68708),h=r(59455),f=r(54993),m=r(48884),g=r(53507),p=r(19851),y=r(50213),v=r(84968),w=r(48963),S=r(56519),b=r(84777),P=r(8103),_=r(45879),E=r(43334),M=r(24399),C=r(45643),T=(0,p.lazy)((()=>(0,y.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){if(E.isLinux)return async function(e){const t=[];for(const r of e)t.push(z(await(0,_.readFileMaybe)("/proc/"+r+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,C.existingPids)(e),r=(await(0,m.collectBatchedAsync)(t,20,E.isWin?A:R)).filter((e=>x(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:r,meta:{pids:e}})}t.isProcEntry=x,t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,C.existingPids)(e),(t=>{const r=[o.default.pid,...t];return e.filter((e=>!r.includes(e)))}))},t.pidInfos=D;const k="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function A(e){if(M.PowerShell.instance().ended)return L(e);const t=[k,"-Id",I(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},N=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const r=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",r)}t.push("get",N.join(","));const r=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),i=(0,d.onlyReqValued)((0,g.parseFixed)(N,r.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return i.find((e=>e.pid===o.default.pid))||i.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),i}async function R(e){return t=(await(0,b.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,g.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=L;const j=(0,p.lazy)((()=>{try{if(E.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){T().warn("clk_tck failed",{error:e})}return 100})),B=(0,p.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),V=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function z(e){const t=V.exec((0,f.toS)(e))?.groups,r=(0,c.toInt)(t?.pid),i=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(r)&&!(0,l.blank)(i)&&(0,c.gt0)(n)?{pid:r,cmd:i,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},24399:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const i=r(58587),n=r(19851),s=r(22573),o=r(42659),a=r(41400),l=r(55835),u=r(13538),c=r(36557),d=r(14121),h=r(50213),f=r(7282),m=r(45255),g=r(81168),p=r(25764),y=r(38836),v=r(99331),w=r(56519),S=r(31562),b=r(84777),P=r(34102),_=r(43334),E=r(28874),M=r(63870),C="{ready}",T=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),p.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new i.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",E.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${C}"}`,...(0,s.mapNotBlankOr)(E.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:C,fail:"Error",exitCommand:"exit",maxProcs:E.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),p.EndableRanks.postdb),E.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(E.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,g.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const r=this.mockResults.get(e);return t(r.stdout,r.stderr,r.passed)}try{const r=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new i.Task(e,((r,i,n)=>t((0,l.map)(r,(t=>(0,g.stripPrefix)(t,e))),i,n)))));return this.logger.tap({msg:"execute()",result:r.result,meta:{elapsedMs:r.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,g.ensureSuffix)(e,T),((e,t,r)=>({stdout:e,stderr:t,passed:r})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const r=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,g.ellipsize)(t.stdout),after:(0,g.ellipsize)(r)}),JSON.parse(r)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,n.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const i=r(50989);t.AggregateTypes=(0,i.strEnum)("union","intersection")},71988:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const i=r(50989);t.AssetFileSortCriteria=(0,i.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const i=r(22573),n=r(38639),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(i.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const i=r(50989);t.ColorDistanceFunctions=(0,i.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const i=r(36507),n=r(22573),s=r(45599),o=r(50213),a=r(81168),l=r(98314),u=r(8769),c=r(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,i.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,r){try{return(0,n.blank)(t)?void 0:(0,i.Cron)(t,{name:e,unref:!0,protect:!0,catch:r=>(0,u.onError)(r,{name:e,crontab:t}),...r})}catch(r){return void d().warn("invalid cron",{name:e,crontab:t,error:r})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const i=r(70488),n=r(91655),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration})}get valueOrDefault(){return(0,i.decodeDuration)(super.valueOrDefault)}get value(){return(0,i.decodeDuration)(super.value)}set value(e){super.userValue=(0,i.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,i.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,i.decodeDuration)(this.defaultValue)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const i=r(22573),n=r(53265),s=r(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,i.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const i=r(51926),n=r(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,i.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=r(19851),a=r(40958),l=r(79666),u=r(50357),c=r(57924),d=r(98553),h=r(55835),f=r(68708),m=r(39926),g=r(46891),p=r(42279),y=r(59455),v=r(40583),w=r(81168),S=r(44198),b=r(96706),P=r(34102),_=r(28283),E=r(81075),M=r(98778),C=r(10357);t.settingsToObj=function(e){const t={};for(const r of e)r.hasValue()&&(t[r.name]=r.value);return t},t.Setting=class{constructor(e){i.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,i,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const r=this.opts.whyInvalid?.(e);return null!=r?s(this,i,"m",n).call(this,e??t)+": "+r:null==this.fromEnv(e)?s(this,i,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const r=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=r)return r}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const r=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(r)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return E.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,p.tot)(this.optsOverrides.defaultValue)??(0,p.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,p.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const r=e??(0,S.env)(),i=t??this.value;return null!=i&&(r[this.key]=this.toEnv(i)),null==e&&b.caseInsensitiveEnv.unset(),r}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const r=e??(0,S.env)(),i=this.toEnvValue(t);return null!=i&&(r[this.key]=i,null==e&&b.caseInsensitiveEnv.unset()),r}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const r of t.delete(e)??[])delete process.env[r];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],C.WrapComments);function r(e,r){(0,a.isEmpty)(r)||t.push(...(0,w.wrap)(["",(1===r.length?e:(0,g.pluralize)(e))+": "+(0,c.orList)(r.map((e=>(0,d.stringify)(e))))],C.WrapComments))}r("alias",this.opts.aliases),r("environment alias",this.altKeys);for(const[e,r]of(0,f.entries)(this.addToJSON())){const i=Array.isArray(r)?(0,c.orList)(r.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(r);t.push(...(0,w.wrap)(["",e+": "+i],C.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Example value:"],key:this.name,value:(0,p.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Default value:"],key:this.name,value:(0,p.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,p.tot)(this.fileValue)}),e}},i=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const i=r(50989);t.SettingCategories=(0,i.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const i=r(58587),n=r(51168),s=r(76760),o=r(19851),a=r(40958),l=r(76790),u=r(22573),c=r(42659),d=r(73722),h=r(68708),f=r(50989),m=r(12168),g=r(54993),p=r(37975),y=r(9092),v=r(40583),w=r(79840),S=r(7282),b=r(12801),P=r(4328),_=r(70488),E=r(84248),M=r(5531),C=r(99315),T=r(34365),x=r(34580),D=r(96706),k=r(50274),O=r(33866),I=r(52086),A=r(48584),F=r(45969),N=r(43334),L=r(24540),R=r(70379),j=r(71300),B=r(33209),V=r(48987),z=r(68268),W=r(61208),q=r(99023),U=r(30577),G=r(1485),H=r(19861),J=r(55111),K=r(30933),$=r(22859),Y=r(71988),Z=r(38483),X=r(90536),Q=r(75164),ee=r(10546),te=r(90967),re=r(67958),ie=r(55948),ne=r(57039),se=r(9945),oe=r(74589),ae=r(844),le=r(96093),ue=r(23561),ce=r(69005),de=r(87652),he=r(81075),fe=r(58305),me=r(57571),ge=r(72564),pe=r(80372),ye=r(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new pe.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new pe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new pe.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,p.noColor)()}),logContextLimit:new oe.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new pe.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>G.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:G.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>G.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>N.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new pe.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new pe.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,F.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new ge.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:J.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!N.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new i.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>N.isMac?"100ms":N.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new pe.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:E.AutoVacuumModes,defaultValue:E.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:C.RepairModes,defaultValue:C.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,F.isDocker)()}),skipHealthCheckIds:new ge.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new pe.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>N.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new pe.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:U.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new pe.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new pe.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new pe.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,K.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:k.SidecarExts,defaultValue:k.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new pe.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ie.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:re.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,K.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:I.CropStrategies.attention,strEnum:I.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(N.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:A.SharpFailOns.truncated,strEnum:A.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>V.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:R.DateTagFormats.ym,strEnum:R.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:q.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,F.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,r]of(0,h.entries)(t.Settings))r._setName(e);function be(e){const r=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,F.isDocker)()&&r.unshift("/opt/photostructure/tools/bin"),r.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(r).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,D.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const r of(0,t.persistedSettings)()){for(const t of r.names)e.set(t,r);for(const t of r.keys)e.set(t,r)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,g.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const i=r(19851),n=r(31586),s=r(7282),o=r(49776),a=r(46292),l=r(32774),u=r(55086),c=r(46296),d=r(55939),h=r(96706),f=r(83278),m=r(92234),g=r(45969),p=r(60865),y=r(30933),v=r(15674),w=r(28874);t.setSettingsDefaults=(0,i.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,g.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=p.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const i=r(76760),n=r(40958),s=r(22573),o=r(98553),a=r(55835),l=r(59455),u=r(19851),c=r(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function h(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",i.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const r=t.split("|");for(const t of r)e.set(t,r)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const i=r(40958),n=r(98553),s=r(55835),o=r(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,i.uniq)(e)))),fromEnv:t=>{return r=t,n=e.strEnum,(0,i.compact)((0,o.splitStringArray)(r)?.map((e=>n.getCI(e))));var r,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const i=r(22573),n=r(81168),s=r(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,i.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const i=r(76760),n=r(55835),s=r(46292),o=r(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,i.join)(e,o.SettingsToml)))}},80496:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const i=r(50989);t.TagInferenceSettingValues=(0,i.strEnum)("never","always","auto")},6707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const i=r(90858),n=r(44652),s=r(22573),o=r(76850),a=r(50213),l=r(81168),u=r(84542),c=r(17217),d=r(68284),h=r(98778);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,i.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const i=r(22573),n=r(96249),s=r(98553),o=r(68708),a=r(51926);function l(e,t,r){if((0,i.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,i.blank)(r?.prefix)?[n]:(0,a.wrap)(n.split("\n"),r)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,i.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},65162:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const i=r(4001),n=r(81168);t.bname=function(e,t=!0){let r=(0,n.isString)(e)?e:e.name;return t&&(r=(0,i.stripCopySuffixFromName)(r)),r=(0,n.trimLeftPadding)((0,i.stripDSC)(r)),r.toLowerCase().normalize()}},70379:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const i=r(50989);t.DateTagFormats=(0,i.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},68268:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const i=r(50989);t.KeywordReparentingStrategies=(0,i.strEnum)("move","copy","retain")},61208:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const i=r(50989);t.NameTagFormats=(0,i.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const i=r(50989);t.NameTagOrders=(0,i.strEnum)("western","eastern")},60865:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const i=r(37805),n=r(30577);t.channel=function(){return(0,n.extractUpdateChannel)(i.version)},t.baseVersion=()=>[i.versionMajor,i.versionMinor,i.versionPatch].join("."),t.versionMajorMinor=i.versionMajor+"."+i.versionMinor},30577:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const i=r(50989);t.UpdateChannels=(0,i.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const r of t.UpdateChannels.values)if(e.includes("-"+r))return r;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},1485:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const i=r(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,i.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69375:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const i=r(19851),n=r(22573),s=r(50213),o=r(9103),a=r(7282),l=r(29882),u=r(43334),c=r(28874),d=(0,i.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,g=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function p(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),r=t[0],i=t[t.length-1];return c.Settings.excludedRootDirectories.has(r)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(i)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===r&&!1===m?.test(e)?"LinuxRunRE":!0===g?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=p(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=p},63870:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const i=r(42659),n=r(12168),s=r(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/i.secondMs},55111:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const i=r(50989);t.HelmetPlugins=(0,i.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},30933:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=i(r(48161)),s=r(19851),o=r(42659),a=r(31586),l=r(50213),u=r(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),r=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??r)),meta:{availableParallelism:e,cpuInfoLength:r}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=i(r(48161)),s=r(19851),o=r(31586),a=r(12168),l=r(50213),u=r(45879),c=r(70417),d=r(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),r=(2*e+t)/3;if((0,d.isDocker)()){const i=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(i))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([i,r]),meta:{freemem:e,totalmem:t,cgroupMem:i}})}return h().tap({msg:"estimatedFreeMem() ",result:r,meta:{result:(0,a.fmtBytes)(r),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},15674:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const i=r(19851),n=r(42659),s=r(41400),o=r(31586),a=r(12168),l=r(50213),u=r(7282),c=r(34102),d=r(57902),h=r(28874),f=r(30933),m=r(58444),g=r(22751),p=(0,i.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,i.lazy)((()=>{const e=(0,o.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*a.MB;return p().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,r=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return p().tap({msg:"timeoutPenalization()",level:r>1?d.LogLevels.warn:d.LogLevels.debug,result:r,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,i.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const r=g.timeoutRate.prior()?.eventsPerMinute??0,i=w();if(1!==i){const e=t;t*=i,p().warn("Recent timeouts! Throttling down.",{penalization:i,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),p().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:i,timeoutsPerSecond:r,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,i.lazy)((function(){return(0,o.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const i=r(58587),n=r(87997),s=r(19851),o=r(42659),a=r(41400),l=r(50213),u=r(7282),c=r(45255),d=r(34102),h=r(976),f=r(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new i.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const g=(0,s.lazy)((()=>(0,n.setInterval)(p,o.minuteMs).unref()));function p(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),g()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),p()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const i=r(76790),n=r(22573),s=r(50357),o=r(98553),a=r(49769),l=r(34666),u=r(30976),c=r(42279),d=r(32639),h=r(59455),f=r(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function g(e){return null==e||0===(0,h.toA)(e).length}function p(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,r)=>e===t[r]))}function v(e,t){for(let r=0;r=e.length||r>=e.length)return e;const i=e[t];return e.splice(t,1),e.splice(r,0,i),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&(0,a.getOrSet)(r,e,(()=>i))}return[...r.values()]}function P(e,t,r=1,i=(e=>e)){const n=[];if(et;s-=r)n.push(i(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=g,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,r){return m(e)?t(e):(0,c.tot)(r)},t.toPrimitive=p,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let r=0;rt.includes(e)))},t.includesAll=function(e,t){if(g(e)||g(t))return!1;for(const r of t)if(!e.includes(r))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const r=(0,i.sortBy)(e,p),n=(0,i.sortBy)(t,p);return r.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const r of t)null==r||e.some((e=>(0,s.eql)(e,r)))||e.push(r);return e},t.pushUniqBy=function(e,t,r){const i=e.map(r);for(const n of t){const t=r(n);i.includes(t)||(e.push(n),i.push(t))}return e},t.insertAt=function(e,t,...r){return e.splice(t,0,...r),e},t.insertUniq=function(e,t,r){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let i=0;i0)return e.splice(i,0,t),e}return e.push(t),e},t.remove=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),r!==e.length},t.removeSame=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>e!==t)))),r!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const r of e)null==r||(0,s.eql)(t[t.length-1],r)||t.push(r);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const r=[];for(const e of(0,i.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))r.some((t=>t.includes(e)))||r.push(e);return(0,i.sortBy)(r,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&r.set(e,i)}return[...r.values()]},t.uniqBy2=function(e,t){const r=[];for(const i of e)null!=i&&r.every((e=>!t(i,e)))&&r.push(i);return r},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,r,i)=>e+(t(r,i)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,r,i)=>e+t(r,i)),0)},t.firstMatch=function(e,t){for(const r of S(t)){const t=e.exec(r);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let r=0;for(;e[r]===t[r];)r++;return r},t.anneal=function({array:e,expense:t,allowedDelta:r}){const i=Math.round(r);if(i<2)return e;for(let r=0;re)){return P(e,t,1,r)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,r,i=t.primitiveValueOfOrElse){const n=new Set(r.map(i));return e.filter((e=>!n.has(i(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const i=r(40958),n=r(36783),s=r(41801),o=r(98553),a=r(49769),l=r(55835),u=r(34666),c=r(59455);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const r=new Map;for(const i of e)(0,a.getOrSet)(r,(0,o.stringify)(t(i)),(()=>i));return f(r.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,l.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,i.compact)(e),i.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,r)=>0===r||t>=e[r-1]))},t.sortedBy=function(e,t){return e.every(((r,i)=>0===i||t(r)>=t(e[i-1])))},t.sortBy=f,t.deepSortBy=function e(t,r){return f(t,r).map((t=>(0,s.isIterable)(t)?e(t,r):t))},t.pushSorted=function(e,t,r){const i=e.findIndex((e=>r(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const i=r(32639);t.asPromise=async function(e){const t=await e;return(0,i.isFunction)(t)?t():t}},5233:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const i=r(41400),n=r(31586),s=r(13538),o=r(41583);t.retryOnReject_=async function(e,t){const r=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return r();const a=t.onRetryWaitUntil??(e=>(0,i.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await r()}catch(e){const r=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(r)||l>t.maxRetries)throw r;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},22573:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const i=r(55835),n=r(42279),s=r(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const r=(0,s.toS)(e);return a(r)?t(r):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const r=(0,s.toS)(e).trim();return r.length>0?r:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,r){return(0,i.orElse)(l(e,t),r)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function r(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function i(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const r=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(r)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=r,t.toBoolean=function(e){return!!r(e)||!i(e)&&void 0},t.toNotBoolean=function(e){return!r(e)&&(!!i(e)||void 0)},t.boolToInt=function(e){return r(e)?1:0},t.isFalse=i,t.isDisabled=function(e){return i(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>r(e)))},t.and=function(e){return e.every((e=>r(e)))},t.maybeAnd=function(e){let t;for(const r of e){if(!1===r)return!1;!0===r&&(t=!0)}return t},t.mapBoolean=function(e,t){return r(e)?t(!0):i(e)?t(!1):void 0},t.mapTrue=function(e,t){return r(e)?t():void 0}},79666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const i=r(98553);t.clone=function(e){return null==e?e:JSON.parse((0,i.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const i=r(40958),n=r(22573),s=r(30301),o=r(55835),a=r(31586),l=r(39926),u=r(51926),c=r(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function g(e){return e instanceof Date}function p(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=g,t.thisYear=function(){return(new Date).getFullYear()},t.ago=p,t.hence=function(e,t){return p(-e,t)},t.unixtime=function(e){const r=g(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(r/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,r={includeMs:!0}){const i=Math.floor(e/t.hourMs);e-=i*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(i)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(r.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const r=()=>{const e=t%100;return t=Math.floor(t/100),e},i=10*r(),n=r(),s=r(),o=r(),a=r(),l=r();return new Date(t,l-1,a,o,s,n,i)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,r="ago"){return e<1e3?"just now":(r=(0,n.blank)(r)?"":(0,u.ensurePrefix)(r," "),et.ms<=e)))){const s=Math.floor(e/i.ms);e-=s*i.ms,s>0&&(i.ms>=t.dayMs?r:n).push(s+i.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+r.join("")+((0,i.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=g(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const i=r(38639),n=r(73872);function s(e,t,r){if(null==r||y(e)||y(t))return null;const i=r.get(e)?.get(t);return"boolean"==typeof i?i:null}function o(e,t,r,i){if(null==r||y(e)||y(t))return;let n=r.get(e);null!=n?n.set(t,i):(n=new WeakMap,n.set(t,i),r.set(e,n))}function a(e,t,r,i){if(null!=r?.comparator)return u(e,t,r,i);const n=l(e,t);return null!==n?n:u(e,t,r)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,r,i){r??(r={});const u=!1===r.memoize?void 0:r.memoize??(r.memoize=new WeakMap),d=r?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const r=d(e,t,i);if(!1===r||!0===r)return o(e,t,u,r),r;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,r,i){switch(r){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return g(e,t,["name","message","code"],i);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,i);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,r){return c(h(e),h(t),r)}(e,t,i);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),i);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),i);case"Set":case"Map":return function(e,t,r){if(e.size!==t.size)return!1;if(0===e.size)return!0;const i=[],n=[];return e.forEach((function(e,t){i.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(i.sort(),n.sort(),r)}(e,t,i);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return p(e,t,i)}}(e,t,y,r);return o(e,t,u,v),v}function c(e,t,r){const i=e.length;if(i!==t.length)return!1;if(0===i)return!0;let n=-1;for(;++n{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,r,i=!1;const n=function(){if(i){if(null!=r)throw r;return t}try{return i=!0,t=e()}catch(e){throw r=e,e}};return n.prior=()=>t,n.hasPrior=()=>i,n}},41400:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const i=r(42659),n=r(35556),s=r(31586),o=r(68708);function a(e,t=!0){return new Promise((r=>{if(e<=0)r();else{const s=setTimeout((()=>r()),Math.ceil(e+.5));e>i.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const r=Math.max(1,Math.ceil(t)),s=n.isNode&&r<=1?setImmediate(e):setTimeout(e,r);return n.isBrowser||t<=i.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},50357:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const i=r(12487),n=r(68708),s=r(34666),o=r(32639);function a(e,t){return(0,i.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const r of(0,n.keys)(e))if(!a(e[r],t[r]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,r){if(null==e||null==t)return e===t;if(null!=r){const i=d.get(r);if(null!=i)return i(e,t)??null}for(const r of c){const i=r(e,t);if(null!=i)return i}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(31586),a=r(68708),l=r(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const r=[];for(const t of e)null!=t&&(t instanceof Error?r.push(u(t),c(t),t?.message):r.push((0,l.toS)(t)));return(0,i.uniq)((0,i.compactBlankish)((0,s.flatten)((0,i.compact)(r).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const r=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,i.isEmpty)(r)?["(missing stack)"]:r}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},96249:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const i=r(59455);t.flatten=function(e,t=[]){for(const r of(0,i.toA)(e))if(null!=r)for(const e of(0,i.toA)(r))null!=e&&t.push(e);return t}},57924:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const i=r(40958);function n(e,t){return null==(e=(0,i.uniq)((0,i.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},73722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const i=r(50989);t.FitSizes=(0,i.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,i.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const i=r(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,r){if((0,i.lt0)(t))return[...e].slice(t,r);const n=e[Symbol.iterator]();if((0,i.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,r){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(r))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],r=[];return function e(i,n){if((0,isFunction_1.isFunction)(i))return;let s,o,a,l=toJSON(i);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(i===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let i=0;t.Latch=class{constructor(e=i++){this.id=e,this[r]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},r=Symbol.toStringTag},30301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const i=r(40958),n=r(50357),s=r(31586),o=r(65812);t.lazy=function(e,t){let r,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return r=Date.now(),async function(e,r){if((0,i.isEmpty)(l))return;const s=await e,a=await r;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==r||(0,s.gt0)(t)&&r+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,r){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const i=r();return null!=i&&e.set(t,i),i}},t.deleteIf=function(e,t){for(const[r,i]of e.entries())t(r,i)&&e.delete(r)}},55835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const i=r(42279),n=r(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,r){return null==e||null==t?void 0:r(e,t)}function a(e,t){return null!=e?e:(0,i.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,r,i){return null==e||null==t||null==r?void 0:i(e,t,r)},t.orElse=a,t.mapOr=function(e,t,r){return null!=e?t(e):(0,i.tot)(r)},t.map2Or=function(e,t,r,i){return a(o(e,t,r),i)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const i=r(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,i.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const i=r(40958),n=r(76790),s=r(50357),o=r(98553),a=r(49769),l=r(55835),u=r(51926),c=r(59455);class d{static fromJSON(e){const t=new d;for(const[r,i]of Object.entries(e))t.add(r,...i);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,i.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const r=(0,a.getOrSet)(this.store,e,(()=>[]));return r.push(...t),r}addUniq(e,...t){return(0,i.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const r=this.store.get(e);if(null==r)return!1;{const i=r.filter((e=>!(0,s.eql)(e,t)));return 0===i.length?this.store.delete(e):this.store.set(e,i),r.length!==i.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,i.uniq)(t))){for(const t of this.keys()){const r=this.store.get(t),n=null==r?[]:e(t,r);(0,i.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,i.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield[t,r])}()}tuples(){const e=this;return function*(){for(const[t,r]of e.store.entries())for(const e of(0,c.toA)(r))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[r,n]of this.store.entries()){const s=(0,i.findIndexes)(n,(t=>!e(r,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(r)}return t}inverse(){const e=new d;for(const[t,r]of this.store.entries())for(const i of r)e.add(i,t);return e}findKeyByTuple(e){for(const[t,r]of this.tuples())if(e(t,r))return t}filterKeysByTuple(e){const t=[];for(const[r,i]of this.entries())i.some((t=>e(r,t)))&&t.push(r);return t}toJSON(){const e={};for(const[t,r]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=r;return e}}function h(e,t){const r=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>r.add(t,e))))),r}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const r=h(e,t);return(0,n.sortBy)((0,c.toA)(r.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const r=globalThis;t.isBrowser="object"==typeof r?.window&&"object"==typeof r?.document,t.isNode="string"==typeof r?.process?.versions?.node},31586:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const i=r(76790),n=r(22573),s=r(42279),o=r(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,r)=>a(t)&&a(r)&&e(t,r);function f(e,r,n){return!(null==n||!a(n))&&([e,r]=(0,i.sort)([e,r]),(0,t.lte)(e,n)&&(0,t.gte)(r,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function p(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return p(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const r=Math.pow(10,t);return P(e*r)/r}function E(e,t,r){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${r})`);return a(r)?rt?t:r:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,r=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(r>=1)return!1;const i=(0===t?1e-5:t)*(1-r);return f(t-i,t+i,e)},t.within=f,t.max_=function(...e){let t;for(const r of e)a(r)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const r=y(e);return null==r?void 0:t(r)},t.mapFloat=function(e,t){const r=v(e);return null==r?void 0:t(r)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,r){return b(e,(e=>b(t,(t=>r(e,t)))))},t.mapNumericOr=function(e,t,r){return a(e)?t(e):r},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const r=t-P(Math.ceil(Math.log10(Math.abs(e)))),i=Math.pow(10,Math.abs(r));return r<0?P(e/i)*i:P(e*i)/i},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!w(e))return[];const r=Math.round(e);return r<=0?[]:[...Array(r)].map(((e,r)=>t(r)))},t.pct=function(e,t){return E(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const r=Math.round(e??-1);return null==t||f(0,t,r)?r+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const r of e){if(!a(r))return;t+=r}return t}},68708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(32639),a=r(55835),l=r(31586),u=r(34666),c=r(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function g(e){return h(e).map((t=>e[t]))}function p(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const r of e)if(null!=r&&Array.isArray(r)){const[e,i]=r;null!=e&&void 0!==i&&("object"!=typeof t&&(t={}),t[e]=i)}return t}function v(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>null!=e)))return e;const r=t.filter((([,e])=>null!=e));return(0,i.isEmpty)(r)?void 0:y(r)}function w(e,t,r={}){return y((0,i.compact)((0,n.sort)(h(e)).map((r=>t(r,e[r])))).filter((([e,t])=>null!=e&&void 0!==t)),r)}function S(...e){const t=(0,i.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const r=t.filter(d);if(t.length!==r.length)return t;const n={};for(const e of(0,i.uniq)((0,i.flatMap)(r,h)))n[e]=S(...r.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const r=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(r.test(t))return{key:t,value:e[t]}}function P(e){return g(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const r=v(e);return m(r)?t(r):void 0},t.values=g,t.entries=p,t.fromEntries=y,t.assignFields=function(e,t,r){if(null==t)return e;for(const[i,n]of p(t))!0!==r?.omitKeys?.includes(i)&&(null==n&&!0!==r?.assignNullish||(e[i]=n));return e},t.assignUndefinedFields=function(e,t,...r){if(null==t)return e;for(const i of r){const r=t[i];void 0!==r&&void 0===e[i]&&(e[i]=r)}return e},t.assignAllFields=function(e,t){for(const[r,i]of p(t??{}))e[r]=i;return e},t.definedValues=function(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>void 0!==e)))return e;const r=t.filter((([,e])=>void 0!==e));return(0,i.isEmpty)(r)?void 0:y(r)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,i.compact)(t.map(e));{const r=(0,i.compact)(p(t).map((([t,r])=>(0,a.map)(e(r),(e=>[t,e])))));return 0===r.length?void 0:y(r)}}},t.compactBlankValues=function(e){if(null==e)return;const t=p(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,i.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickCompact=function(e,...t){if(null==e)return;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickNonBlank=function(e,...t){if(null==e)return e;const r={};for(const i of t){const t=e[i];(0,s.notBlank)(t)&&(r[i]=t)}return r},t.pickFirst=function(e,t,r=a.defined){if(null!=e)for(const i of t)if(r(e[i]))return e[i]},t.pickDeep=function e(t,...r){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...r)));const i={};function n(e,t){if(null==t)return;const r=i[e];i[e]=null==r?t:S(r,t)}for(const i of r){const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const i of h(t))((0,l.toInt)(i)??-1)>=0&&n(i,e(t[i],...r));return i},t.pluck=b,t.pluckDeep=function e(t,r){if(null==t||(0,s.blank)(r))return;if(Array.isArray(t)){const n=(0,i.compact)(t.map((t=>e(t,r))));return(0,i.isEmpty)(n)?void 0:{key:n[0].key,value:(0,i.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(r,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const r=p(e).filter((([e])=>!t.includes(e)));return(0,i.isEmpty)(r)?void 0:y(r)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(p(e).filter((([e,r])=>t(e,r))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,i.uniq)(t)},t.maybeCall=function(e,t,...r){const i=e?.[t];return(0,o.isFunction)(i)?i.bind(e)(...r):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const r=t.toLowerCase().normalize();for(const t of h(e))if(r===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const r=w(t,((t,r)=>[t,e(r)])),i=g(r);return 1===i.length?i[0]:r}},97790:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(r||(r={})),t.None=r;class i{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new i(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,r){return s(e).flatMap((e=>s(t).flatMap((t=>r(this.a,e,t)))))}zip3(e,t,r,i){return s(e).flatMap((e=>s(t).flatMap((t=>s(r).flatMap((r=>i(this.a,e,t,r)))))))}}function n(e){return e instanceof i||e===t.None}function s(e){return n(e)?e:null!=e?new i(e):t.None}t.Some=i,t.isOpt=n,t.opt=s},39926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const i=r(31586),n=r(54993),s={};function o(e,t){if(t<1)return"";if(!(0,i.gte)(s[e]?.length,t)){let r=s[e]??e;for(;r.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const i=r(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,i.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const i=r(40958),n=r(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,r){return o(e)?t(e):r()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,r){if(null==e&&null==r)return 0;if(null==e)return-1;if(null==r)return 1;const i=typeof e,s=typeof r;if(!("string"!==i&&"symbol"!==i||"string"!==s&&"symbol"!==s)){const i=(0,n.toS)(e),s=(0,n.toS)(r),o=i.localeCompare(s);return i[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(r)?u(e,r):i!==s?a.indexOf(i)-a.indexOf(s):e>r?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const i=r(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const r=await e;return null==r?void 0:t(r)},t.thenCollect=async function(e,t){const r=[];for(const n of(0,i.toA)(await e))if(null!=n){const e=await n;if(null!=e){const i=await t(e);null!=i&&r.push(i)}}return r},t.thenTap=async function(e,t=console.dir.bind(console)){const r=await e;return await t(r),r},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:r}){const i=await e;return t(i)?r(i):void 0}},57153:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const i=r(50989);t.PromiseStates=(0,i.strEnum)("pending","resolved","rejected")},30976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const i=r(40958),n=r(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,r){return null==r||0===r.length?s(e,t):a(e,t,1,r)[0]}function a(e,t,r,i){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(i??[]);if(t===e&&0===n&&0===o.size&&1===r)return[e];const a=n-o.size;if(r>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:r,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const r=Math.floor(Math.random()*(e+1));e!==r&&([t[e],t[r]]=[t[r],t[e]])}return t},t.sample=function(e,t){const r=[];for(const i of a(0,e.length,t))r.push(e[i]);return r},t.pickWeightedRandom=function(e){if((0,i.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let r=l(0,(0,i.sum)(t,(e=>e.priority)));return t.find((e=>(r-=e.priority,r<=0)))}},5670:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const i=r(50989);t.ServiceNames=(0,i.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const r=e.indexOf(t);return-1===r?[e]:[e.slice(0,r),e.slice(r+t.length)]}},50989:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const i=r(68708),n=r(42279);t.strEnum=function(...e){const t=Object.freeze(e),r=(0,i.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?r[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const r=o(e),i=o(t);return null==r||null==i?void 0:r>i?1:r{const r=o(e);return null==r?void 0:t[r]}}}},51926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const i=r(40958),n=r(17586),s=r(22573),o=r(96249),a=r(41801),l=r(31586),u=r(59455),c=r(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,r){if(d(e))return t<0&&(t+=e.length),e.slice(t,r);{const i=f();return null!=i?(0,a.sliceIterable)(i.segment(e),t,r).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,r).join("")}}function g(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function p(e,t){const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.startsWith(i)?r.slice(i.length):r}function y(e,t){if(null==t)return e;const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.endsWith(i)?r.slice(0,-i.length):r}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,r){null==r&&(r=e.length);for(let i=r;i>=0;i--)if(m(e,i).startsWith(t))return i;return-1}function b(e,t,{normalize:r=!0}={}){if(null==e||null==t)return!1;const i=(0,c.toS)(e),n=(0,c.toS)(t);return i.length===n.length&&(i===n||i.toLowerCase()===n.toLowerCase()||"function"==typeof i.localeCompare&&0===(r?i.normalize():i).localeCompare(r?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,i.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,r){return d(e)?e.slice(t,null==r?void 0:t+r):m(e,t,null==r?void 0:t+r)},t.charArr=g,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=p,t.stripPrefixes=function e(t,r){if(null==t)return"";const i=(0,c.toS)(t);for(const t of r)if(null!=t&&t.length>0&&i.startsWith(t))return e(i.slice(t.length),r);return i},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:r}){return y(p(e,t),r)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:r}){return w(v(e,t),r)},t.ellipsize=function(e,t=80,r=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),r=(0,l.clamp)(0,t-1,(0,l.round)(r));const i=g(e);return i.length<=t?i.join(""):i.slice(0,t-1-r).join("")+"…"+(r>0?i.slice(-r).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,r){const i=r?.maxLineLen??80,n=r?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const i=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(i.map((t=>e(t,r))))}if((t=v((0,c.toS)(t),n).trim()).length<=i)return[t];const s=S(t," ",i);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),r)];{const i=t.indexOf(" ",n.length+1);return i>0&&i{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const i=r(42659),n=r(68708),s=r(42279),o=r(83104),a=r(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,r=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(r,i)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,r(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,r(t))}catch(e){n&&(n=!1,i(e))}finally{clearTimeout(s)}}))}async function c(e,t,r=!0){const n=await u(e,t,r);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,r=!0){return u(e,t,r).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,r=!0){const i=t-Date.now();return i<=0?o.Timeout:u(e,i,r)},t.thenOrOnTimeout=async function(e,t,r){return t<=0?e:new Promise((async(i,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{i(await r())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),i(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,r=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(n)+")");return c(e,n,r)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:r,unref:i=!0}){if(null==e)return(0,s.tot)(r);const n=await u(e,t,i);return n===o.Timeout?(0,s.tot)(r):n}},42279:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const i=r(32639);t.tot=function(e){return(0,i.isFunction)(e)?e():e},t.tol=async function(e){return(0,i.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class r extends Error{}t.TimeoutError=r},12168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const i=r(22573),n=r(30301),s=r(31586),o=r(46891),a=r(50989),l=r(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let r=0;for(const i of e)(0,s.isNumber)(i)&&(r+=i/t.MB);return(0,s.round)(r)},t.fmt=c,t.fmtToInt=function(e){return(0,i.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const r=Math.floor(Math.log10(e)),i=Math.floor(r/3),n=Math.pow(10,3*i),o=d[i];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,r=3){return f(e*t.MB,r)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const r=Math.floor(Math.log2(e)),i=Math.floor(r/10),n=Math.pow(2,10*i),o=h[i];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,r){return null==e?"":(0,i.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(r??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,r){return r??(r=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:r}}},65812:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const i=r(68708);t.setUnrefTimeout=function(e,t){const r=setTimeout(e,t);return(0,i.maybeCall)(r,"unref")??r}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const i=r(41801),n=r(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,i.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const i=r(40958),n=r(23541),s=r(59455),o=r(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,i.compact)((0,s.toA)(e).map(a))}},54993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const i=r(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,i.stringify)(e)}}t.toStr=s},92636:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(6858),s=i(r(73024)),o=i(r(76760)),a=r(1708),l=r(37805),u=r(41269),c=r(80061),d=r(94361);function h(e){for(const t of["bin",__dirname]){const r=o.default.join(t,e);if(s.default.existsSync(r))return r}return console.error("failed to find command "+e),e}n.program.version(l.version),n.program.description("Welcome to PhotoStructure, your new home for all your photos and videos.\nSee https://photostructure.com/server/tools/ for details about these tools."),(0,d.verifyUidGid)(),(0,c.addHelpFooter)(n.program).command("main",u.CliDesc.main+" (default)",{isDefault:!0,executableFile:h("main.js")}).command("info",u.CliDesc.info,{executableFile:h("info.js")}).command("list",u.CliDesc.list,{executableFile:h("list.js")}).command("logcat",u.CliDesc.logcat,{executableFile:h("logcat.js")}).command("logtail",u.CliDesc.logtail,{executableFile:h("logtail.js")}).command("web",u.CliDesc.web,{executableFile:h("web.js")}).command("sync",u.CliDesc.sync,{executableFile:h("sync.js")}).parse(a.argv)},90858:e=>{e.exports=require("@iarna/toml")},58587:e=>{e.exports=require("batch-cluster")},6858:e=>{e.exports=require("commander")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}var __webpack_exports__=__webpack_require__(92636);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={37975:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const i=r(1708),n=r(22573),s=r(38639);function o(){return(0,s.toNotBoolean)(i.env.PS_LOG_COLOR)??(!(0,n.blank)(i.env.NO_COLOR)||["dumb","unknown"].includes(i.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(r){return l()?`[${e}m${r}[${t}m`:r}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const i=r(19851),n=r(7282),s=r(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,i.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,i.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const i=r(40958),n=r(36783),s=r(76790),o=r(22573),a=r(50357),l=r(98553),u=r(55835),c=r(31586),d=r(68708),h=r(34666),f=r(59455),m=r(84885);var g=r(40958);function p(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,r=i.primitiveValueOfOrElse){const n=new Set(t.map(r));return e.filter((e=>n.has(r(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],r=e.lastIndexOf(t);return[{t,count:r+1},...v(e.slice(r+1))]}function w(...e){const t=[],r=Math.max(...e.map((e=>e?.length??0)));for(let i=0;ie?.[i])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function E(e,t){return(0,i.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,r){return C(e,t,r).index}function C(e,t,r){if((0,i.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let i=0;ie.slice(r,r+t)))}async function x(e,t){return(0,i.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return g.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return g.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return g.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=p,t.mapAllDefined=function(e,t){return p(e)?t(e):void 0},t.mapAll=function(e,t){return p(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const r of(0,f.toA)(e))if(null!=r&&!0===await t(r))return r},t.findLastAsync=async function(e,t){for(let r=(e=(0,f.toA)(e)).length-1;r>=0;r--){const i=e[r];if(null!=i&&!0===await t(i))return i}},t.first=function(e,t){if(null!=e)for(const r of(0,f.toA)(e))if(null!=r){const e=t(r);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null!=i){const e=await t(i,r);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,i.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,r){for(let i=r;i<=e.length-1;i++)if(t(e[i]))return i},t.findLast=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},t.findLastIndex=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},t.concat=function(...e){const t=[];for(const r of e)if(Array.isArray(r))for(const e of r)null!=e&&t.push(e);else null!=r&&t.push(r);return t},t.moveToEnd=function(e,t){return(0,i.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const r=e[t];if(null==r)return e;e.push(r);for(let r=t;r(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const r=e.findIndex(t);return r>=0?e.splice(r,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,i.uniqBy)(e,t),e)},t.partition=function(e,t){const r=[],i=[];let n=0;for(const s of e)(t(s,n++)?r:i).push(s);return[r,i]},t.isUniq=function(e){return e.every(((t,r)=>e.indexOf(t)===r))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,i.compact)((0,i.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),r=[];return(0,c.times)(t,(t=>e.map((e=>r.push(e?.[t]))))),r},t.unFlatZip=function(e,t){const r=e.length/t;if(r!==Math.round(r))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const i=(0,c.times)(t,(()=>new Array(r)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=E,t.least=function(e){return E(e,(e=>e))},t.greatestBy=function(e,t){return(0,i.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const r=C(e??[],t,h.lt);return null==e||null==r||r.index<0||null==r.value?void 0:{result:e[r.index],index:r.index,value:r.value}},t.reverse=function(e){const t=[];for(let r=e.length-1;r>=0;r--)t.push(e[r]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(r(s)));return n},t.collectBatchedAsync=async function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(await r(s)));return n},t.contextFilter=function(e,t){let r;return e.filter(((e,i)=>(0,d.tap)(t(e,i,r),(t=>{t&&(r=e)}))))},t.clusterSome=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.some((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterEvery=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.every((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterAsync=async function(e,t){const r=[];e:for(const i of e){for(const e of r)if(null!=i&&await x(e,(e=>t(i,e)))){e.push(i);continue e}null!=i&&r.push([i])}return r},t.someAsync=async function(e,t){if(null!=e)for(let r=0;r=0&&!0===(0,u.map)(e[i],(e=>r(e,i))))return i}{const i=t+n;if(ie+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,r){return e.lengthr))),e}},36557:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=r(77988),l=o(r(1708)),u=r(19851),c=r(42659),d=r(55835),h=r(31586),f=r(85556),m=r(54993),g=r(50213),p=r(79089),y=r(45255),v=r(25764),w=r(38836),S=r(99331),b=r(95937),P=r(98314),_=r(38835),E=r(70025),M=r(8769),C=r(43334),T=r(95402),x=r(28874),D=r(63870);class k extends w.EndableWrapper{constructor(e,t,r=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,i,"m",n).call(this)),r,"worker"===e?(0,D.commandTimeoutMs)():y.ShortCommandTimeoutMs),i.add(this),this.t=t;const o=t;o.on("childStart",(async r=>{null!=r.pid?(this.logger.info("Started child process",{pid:r.pid}),(0,p.renice)(r.pid).catch((e=>this.onError("renice failed",e))),(0,T.addPid)({pid:r.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,r,i)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&T.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,E.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=k,i=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(C.isWin?3:1)*c.minuteMs,maxTasksPerProcess:x.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:x.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:x.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,g.mkLogger)(t))),spawnTimeoutMillis:(0,D.commandTimeoutMs)(),taskTimeoutMillis:x.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=r(92460),d=r(31586);class h{constructor(e){if(i.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,r;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,i,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,r;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,i,"m",a).call(this,0,(e=>{var t,r;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(r=u(this,s,"f"),--r),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,i,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const r=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=r}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const i=r(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:r}of n)if(o(e,t))return e.subarray(t.length).toString(r);return e.toString()}function o(e,t){return t.every(((t,r)=>e[r]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,i.toS)(e)},t.bufferStartsWith=o},9092:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,r]of e)this.set(t,r)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const r=this.normalizer(e);return null!=e&&null!=r&&this.store.set(r,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=r(40958),a=r(23838),l=s(r(68708)),u=r(59455),c=r(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const r of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(r,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const r=this.lookup(e);if(null!=r)return r;let i,n=-1;for(const[r,s]of this.m.entries()){const o=(0,c.diceCoeff)(r,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(i=e,n=o)}}return i}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),r=this.m.get(t);if(null!=r){for(const e of r)delete this.obj[e];this.m.delete(t)}return r}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const i=r(76790),n=r(31586),s=r(68708),o=r(54993),a=r(82647),l=r(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const r=this.get(e)+t;return 0===r?this.m.delete(e):this.m.set(e,r),r}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,r]of this.m.entries())e[(0,o.toS)(t)]=r;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,i.sortBy)([...this.entries()],(([t,r])=>[-r,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,r]of(0,i.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,r);return e}addAll(e){for(const[t,r]of e.entries())this.incr(t,r);return this}get toS(){return(0,i.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let r=0;for(const[i,n]of this.m.entries()){const s=e(i);t.fill(s,r,r+n),r+=n}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const i=r(19851),n=r(72993),s=r(45969),o=r(43334);t.EditionType=(0,i.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,i.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const i=r(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),r=t-this.ts;this.ts=t,(0,i.map)(this.listener,(t=>t(e,r))),r>2&&this.l.log(r>500?"warn":r>100?"info":"debug",e,{elapsedMs:r})}},t.elapsed=function(e){const t=Date.now(),r=e();return{elapsedMs:Date.now()-t,result:r}},t.thenElapsed=async function(e){const t=Date.now(),r=await e;return{elapsedMs:Date.now()-t,result:r}}},23467:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const i=r(50357),n=r(55835),s=r(68708);var o=r(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,i.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,i.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,i.eql,(()=>!1))},t.eqlPicked=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))},t.eqlOmit=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.omit)(e,...r),(0,s.omit)(t,...r))},t.eqlAsyncPicked=async function(e,t,...r){return(0,n.map2Or)(await e,await t,((e,t)=>(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))),(()=>!1))}},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(31586),a=r(54993),l=r(77377),u=r(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const r of this.expireListeners)r(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[i.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const r of this.expireListeners)r(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const r of this.expireListeners)r(e,t)}const r=this.priorCache[e];if(void 0!==r&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,r)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const r=this.currentCache[t]??this.priorCache[t];null!=r&&e(t,r)}}deleteIf(e){for(const t of this.keys()){const r=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=r&&e(t,r)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const r=t();return this.set(e,r),r}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=r(31586),d=r(85556),h=r(54993),f=r(54557),m=r(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,i.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,i,l(this,i,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,i,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,r,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(r=l(this,n,"f"),++r),"f"),c.promise):(u(this,i,(o=l(this,i,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,i,(a=l(this,i,"f"),++a),"f"),c}get(e){var t,r;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,i,(r=l(this,i,"f"),++r),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,i,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const r=this.get(e);if(null!=r){if(r instanceof Error)throw r;return r}return this.set(e,t())}getOrSetAsync(e,t){const r=(0,h.toS)(e);{const e=this.get_(r);if(null!=e)return e instanceof m.Deferred?e.promise:e}const i=new m.Deferred(this.opts.name).observe(t());return this.cache.set(r,i),(0,c.gt0)(this.opts.timeoutMs)&&i.setTimeout(this.opts.timeoutMs),i.promise.then((e=>{this.set(r,e)}),(e=>{var t,i;this.cache.set(r,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(i=l(this,a,"f"),++i),"f")})),i.promise}},i=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class i{constructor(e){this.maxSize=e,this[r]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(r=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=i},53507:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(31586),a=r(68708),l=r(50213),u=r(68852),c=r(81168),d=r(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,i.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,r=!0){return new m(e,t,r).entries};class m{constructor(e,t,r=!0){this.warnIfMissingHeaders=r,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const i=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,i).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let r=e;r!==t;t>e?r++:r--)if(this.blankColumns.has(r))return r;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),r=[];let i,a=0;for(;null!=(i=t.exec(this.headerRow));){const l=this.headerRow.substring(a,i.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:i.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(i.index,t.lastIndex),d=i.index+((0,c.indexOfNonSpace)(u)??0),h=i.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),g=e.find((e=>e.text===m));if(null==g||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:i,left:d,right:h});else{const e=(0,n.last)(r);if(r.push(g),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=g.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,i.index-((0,c.lastIndexOfNonSpace)(l)??l.length));g.leftIdx=g.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),g.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(r);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),r}}t.Fixed=m},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const i=r(51455),n=r(98553);var s=r(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const r=(0,n.parseJSON)(e);return null==r?void 0:t(r)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,i.readFile)(e)).toString())}},19851:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=r(57975),a=r(40958),l=r(50357),u=r(31586),c=r(65812),d=r(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),i.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,i,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const r=await e,i=await t;if(!(0,l.eql)(r,i))for(const e of this.watchers)e(i);null!=this.ttlMs&&this.ttlMs>0&&void 0!==i&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(42659),a=r(50213),l=r(81168),u=r(5916),c=r(56519),d=r(84777),h=r(44198),f=r(6012),m=r(43334),g=r(24399),p=r(63870);t.DefaultLocale="en";const y=(0,i.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?E():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,p.commandTimeoutMs)()}),t.envLocale=(0,i.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const r=w.exec(e.trim())?.groups;return null==r?void 0:(0,n.compact)([r.lang,r.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(g.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function E(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=E,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},50213:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const i=r(19851),n=r(32105),s=r(14593);t.rootLoggers=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},9103:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const i=r(98553),n=r(54557);t.memoize=function(e,t){let r=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return r++,s.getOrSet((0,i.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,i.stringify)(e)),o.size=()=>s.size,o.callCount=()=>r,o}},7282:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=i(r(1708)),s=r(38639),o=r(54993),a=r(19851),l=r(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(55835),a=r(31586),l=r(39926),u=r(54993),c=r(20014);var d=r(31586);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,r){return(0,o.orElse)(h(e,t),r)},t.mapGte0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>=0?t(r):void 0},t.mapGt0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>0?t(r):void 0},t.mapGt0=function(e,t){const r=(0,a.toInt)(e);return null!=r&&r>0?t(r):void 0},t.map2Gt0=function(e,t,r){const i=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=i&&i>0&&null!=n&&n>0?r(i,n):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(f.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(m(e))}function p(e,t){if(null==e||null==t)return;const r=[e,t].map((e=>e.toString(2))),i=Math.max(...r.map((e=>e.length)));return r.map((e=>(0,l.leftPad)(e,i,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let r=0;for(let i=0;ie/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,r){this.store[e*this.columns+t]=r}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(p(e,t),(([e,t])=>(0,i.count)([...e],((e,r)=>e!==t.charAt(r)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(p(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,i.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,r){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let i=0;const n=r*e.length;for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const i=r(40958),n=r(42659),s=r(96249),o=r(55835),a=r(31586),l=r(68708),u=r(34666),c=r(41583),d=r(48884),h=r(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const r={};for(const[i,n]of(0,l.entries)(e)){const e=t(i,n);null!=e&&(r[i]=e)}return r}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const r of e){const e=r();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(r=>t(r,e[r])?e[r]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,r){if(null!=e)return t(e);throw new Error(r)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,i.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[r,i]of m(t))null==e[r]&&(e[r]=i);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[r,i]of(0,l.entries)(t))null==e[r]&&(e[r]=i);return e},t.pickMap=function(e,t,r){const i={};for(const n of t)i[n]=r(n,e[n]);return i},t.mapEntries=g,t.mapNullEntries=function(e,t,r){const i={};let n=0;for(const s of(0,l.keys)(e))if(i[s]=t(s,e[s]),n++,(0,a.gt)(n,r))break;return i},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const r={};for(const i of(0,h.sortIgnoreCase)((0,l.keys)(t)))r[i]=e(t[i]);return r}return t},t.deepDelete=function e(t,...r){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...r))):g(t,((t,i)=>r.includes(t)?void 0:e(i,...r)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const r of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[r])return e[r]}},t.pairToObject=function(e,t){const r={};return r[e]=t,r},t.zipPojos=function(...e){const t={};for(const r of(0,i.uniq)((0,s.flatten)(e.map(l.keys))))t[r]=e.map((e=>e?.[r]));return t}},12801:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=i(r(48161)),s=r(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const i=r(41400),n=r(56409),s=r(31586),o=r(22911),a=r(73614),l=r(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:r,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const g=[];function p(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...i){f=!0,m=Date.now()+(0,s.max_)(t,r);const n=d=new o.Deferred(c);(0,s.gt0)(r)&&n.setTimeout(r);try{n.resolve(await e(...i))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),g.forEach((e=>e.resolve())),g.length=0}return n.promise}const w=(...e)=>{if(p()){if(!0===u)return null;const t=d?.promise;return h=e,(0,i.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return g.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>p(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const i=r(68708),n=r(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const r=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:r.push((0,i.pick)(n,"index","groups"));return r},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,r){const i=[];for(const t of e)try{i.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{i.push(s(t))}const n=0===i.length?t.NothingRegExp:i.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,r)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let r="",i=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(r+=t.source,i||(i=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):r+=s((0,n.toS)(t));return new RegExp(r,t??(i?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=i(r(48161)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(42659),u=r(41400),c=r(96249),d=r(31586),h=r(51926),f=r(54993),m=r(50213),g=r(12801),p=r(22277),y=r(84777),v=r(34102),w=r(43334),S=r(24399),b=r(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let E=!0;const M=(0,o.lazy)((()=>new p.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const r=(0,g.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=g.PriorityClassToNode[r]),E)try{return n.default.setPriority(e,t),t}catch(r){const i=-13===r?.errno||"EACCES"===r?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:i,error:r}),i)return;E=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&g.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,r):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,g.PriorityClassToPosix[r]??g.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+r),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=i(r(1708)),s=r(19851),o=r(40958),a=r(5670),l=r(54993),u=r(7282),c=r(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function g(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=g,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||g())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||g())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const i=r(59455);function n(e){return e instanceof Set?e:new Set((0,i.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,i.toA)(e.keys()).every((e=>t.has(e)))&&(0,i.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,r){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),r())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const r=n(t);return new Set([...e].filter((e=>r.has(e))))},t.diff=function(e,t){const r=n(t);return new Set([...e].filter((e=>!r.has(e))))}},12089:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=r(98553),d=r(34666),h=r(54993),f=r(62344),m=r(56038);t.shim1=function(e){return new g(e.name,e.impl,e.cache,e.toKey)};class g extends f.ExtensibleFunction{constructor(e,t,r,o){super(),i.add(this),this.impl=t,this.cache=r,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,i,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,i,"m",o).call(this,e),(()=>u(this,i,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,i,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,i=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const i=r(42659);t.ShortCommandTimeoutMs=7*i.secondMs},92322:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=r(76790),o=r(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,i.set(this,[])}[(i=new WeakMap,Symbol.iterator)](){return n(this,i,"f")[Symbol.iterator]()}get length(){return n(this,i,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,r=n(this,i,"f").length-1;for(;t<=r;){const s=t+Math.floor((r-t)/2),o=this.valueOf(n(this,i,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:r=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,i,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:r}){if(t>=this.length)return[...n(this,i,"f")];const o=t=>t<0||t>n(this,i,"f").length-1?null:(r??this.diff)(n(this,i,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return n(this,i,"f").shift()}at(e){return(0,o.at)(n(this,i,"f"),e)}toA(){return[...n(this,i,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,i,"f").length-1){const e=[...n(this,i,"f")];return n(this,i,"f").length=0,e}return n(this,i,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,i,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},82328:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const i=r(1708),n=r(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(i.stdout)}},71567:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=i(r(1708)),s=r(22573),o=r(98553),a=r(23560),l=r(82328),u=r(38835),c=r(70025),d=r(95705);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:r,stream:i}){if(null==i||(0,d.streamEnded)(i))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);i.write(n+"\n"),(0,a.isWorkerService)()&&null!=r&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?i.write(u.FailStr+"\n"):i.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const r of e)r.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(55835),a=r(31586),l=r(39926),u=r(34666),c=r(51926),d=r(59455),h=r(54993),f=r(48884),m=r(68852),g=r(38835);var p=r(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return p.splitFirst}});var y=r(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=r(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,r){if(0===r.length)throw new Error("rightPad() given empty pad");const i=String(e);return i+(0,l.padding)(r,t-i.length)},t.padReplace=function(e,t,r,i){return(0,c.strslice)(e,0,t)+(0,l.padding)(i,r)+(0,c.strslice)(e,t+r)},t.contains=function(e,t,r){return(0,h.toS)(e).indexOf((0,h.toS)(t),r)>-1},t.countChars=function e(t,r,i=0){if(null==r||0===r.length)return 0;const n=t.indexOf(r,i);return-1===n?0:1+e(t,r,n+r.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,r){const i=Math.min(Math.ceil(e.length/t),r??e.length)-1;return i<=0?[e]:[...(0,a.times)(i,(r=>e.slice(r*t,(r+1)*t))),e.slice(i*t)]},t.spliceCapture=function(e,t){const r=t.exec(e);if(null==r||null==r[1])return;const i=r[0].indexOf(r[1])+r.index;return{captured:r[1],uncaptured:e.substring(0,i)+e.substring(i+r[1].length),unmatched:e.substring(0,r.index)+e.substring(r.index+r[0].length),matchedIndex:i}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,r={}){if(null==t)return e;const i=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(i.slice(-n.length),n,r)?i.slice(0,-n.length):i},t.gist=function(e,t=80,r=80){const i=(0,h.toS)(e),n=i.length-(t+r);return n<=0?i:i.slice(0,t).trim()+" …(+"+n+" chars)…"+i.slice(-r).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const r=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===r?e.localeCompare(t):r}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,i.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,o.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const r=S(e.cmp[0],t.cmp[0]);return 0!==r?r:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,i.isEmpty)(e)||(0,s.blank)(t))return;for(const r of e)if((0,c.equalsIgnoreCase)(r,t))return{index:0,match:r};for(const r of e){const e=t.indexOf(r);if(e>=0)return{index:e,match:r}}const r=t.normalize();for(const t of e){{const e=r.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=r.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=r.toLowerCase(),i=e.toLowerCase(),n=t.indexOf(i);if(n>=0)return{index:n,match:i}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function E(e){return _.reduce(((e,[t,r])=>e.replace(t,r)),e).normalize()}t.dumbquote=E;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(E(e))&&(e=e.slice(1,-1).trim())),e};const C=/^['‘’].*['‘’]$/,T=/^["“”„«»〃].*["“”„«»〃]$/;function x(e,t){const r=D(e,t);return(0,f.flatZip)(r.nonSeparators,r.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+g.NonRetriableErrorFlag);const r=[],i=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,r.push(e.substring(s,n.index)),i.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),C.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const r=(0,i.compactBlanks)(e),n=Math.max(...r.map((e=>e.length)));for(let e=0;e(0,o.map)(r[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,i.compactBlanks)(e)),r=t.filter(((e,r)=>!P(t[r+1],e)));return(0,n.sortBy)(r,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const r=Math.min(e.length,t.length);for(let i=0;i4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const r=new Set;for(const i of(0,d.toA)(e))if(null!=i&&!(0,s.blank)(i))for(const e of i.split(t))(0,s.blank)(e)||r.add(e);return[...r].join(t)},t.dedupeNeedle=function(e,t,r){if((0,s.blank)(t))return e;const i=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>i.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(r)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const i=r(54993);function n(e){return(0,i.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>"_"+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>" "+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=i(r(77598)),s=r(73913),o=r(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,r=o.Radix58,i=224){return r.encodeBuffer(a(e,i)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,r=o.GeoRadix,i=224){return l(e,t,r,i)}},94863:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const i=r(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,i.toS)(e).toLowerCase().normalize()}},96859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(31586),a=r(39926),l=r(51926),u=r(54993),c=r(55222),d=r(97352),h=r(88158),f=r(77377),m=r(81168);function g(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const r=new d.Array2D(e.length);let i=0,n="";for(let s=0;s=i&&(i=r.get(s,o),n=(0,l.substr)(e,s-i+1,i)));return n}function p(e,t){if(null==e||null==t)return;if(e===t)return 0;const r=y(e,t);if(null!=r)return r;const i=e.normalize(),n=t.normalize();return e!==i||t!==n?y(i,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,r,i)=>r===t.charAt(i)?e:e+1),0)}function v(e,t){const r=e.toUpperCase().normalize(),i=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>r===i?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(r),t=w(i);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,r)=>e+t[r+1]))}function S(e,t){const r=(0,f.intersection)(e,t),n=[];return r.forEach((r=>{const s=Math.min((0,i.count)(e,(e=>e===r)),(0,i.count)(t,(e=>e===r)));(0,o.times)(s,(()=>n.push(r)))})),n}function b(e,t,r){const n=(0,i.commonPrefixLength)(e,t);return r((0,l.strslice)(e,n))-r((0,l.strslice)(t,n))}function P(e){const t=(0,i.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[r,i]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(r,i,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:g(e,t).length/Math.max(e.length,t.length)},t.lcs=g,t.hamming=p,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const E=/[^\da-z]+/gi;function M(e,t){const[r,i]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(E,"").toLowerCase()));return b(r,i,(e=>c.RadixAlphaNum.decode(e)))}function C(e,t){let r;for(let i=Math.max(e.length,t.length);i>=0;i--){const n=(0,o.mapNumericOr)(e.charCodeAt(i),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(i),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);r=null==r?a:(r+a)/2}return r}t.radixDiff=M,t.str=function(e,t){return{pref:(0,i.commonPrefixLength)(e,t),ham:p(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,i.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=C,t.paddedPositionalDiff=function(e,t,r=8){return C((0,a.leftPad)(e,r," "),(0,a.leftPad)(t,r," "))}},84885:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const i=r(98553),n=r(88158);t.stringifySorted=function(e){return(0,i.stringify)((0,n.sortedKeys)(e))}},22277:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=r(73614);class u{constructor(e,t=!1){i.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,i,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,i,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const r=this.delegate.get(e);return null==r||a(this,i,"m",n).call(this,e,r)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,r]of this.delegate)a(this,i,"m",n).call(this,t,r)||e(t,t,this)}has(e){return null!=e&&!a(this,i,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield[t,t])}()}toA(){return a(this,i,"m",s).call(this),[...this.delegate.keys()]}[(i=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const r=t<=Date.now()-this.ttlMs;if(r){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return r},s=function(){for(const[e,t]of this.delegate)a(this,i,"m",n).call(this,e,t)}},94174:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(38639),c=r(31586),d=r(50213),h=r(45255),f=r(84777),m=r(96706),g=r(43334),p=r(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>g.isWin?p.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>g.isWin?g.isWin?p.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const i=r(42659),n=r(55835),s=r(31586),o=r(97790),a=r(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const r=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(r))return;const[o,a,u,c,d,h,f]=r,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*i.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+i.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class r extends Error{}t.AbortError=r},76740:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=r(45599),l=r(56409),u=r(73568);t.Abortable=class{constructor(){this._aborted=!1,i.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,i,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,i,"f")&&clearTimeout(s(this,i,"f")),o(this,i,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},i=new WeakMap,n=new WeakMap},22911:function(e,t,r){var i,n,s,o,a,l,u,c,d,h,f,m,g=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(r(87997)),w=y(r(57975)),S=r(45599),b=r(26905),P=r(55835),_=r(31586),E=r(68708),M=r(20214),C=r(57153),T=r(85556),x=r(50213),D=r(70025),k=r(95937),O="TIMEOUT",I=(0,S.defer)((()=>(0,x.mkLogger)("async.Deferred")));class A{static async*toAsyncIterable(e,t){const r=[...e].reverse(),i=(0,_.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=i&&r.push(i);;){for(let i=r.length-1;i>=0;i--){const n=r[i];if(n.isSettled){if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});r.splice(i,1),yield n.value}}if(r.every((e=>e.name===O)))break;try{await Promise.race(r)}catch{}}i?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var r,m,y;i.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,C.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(p(r=n,n,(y=g(r,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{p(this,u,e,"f"),p(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return g(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:g(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,E.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return g(this,o,"f")}get elapsedMs(){return(g(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,i=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=g(this,h,"f")&&(v.default.clearTimeout(g(this,h,"f")),p(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(p(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),g(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return g(this,a,"f")===C.PromiseStates.pending}get value(){return this.isResolved?g(this,l,"f"):void 0}get error(){return g(this,d,"f")}get isSettled(){return g(this,a,"f")!==C.PromiseStates.pending}get isResolved(){return g(this,a,"f")===C.PromiseStates.resolved}get isRejected(){return g(this,a,"f")===C.PromiseStates.rejected}get settledMs(){return null==g(this,o,"f")?void 0:g(this,o,"f")-this.startedAt}resolve(e){return g(this,i,"m",m).call(this,(()=>{p(this,a,C.PromiseStates.resolved,"f"),p(this,l,e,"f"),g(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return g(this,i,"m",m).call(this,(()=>{p(this,d,t,"f"),p(this,a,C.PromiseStates.rejected,"f"),g(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=A,n=A,m=function(e){if(g(this,a,"f")===C.PromiseStates.pending){(0,P.map)(g(this,h,"f"),v.default.clearTimeout),e(),p(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:g(this,l,"f")});return this},s={value:0}},27395:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const i=r(19851),n=r(40958),s=r(42659),o=r(23838),a=r(13538),l=r(50213),u=r(7282),c=r(97352),d=r(77740),h=r(25764),f=r(99331),m=r(73614),g=(0,i.lazy)((()=>(0,l.mkLogger)("async.Endable"))),p=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const r=await e;if(null==r||!0===r?.ended)return;const i=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,r.endTimeoutMs,y);g().trace(r.name+" ending...",{timeoutMs:i});try{await(0,a.thenOrTimeoutError)(r.end(),i,(0,u.isTest)())}catch(e){try{g().warn(r.name+".end() failed",e)}catch{}}}function w(){p.filterInPlace(((e,t)=>!0!==t.ended)),g().debug("vacuumEndables()",p.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),p.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,i.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;g().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const r=p.get(t)??[];(0,n.isNotEmpty)(r)&&(g().debug("endEndables(): ending "+t),await Promise.allSettled(r.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,n.compact)(p.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const r=p.get(t)??[];e[t]=r.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,r){var i,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=r(87997),h=r(55835),f=r(31586),m=r(68708),g=r(25764),p=r(38836),y=r(99331);class v extends p.EndableWrapper{constructor(e){super(e.name,(()=>u(this,i,"m",o).call(this)),e.rank??g.EndableRanks.first,e.endTimeoutMs),i.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,r=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!r&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,i,"m",o).call(this);const h=()=>{u(this,i,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,i,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,i=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const i=r(50989);t.EndableRanks=(0,i.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=r(19851),l=r(45599),u=r(56409),c=r(50213),d=r(27395),h=r(25764),f=r(99331),m=r(56519);t.EndableWrapper=class{constructor(e,t,r=h.EndableRanks.first,o){this.endTimeoutMs=o,i.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(r,this)}setName(e){o(this,i,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,i,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},i=new WeakMap,n=new WeakMap},99331:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const i=r(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,i.isTest)()?e:e||n}},45608:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=i(r(1708)),s=r(22573),o=r(45599),a=r(37975),l=r(50213),u=r(71567),c=r(57159),d=r(57902),h=r(28874),f=r(27395),m=r(99331),g=r(56038),p=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(g.PromiseTimer.instance().report())}));async function v(e){p().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const r=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==r.errno||!0===r.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const i=(0,s.toNotBlank)(e?.reason)??r.toString();for(const e of t.onFatalHandlers)await e(i)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(r=>{v({reason:`${e}:${t}`,status:0,error:r})}))}))},5916:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=r(45599),f=r(50357),m=r(31586),g=r(41583),p=r(62344),y=r(50213),v=r(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:r,timeoutMs:i}){return new S(e,t,r,i)};class S extends p.ExtensibleFunction{constructor(e,t,r,l){super(),i.add(this),this.later=e,this.desc=t,this.ttlMs=r,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,i,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,i,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,i,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=async function(e,t){var r;try{const r=await t;if(!(0,f.eql)(e?.value??await(e?.promise),r))for(const e of c(this,a,"f"))await e.onChange(r)}catch(e){const t=(0,g.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(r=c(this,s,"f"),++r),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,i,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},56519:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const i=r(40958),n=r(76790),s=r(38639),o=r(42659),a=r(41400),l=r(31586),u=r(20214),c=r(13538),d=r(42279),h=r(32639),f=r(59455),m=r(41583),g=r(48884),p=r(50213),y=r(88158),v=r(15674),w=r(42638);var S=r(20214);async function b(e){if(null==e)return[];const t=(0,i.compact)(await e);return(0,i.isEmpty)(t)?[]:(0,i.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:r,timeoutMs:n}){const s=[];for(const o of(0,i.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(r(o),n):r(o));null!=e&&s.push([e,o])}catch(t){(0,p.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:r,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,i.compact)(await e);if((0,i.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:r,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(r,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(r,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,p.mkLogger)(r).warn("failed to apply",{ea:e,error:t})}})));return(0,i.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,r){const i=[];for(const n of(0,g.batches)((0,f.toA)(await e),t)){const e=await b(n);i.push(...await b(r(e)))}return i},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const r of(0,i.compact)(e)){const e=await r();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;if(null!=e)if(Array.isArray(e))for(const r of e){const e=await r;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;null!=e&&t.push(e)}return(0,i.uniq)(t)},t.asyncFind=async function(e,t){for(const r of e)if(await t(r))return r},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:r,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,i.compact)(t),f:r,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const r=await E({name:"partitionAsync",arr:e,f:t});return[r.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),r.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,r=(e=>console.error(e)),i=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,i)}catch(e){r((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),r=(()=>{})){let i,n=null;try{i=await((0,h.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await r(n??i)}catch{}if(null!=n)throw n;return i},t.thenNot=async function(e,t=!0){if(null==e)return t;const r=await e;return null==r?t:!(0,s.isTrue)(r)},t.thenMap2=async function(e,t,r){const i=await e;if(null==i)return;const n=await t;return null!=n?r(i,n):void 0},t.thenMapOr=async function(e,t,r){const i=await e;if(null==i)return r();const n=await t(i);return null==n?r():n},t.thenMap2Or=async function(e,t,r,i){const n=await e;if(null==n)return i();const s=await t;if(null==s)return i();const o=await r(n,s);return null==o?i():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null==i)continue;const e=await t(i,r);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const r of e){const e=await r();if(null!=e){const r=await t(e);if(null!=r)return r}}},t.firstResolvedDefinedPromise=async function(e,t){for(const r of e)try{const e=await r();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const r of t)try{const t=await r();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:r}){const i=await E({name:e,arr:t,f:r});return(0,n.sortBy)(i,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const i=r(19851),n=r(40958),s=r(76790),o=r(42659),a=r(49769),l=r(31586),u=r(68708),c=r(42279),d=r(41583),h=r(22454),f=r(14121),m=r(50213),g=r(7282),p=r(34102),y=r(82647),v=r(25764),w=r(38836),S=r(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,r){const i=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-i)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-i;return r?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),r?.((0,d.toErr)(t),Date.now()-i),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),r=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),i=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",r.stats()],...i])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:r.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:(0,l.mapFinite)(r.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:r.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:{sumSec:(0,l.sigFigs)(r.sum/o.secondMs,3),...(0,u.omit)(r.stats(),"sum")}})),{})}}function _(e,t,r){return P.instance().time(e,t,r)}function E(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,i.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.isTest)()&&(0,p.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const r=Date.now(),i=t();return E(e,Date.now()-r),i},t.pushTime=E,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,r){return(0,i.lazy)((async()=>_(e,t)),r)}},42638:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(r(66261)),m=r(40958),g=r(55835),p=r(31586),y=r(42279),v=r(54993),w=r(89788),S=r(82647),b=r(15674),P=r(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){i.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,p.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:r,serialId:n}){const s=d(this,i,"m",l).call(this,{name:e,l:t,payload:r,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const r=t.map((t=>d(this,i,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(r)}serial(e,t,r){return this.enqueue({name:e,l:t,serialId:e,payload:r})}push(e,t,r){return d(this,i,"m",u).call(this,new P.Deferred(e,{payload:r}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),r=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,p.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=function({name:e,l:t,payload:r,serialId:i}){const n=new P.Deferred(e,{payload:r,serialId:i});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const r=Date.now();return this.lastWorkTs=r,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-r),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const r=new _(e);return()=>r.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:r}){return new _(e,(0,g.map)(r,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class r extends Error{}t.RedoableError=r},4867:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const i=r(40958),n=r(34546),s=r(41400),o=r(31586),a=r(83104),l=r(85556),u=r(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:r}){let a=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,r?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:r}){let l=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,r?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let r=e=>null;t.setTimeoutHandler=function(e){r=e},t.onTimeout=function({soft:e}={}){r(e)}},73614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const i=r(87997);t.setUnrefTimeout=function(e,t,...r){return(0,i.setTimeout)(e,Math.round(t),...r).unref()},t.setUnrefInterval=function(e,t,...r){return(0,i.setInterval)(e,Math.round(t),...r).unref()}},31562:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const i=r(38639),n=r(42659),s=r(41400),o=r(32639),a=r(31586),l=r(45255),u=r(95937);async function c(e,{timeoutMs:t,intervalMs:r,acceptable:i,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const i=r??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(i,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:i.isTrue,timeoutResult:!1})}},9727:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=i(r(1708)),s=r(45599),o=r(41400),a=r(50357),l=r(68708),u=r(48884),c=r(36638),d=r(44198),h=r(59958),f=r(96706),m=r(34102),g=r(19851),p=r(19043),y=r(66184),v=r(50213),w=r(7282),S=r(88158),b=r(45969),P=r(43334),_=r(28874),E=r(3790);function M(e){return C().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const C=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const r of t.names)e.add(r);for(const r of t.keys)e.add(r)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const T=["HOME","LANG","USER"],x=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],D=(0,g.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?T:x),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function k(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const r of(0,_.persistedSettings)()){const i=e?r.value:r.envValue;null==i||(0,a.eql)(i,r.defaultValue)||r.addToEnv(t)}return t}t.sanitizedEnv=(0,g.lazy)((()=>(0,l.filter)(n.default.env,(e=>M(e)||!(0,E.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=k,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:I({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function I({overrides:e,forceCLocale:r=!0,forWorker:i=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...D(),...r?(0,p.childProcLocale)():{},...k(i),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,E.isHiddenEnvKey)(e)?"(hidden)":t])),[r,i]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(r)),e.debug("non PS env:",(0,l.fromEntries)(i))}return n}t.childEnv=I},84777:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=i(r(31421)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(42659),c=r(98553),d=r(56409),h=r(31586),f=r(68708),m=r(51926),g=r(50213),p=r(7282),y=r(88158),v=r(79089),w=r(45255),S=r(22911),b=r(4867),P=r(73614),_=r(70025),E=r(57159),M=r(36868),C=r(66184),T=r(45643),x=r(95402),D=r(9727),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const r=e.pid;if(null==r||r<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(r===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(r===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+r+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,x.killPid)(r).catch((e=>{k().warn("endProcess(): kill("+r+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,p.isSingleSpecTests)())return!0;if(await(0,T.waitForPidExit)(r,t))return k().debug("endProcess(): exitted",O(e)),!0;{x.Pids.instance()?.onKill(r);const t=e.kill("SIGKILL");k().warn("endProcess("+r+") had to resort to SIGKILL",{killResult:t}),t||await(0,x.killPid)(r,!0).catch((e=>{k().warn("endProcess(): kill("+r+",true) failed: "+e)}))}return(0,T.waitForPidExit)(r,5e3)}function A(e,r,i,n=0){const o=new Date,a=[];return(0,v.niceable)(r,i)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,x.addPid)({pid:e.pid,cmd:r,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function F(e,t,r,i){const s=(0,D.spawnOptions)(i);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:r,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:r}),A(n.default.execFile(e,t,s),e,t,r)}async function N(e,t,r){const i=r.quiet??!1,n=r.ignoreStderr??!1,s=r.ignoreExitCode??!1,o=F(e,t,r.timeoutMs,(0,f.omit)(r,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===r.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],g=[],p=[],y=new S.Deferred(f);o.on("error",(e=>p.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>p.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>p.push(e))),o.stderr?.on("data",(e=>g.push(e))),o.stderr?.on("end",(()=>P.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:r.timeoutMs,halt:r.halt}),k().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt});const C=g.join("");(0,l.notBlank)(C)&&p.push(new Error(C)),!i&&(0,a.isNotEmpty)(p)&&k().warn(f+" resulted in errors:",p);const T=r.isIgnorableError??_.isIgnorableError,x=p.filter((e=>!0!==T(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:C}}catch(e){throw k().error("stdoutResult_() failed",e),await(0,x.killPid)(o.pid,!0),e}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,r,i){const s=(0,D.spawnOptions)(i);return k().debug("spawn()",{command:e,args:t,maxAgeMs:r}),A(n.default.spawn(e,t,s),e,t,r)},t.execFile=F,t.stdoutResult_=N,t.stdout_=async function(e,t,r){const i=await N(e,t,r);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(i.result),meta:{cmd:e,args:t,opts:r,result:i}})}},3790:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const i=r(22573),n=r(41400),s=r(19851),o=r(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,i.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},41269:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const i=r(1708),n=r(31586),s=r(51926),o=r(17344),a=r(37805),l=r(84542);function u(e,t){const r=t?.maxLineLen??(0,n.toInt)(i.env.maxLineLen)??i.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:r,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},94361:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const i=r(19851),n=r(40958),s=r(55835),o=r(31586),a=r(94174),l=r(44198),u=r(45969);function c(e,t,r){const i=(0,o.toGt0)((0,l.env)()[t]);return null==i||r.includes(i)?void 0:`WARNING: ${e} is running as ${r} but $${t}=${i}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,i.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},76596:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const i=r(51168),n=r(19851),s=r(22573),o=r(42659),a=r(55835),l=r(31586),u=r(68708),c=r(34666),d=r(50213),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,r){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=r}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const r=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),i=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(r,i)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),r=Date.now();return t<=r?0:t-r},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const i=r(22573),n=r(31586),s=r(54557),o=r(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,i.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,i.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const i=r(51168),n=r(40958),s=r(22573),o=r(42659),a=r(31586),l=r(51926),u=r(68852),c=r(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=i.Duration.fromISO(e);if(t.isValid)return t.toMillis();const r=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(r,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const r=(0,a.toFloat)(e);if(null!=r){if((0,s.blank)(t))return r;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*o.yearMs;case"weeks":case"week":case"w":return r*o.weekMs;case"days":case"day":case"d":return r*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return r*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return r*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return r*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return r;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,r=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const i=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const r=Math.floor(t/e.ms);t-=r*e.ms,r>0&&i.push(r+e.s)}return i.join(r)}},84248:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const i=r(50989);t.AutoVacuumModes=(0,i.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const i=r(50989);t.CheckpointTypes=(0,i.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const i=r(50989);t.RepairModes=(0,i.strEnum)("dump","recover")},34365:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const i=r(50989);t.SynchronousModes=(0,i.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(r(76760)),a=r(40958),l=r(22573),u=r(55835),c=r(72993),d=r(19851),h=r(97352),f=r(94174),m=r(44198),g=r(96706),p=r(8769),y=r(57159),v=r(70698),w=r(64680),S=r(29882),b=r(45969),P=r(43334),_=r(28874),E=r(41692),M=r(32774),C=r(80612),T=r(32551),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,g.getEnv)("TEMP"),(0,g.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const r of t)(0,l.blank)(r)||e.push({dir:(0,o.join)(r,".photostructure-cache"+x()),preexistingDir:r});return e}}function k(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:M.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(P.isWin?[(0,g.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,r=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return r.push(...D()),r}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,C.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,C.firstDir)({dirs:k(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,E.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(I)}));function I(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,p.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=I},46292:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const i=r(19851),n=r(45969),s=r(41692),o=r(32774),a=r(10924),l=r(84373),u=r(80612);t.configDir=(0,i.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const i=r(66430),n=r(45969),s=r(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,i.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=i(r(76760)),s=r(40958),o=r(72993),a=r(44198),l=r(96706),u=r(43334),c=r(80612),d=r(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const i=r(22573),n=r(96706),s=r(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,i.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const i=r(44652),n=r(40958),s=r(22573),o=r(66430);function a({dirs:e,desc:t}){for(const{dir:r,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(r)){if((0,o.isReadWriteableDirectorySync)(r))return r;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,i.mkdirpSync)(r),r}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const i=r(48161),n=r(76760),s=r(1708),o=r(19851),a=r(40958),l=r(68284),u=r(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,i.homedir)()}))},46296:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(55835),u=r(54993),c=r(72993),d=r(96706),h=r(45969),f=r(43334),m=r(32707),g=r(6707),p=r(49776),y=r(32774),v=r(80612),w=r(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,p.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,g.readTomlFileSync)((0,m.systemSettingsFile)()),r=(0,u.toS)(t?.logDir);return(0,a.notBlank)(r)?r:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const i=r(76760),n=r(19851),s=r(22573),o=r(44198),a=r(43334),l=r(24399),u=r(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,i.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const i=r(38639),n=r(7282),s=r(29325),o=r(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,i.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const i=r(38639),n=r(44198);t.doNotTrack=function(){return(0,i.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=i(r(73024)),s=r(76760),o=i(r(1708)),a=r(19851),l=r(40958),u=r(41400),c=r(68708),d=r(76850),h=r(7282),f=r(23560),m=r(32551),g=r(34102),p=r(53265),y=r(45969),v=r(59958),w=r(6012),S=r(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),r={...o.default.env};for(const i of e)try{const e=(0,d.debom)(n.default.readFileSync((0,p.resolve)(i))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,i]of(0,c.entries)(s))t.test(e)||(r[e]=i)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+i,e)}return r})),(0,u.later)((()=>{(0,g.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const i=r(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,i.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const i=r(50989);t.EnvKeys=(0,i.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const i=r(22573),n=r(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const r={};if((0,i.blank)(e))return r;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,i.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");r[t?e.toLowerCase():e]=o}}return r}},96706:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=i(r(1708)),s=r(19851),o=r(22573),a=r(38639),l=r(41400),u=r(40583),c=r(79840),d=r(83556),h=r(34102),f=r(44198),m=r(83373);function g(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=g,(0,l.later)((()=>{f.env.watchLater(g),(0,h.ee)().on("clearCache",g)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},98314:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const i=r(58587),n=r(19851),s=r(40958),o=r(22573),a=r(26905),l=r(96249),u=r(51926),c=r(23541),d=r(54993),h=r(89788),f=r(50213),m=r(81168),g=r(84542),p=r(41954),y=r(38835),v=r(70025),w=r(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,p.getErrorDescriptions)(e));const r=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,g.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(r)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const r=(0,s.uniqSubstrings)(b(e)),i=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(r.join(a.ErrorDelimiter)),i-o.length,n)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new i.Rate,t.fatalErrorRate=new i.Rate,t.internalErrorRate=new i.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const r=(0,d.toS)(t?.[e]);if((0,o.notBlank)(r))return r}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,r=256,i=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:r})+" at "+(0,a.shortStack)(e?.stack,i).join("; ")}},41954:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const i=r(40958),n=r(26905),s=r(55835),o=r(54993),a=r(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const r of e)(0,s.map)((0,n.errorErrno)(r),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(r),(e=>t.push(l[e]?.description)));return(0,i.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const i=r(40958),n=r(76790),s=r(50989),o=r(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,i.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const i=r(40958),n=r(38639),s=r(26905),o=r(54993),a=r(68852),l=r(73568),u=r(78656),c=r(98314),d=r(38835);function h(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const r=(0,o.toS)(e)+(0,i.compact)(t).join("");return h(r)+f(r).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const g=/Can't write [a-z\d]+ files/i,p=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const r=(0,c.errorToS)(e);return!g.test(r)&&(!!p.test(r)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const r=(0,c.errorToS)(e);return!(!r.includes("EBUSY")&&!r.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const r=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>r.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const i=r(22573),n=r(31586),s=r(68708),o=r(7282),a=r(23560),l=r(45608),u=r(34102),c=r(28874),d=r(98314),h=r(38835),f=r(70025),m=r(57159),g=r(5012);function p(e,t){try{if((0,i.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,g.stack)()),!1;const r=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===r.fatal,c=!0===r.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",r));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:r}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:r.toString(),status:r.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=p,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,r){return p(e+h.InternalErrorFlag,{cause:t,...r})}},57159:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const i=r(40958),n=r(22573),s=r(38639),o=r(26905),a=r(98553),l=r(68708),u=r(59455),c=r(41583),d=r(48884),h=r(81168),f=r(98314),m=r(38835),g=r(70025);t.toWrappedError=function(e,t){const r=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof p&&(null==t||(0,n.blank)(r.message)||e.message.includes(r.message)))return e;const i=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,r?.message);return new p(i??"(missing error message)",r)};class p extends Error{constructor(e,t={}){super(e),this.causes=(0,i.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const r=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??r.some(g.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(r.map(g.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(r.map(g.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(r.map(g.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,g.stripErrorFlags)(function(e,t){let r=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const i=t?.path;return(0,n.blank)(i)||(r=(0,h.dedupeNeedle)(r,i,"file")),(0,f.joinErrorMessages)([r[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...r.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new p(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=p},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=r(49769),a=r(55835),l=r(54993),u=r(22911),c=r(89788),d=r(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,i.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,i,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const r=this.target.emit(e,...t),o=s(this,i,"f").get(e);return null!=o&&(o.resolve(t),s(this,i,"f").delete(e)),r}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},i=new WeakMap,n=new WeakMap},34102:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const i=r(78474),n=r(19851),s=r(15197);t.ee=(0,n.lazy)((()=>{const e=new i.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=i(r(73024)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(65843),u=r(16287),c=r(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):p({stat:e,r:!0,w:!0,x:!0})}function g(e,t){return c.isWin?f(t,n.default.constants.R_OK):p({stat:e,r:!0,x:!0})}function p({stat:e,r:t=!1,w:r=!1,x:i=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(r&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!i||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=g,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const r of(0,l.selfAndAncestorG)(e)){const i=await(0,u.statMaybe)(r);if(null!=i){if(!i.isDirectory())return!1;if(t){if(!g(i,e))return!1}else if(t=!0,!m(i,e))return!1}}return!0},t.access=p},21144:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=i(r(76760)),s=r(19851),o=r(81168),a=r(57159),l=r(43334),u=r(88561),c=r(29882),d=r(65238),h=r(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const r=(0,c.parseNativePath)((0,h.resolve)(...e)),i=await m(r.dir);for(const e of await(0,d.readdir_)(i))if((0,o.equalsIgnoreCase)(e.basename,r.base))return n.default.join(i,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const i=r(73024),n=r(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,i.readdirSync)(e)}catch(e){return[]}}function l(e,t){const r=a(e);return t.every((e=>r.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,r){var i,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&l(t,e,r);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(r(44652)),g=c(r(73024)),p=r(51455),y=f(r(76760)),v=f(r(1708)),w=r(46466),S=f(r(57975)),b=f(r(38522)),P=r(19851),_=r(40958),E=r(5233),M=r(22573),C=r(42659),T=r(50357),x=r(96249),D=r(98553),k=r(55835),O=r(31586),I=r(68708),A=r(97790),F=r(39926),N=r(51926),L=r(59455),R=r(54993),j=r(48884),B=r(22911),V=r(99331),z=r(56519),W=r(56038),q=r(31562),U=r(76850),G=r(70025),H=r(34102),J=r(80875),K=r(50213),$=r(70417),Y=r(43334),Z=r(81168),X=r(96859),Q=r(65162),ee=r(94174),te=r(64660),re=r(21144),ie=r(84542),ne=r(89968),se=r(20197),oe=r(88561),ae=r(50597),le=r(33456),ue=r(29882),ce=r(78133),de=r(43899),he=r(65238),fe=r(53265),me=r(17217),ge=r(16287),pe=r(68284),ye=r(66003),ve=r(27794),we=r(73428),Se=r(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(i.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,K.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,i=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),r=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(r)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const r=(0,me.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,M.blank)(r))throw new Error("BaseFile.for(): empty nativePathOrFile");const i=be().get(r);if(null!=i)return i;const n=(0,fe.resolve)(r),s=new Pe(n,t);return be().set(r,s),be().set(n,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const r=[];for(const i of t)!0===await e(i)&&r.push(i);return r}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,i,"m",s).call(this)??await d(e=this.clearThisAndParent(),i,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const r of t)await r.visitDescendants(e),await e(r)}))}async descendants(e){const t=[];t.push(...(0,L.toA)(await this.childFiles(e)));const r=await this.childDirectories();if(null==r)return t;for(const i of r)t.push(...(0,L.toA)(await i.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const r=await d(this,n,"f").call(this)??[];for(const t of r)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const i of r)if(i.isDirectory()){const r=await this._directoryEntryChild(i).someDescendant(e,t-1);if(null!=r)return r}}descendantsSync(e){const t=this.directoryEntrySync(),r=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&r.push(this.forDirectoryEntry(t))})),r}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,re.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,r)=>this.join((0,R.toS)(e),(0,F.pad2)(t+1),(0,F.pad2)(r))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,r="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(r,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,r="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(r,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,r){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(r??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,ge.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,ge.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,C.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,ge.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>=(0,C.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(r=>Math.abs(r-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>(0,C.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,A.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,q.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*C.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,J.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,J.parseJSON)((0,g.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,g.readFileSync)(this.nativePath)}readFile_(){return(0,p.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return g.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,E.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,V.ending)()?1:3,timeoutMs:0,retryDelay:C.secondMs,errorIsRetriable:G.isRetriableError})}async gunzip(){return d(this,i,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,i,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,i,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return g.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return g.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const r=await this.children((async r=>!r.isNameHidden()&&t===r.size()&&r.nativePath!==e.nativePath));if((0,_.isEmpty)(r))return;const i=await e.sha();if(null!=i)for(const e of r.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===i)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),r=g.default.createReadStream(this.nativePath,{flags:"r"});return r.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),r.close()):t.maybeReject(e)})),r.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(r,(0,N.newlineRe)(),(i=>{const n=e.exec(i);null!=n&&(t.maybeResolve(n),r.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,r)=>{for(const i of e)for(const e of r)if((0,O.closeTo)(i,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),r=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&r.setTimeout(e.timeoutMs),_e)try{const i=(0,g.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(i,n)=>{try{const s=await e.f(i,(0,k.denull)(n));t(s)&&r.resolve(s)}catch(e){r.reject(e)}}));r.finally((()=>{i.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const i=setInterval((async()=>{try{const i=await e.f();t(i)&&r.resolve(i)}catch(e){r.reject(e)}}),e.intervalMs);e.persistent||i.unref(),r.finally((()=>{clearInterval(i)}))}return r}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const r=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([g.default.createReadStream(this.nativePath,{autoClose:!0}),t,g.default.createWriteStream(r.nativePath,{autoClose:!0})]),await this.unlink(),r}))},Pe.attrTTL=3*C.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},84542:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const i=r(40958),n=r(96249),s=r(51926),o=r(54993),a=r(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,i.compactBlanks)(l(...e))}},70698:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const i=r(76760),n=r(19851),s=r(50213),o=r(37805),a=r(29882),l=r(93854),u=r(17217),c=r(16287),d=r(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const r=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return r===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,i.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const r=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(r),await(0,d.writeTextfile_)((0,a.joinNativePath)([r,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(45969),u=r(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(r(44652)),l=o(r(73024)),u=r(76760),c=r(57975),d=r(19851),h=r(59455),f=r(50213),m=r(81168),g=r(34102),p=r(29882),y=r(65238),v=r(14427),w=r(17217),S=r(16287),b=r(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class E{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,p.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new E(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:r,base:i}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,p.parseNativePath)(e)},n=await a.stat(t);return new E(r,new P(i,n))}clear(){return(0,g.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return E.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,p.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,p.parseNativePath)(this.dir);return e.dir===this.dir?this:new E(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>E.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new E(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const r of t)r.isDirectory()&&await r.visitDescendants(e);for(const r of t)r.isFile()&&await e(r);for(const r of t)r.isDirectory()&&await e(r)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const r of t)r.isFile()&&e(r);for(const r of t)r.isDirectory()&&(r.visitDescendantsSync(e),e(r))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async r=>{!0===await e(r)&&t.push(r)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,g.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,g.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=E},20197:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=i(r(76760)),s=r(39926),o=r(29882),a=r(16287),l=r(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if(await(0,o.mkdirp_)(i.dir),!r.requireNumber&&await(0,a.isEmptyFile)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if(await(0,a.isEmptyFile)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)},t.ensureNewNativePathSync_=function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if((0,o.mkdirpSync_)(i.dir),!r.requireNumber&&(0,l.isEmptyFileSync)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if((0,l.isEmptyFileSync)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)}},88561:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=r(40958),a=r(22573),l=r(41400),u=r(68708),c=r(25764),d=r(38836),h=r(34102),f=r(80049),m=r(50213),g=r(88158),p=r(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:p.ShortCommandTimeoutMs,...e}),i.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,i,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,g.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,i=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const i=r(73024),n=r(22573),s=r(45599),o=r(96249),a=r(68708),l=r(54993),u=r(49047),c=r(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...r]of d)for(const i of r)e[i]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof i.Dirent?e.name:(0,l.toS)(e),r=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(r)?void 0:h()[r]??r}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const r of t)if(r===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const i=r(68708),n=r(17217),s=r(16287),o=r(68284);async function a(e){return(0,i.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,i.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},4001:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const i=r(22573),n=r(55835),s=r(31586),o=r(51926),a=r(54993),l=r(97352),u=r(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,i.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,r){if(t.ymdIsoRE.test(e))return e;let i=e;for(const e of r.aggressive?d:c){const t=i.match(e);if((0,s.gt0)(t?.index)){const e=i.slice(0,t.index).trim();e.length>0&&(i=e)}}return e===i?e:f(i,r)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),r=t.pop();if((0,i.blank)(r))return e;const n=(0,u.parsePosixPath)(r),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),r=h(t),i=(0,o.stripPrefix)(t.toLowerCase().normalize(),r);return(0,n.map)((0,l.extractInt)(i),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,g=/(?<=.{6})_cover$/i,p=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(g,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(p.exec(t),(e=>t=e[1].trim())),t}},50597:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=i(r(77598)),s=i(r(73024)),o=r(46466),a=r(19851),l=r(98553),u=r(68708),c=r(23467),d=r(80049),h=r(73913),f=r(50213),m=r(12089),g=r(37628),p=r(43624),y=r(17217),v=r(16287),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:r=!0}={}){const i=(0,y.toNativePath_)(e);if(r){const t=S().get(i);if(null!=t){if((0,c.eql)(t.stats,await(0,p.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:i,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:i,prior:t}),S().delete(i)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),r=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(r)),stats:(0,u.pick)(await(0,v.stat_)(r),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],r="sha512"){const i=n.default.createHash(r);return await(0,o.pipeline)([e,...t,i]),i.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,g.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},25675:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const i=r(22573),n=r(54993),s=r(7282),o=r(43334),a=r(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,i.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const i=r(57075),n=r(51926),s=r(54993);class o extends i.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,r){const i=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=i.pop();this._prior=o??"";let a=!1;for(const e of i)a||(a=!this.push(e));a?setTimeout(r,1):r()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=i(r(76760)),s=r(17217),o=r(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},29882:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(5233),u=r(22573),c=r(98553),d=r(39426),h=r(51926),f=r(48884),m=r(50213),g=r(81168),p=r(70025),y=r(43334),v=r(78133),w=r(53265),S=r(17217),b=r(16287),P=r(66430),_=r(5545);function E(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=E,t.containsHiddenPathname=function(e){return k(e).some(E)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!E(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return C((0,v.posix2native)(e))},t.extname=function(e){return C(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,g.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function C(e){const t=M.exec(e)?.groups,r=t?.ext2??"",i=s.default.parse(t?.path??e);return{...i,ext:(i.ext??"")+r,base:(i.base??"")+r}}function T(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),r=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(r))return!1;const i=e.acceptSelf??!1;return t===r?i:r.startsWith((0,g.ensureSuffix)(t,s.default.sep))}catch(r){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:r}),!1}}function D(e,t,r){if(null==t||null==r)return!1;const i=e(t),n=e(r);return null!=i&&null!=n&&(y.isLinux?i===n:(0,g.equalsIgnoreCase)(i,n))}function k(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&k(e).length===(y.isWin?1:0)}function I({p:e,maxLength:t}){const r=(0,S.toNativePath_)(e);if(r.length<=t)return r;const i=k(e),n=[],s=[i.pop()];for(;i.length>0;)if(n.length=t){i.unshift(n.pop());break}}else if(s.unshift(i.pop()),F([...n,...s]).length>=t){i.push(s.shift());break}return i.length>0&&n.push("…"),F([...n,...s])}function A(e){return e.startsWith("\\\\")}function F(e){return(0,h.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=C,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(S.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const r=(0,S.toNativePath_)(e),i=(0,S.toNativePath_)(t);if((0,u.blank)(r)||(0,u.blank)(i))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return r===i?"":(0,g.stripPrefix)((0,v.native2posix)(i).normalize(),(0,g.ensureSuffix)((0,v.native2posix)(r),"/").normalize()).normalize()},t.ellipsizePath=I,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:r=4,arrLength:i=e.length}){const n=[];for(const i of e.slice(0,r))n.push(I({p:i,maxLength:t}));return n.join(", ")+(i>r?`, and ${i-r} more…`:"")},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const r=C(e);return`${r.base}${t}${r.ext}`},t.isUNC=A,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(A(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(31586),u=r(51926),c=r(12168),d=r(59455),h=r(54993),f=r(50213),m=r(44198),g=r(96706),p=r(45969),y=r(43334),v=r(64660),w=r(21144),S=r(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const r=await(0,S.statMaybe)(e,"trace");return null!=r&&r.isFile()&&(0,l.gte)(r.size,t)&&(0,v.isStatRX)(r,e)}function E(){if(y.isWin){const e=(0,a.toNotBlank)((0,g.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,g.getEnv)("SystemDrive"))??"C:",r=(0,a.toNotBlank)((0,g.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(r,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,p.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...E()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:r}){const i=(0,o.uniq)((0,o.compactBlanks)([...M(),...(0,d.toA)(r)]));for(const r of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(r,".exe"):r;for(const t of i){const r=n.default.join(t,e);if(await _(r))return y.isLinux?r:(0,w.actualPath)(r)}}b().warn("Failed to find tool",{tool:e,dirs:i})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},78133:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=i(r(76760)),s=r(22573),o=r(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const r=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",i=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(i[0],t)&&i.unshift(),r+i.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(48884),u=r(50213),c=r(45969),d=r(29325),h=r(43334),f=r(65843),m=r(25675),g=r(53265);function p(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(n.default.join((0,g.execDir)(),"resources"),n.default.join((0,g.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,g.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const r of t){if((0,f.hasChildrenSync)(r,e))return r;for(const t of(0,f.ancestors)(r).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const i=n.default.join(r,"node_modules","photostructure");if((0,f.hasChildrenSync)(i,e))return i}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:p("bin"),Data:p("data"),ICC:p("data","icc"),Migrations:p("data","migrations"),Public:p("public"),Tools:p("tools"),Views:p("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const i=r(44652),n=r(19851),s=r(31586),o=r(50213),a=r(57902),l=r(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,i.readFile)(e)}catch(r){return void u().log(t,".readFileMaybe("+e+")",r)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const i=r(44652),n=r(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:r}){let s=-1;try{const n=r??(await(0,i.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,i.open)(e,"r"),await(0,i.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,i.close)}}},69428:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(r(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},32323:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const i=r(57075);class n extends i.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=i(r(51455)),s=r(76760),o=r(19851),a=r(76790),l=r(22573),u=r(42659),c=r(41400),d=r(31586),h=r(13538),f=r(83104),m=r(54127),g=r(50213),p=r(95937),y=r(34102),v=r(28874),w=r(63870),S=r(88561),b=r(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,g.mkLogger)("fs.Readdir")));async function _(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const E=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||E.prior()?.delete(e)}async function C(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await E().getOrSetAsync(e,(()=>async function(e){const r=Date.now()+2*(0,b.statTimeoutMs)(),i=T(e),n=await(0,h.thenOrTimeout)(i,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===f.Timeout&&(0,p.onTimeout)({soft:!1}),n!==f.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),E.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!E().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=E().get(e)},t.childDirectories_=async function(e){return(await C(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?C(e):T(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=C,t.readdirCached=function(e){return E().get(e)},t.readdirUncached_=T},53265:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=r(73024),s=i(r(76760)),o=r(40958),a=r(22573),l=r(45599),u=r(50213),c=r(43334),d=r(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function g(...e){for(const t of m()){const r=s.default.resolve(t,...e);if((0,n.existsSync)(r))return r}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?g(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=g},50274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const i=r(50989);t.SidecarExts=(0,i.strEnum)("xmp","mie","exv")},14427:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const i=r(22573),n=r(38639);t.isSimpleDirent=function(e){return null!=e&&(0,i.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=i(r(73024)),s=i(r(76760)),o=r(22573),a=r(98553),l=r(81168),u=r(43334),c=r(29882),d=r(53265),h=r(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function g(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=g,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(g(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const p=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(p)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),r=t.indexOf(s.default.sep);return r>0?t.slice(1,r):void 0}},t.findFileIndex=function(e,t){for(let r=0;r(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,p.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((r=>{y().log(t,"stat() failed",{error:r,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const r=S(e),i=S(t);if(r!==i)return"inconsistent file type: "+r+" ≠ "+i;for(const r of["size","mtime"]){const i=e[r],n=t[r],s=(0,u.diff)(b(i),b(n));if(null==s||s>1)return"unmatched "+r+": "+i+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const r=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=r&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(r)},t.isNonEmptyFile=async function(e,t=0){const r=await w(e);return null!=r&&r.isFile()&&r.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.access)({stat:r,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.isStatRWX)(r,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=i(r(73024)),s=r(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const r=o(e);return t.emptyIsNew?null==r:a(r)},t.isNonEmptyFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const i=r(28874);t.statTimeoutMs=function(){return i.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const i=r(22573),n=r(56409);t.onDataChunked=function(e,t,r){const i=new s(t,r,!0);return i.read(e),i.done};class s{constructor(e,t,r=!0){this.sep=e,this.onData=t,this.filterBlanks=r,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,i.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,i.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=i(r(57075)),s=r(41400),o=r(55835),a=r(68708),l=r(42279),u=r(99331),c=r(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((r,i)=>{!1===e.write(t,(e=>{e&&i(e)}))?e.once("drain",r):r()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:r,ea:i}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(i,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(r,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends n.default.Transform{constructor(e){super({transform:(e,t,r)=>{this.onProgress(this.bytes+=e.length),r(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=i(r(73024)),s=r(76760),o=r(22573),a=r(76596),l=r(64660),u=r(78133),c=r(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},27794:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=i(r(44652)),s=r(19851),o=r(22573),a=r(42659),l=r(31586),u=r(68708),c=r(13538),d=r(29882),h=r(17217),f=r(16287),m=r(41080);function g(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const r=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const i=(0,h.toNativePath_)(t.file);r&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(g(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),p=Math.round(g(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(i,new Date(p),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!r||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(i),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},5545:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=i(r(76760)),s=r(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const r=t.driveRe.exec(e)?.groups;return null==r?e:r.drive.toUpperCase()+(0,s.toS)(r.path??n.default.sep)}},58722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const i=r(57075),n=r(22911);class s extends i.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,r){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),r()}}t.WritableToBuffer=s},73428:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(51926),a=r(54993),l=r(34102),u=r(84542),c=r(29882);async function d(e,t){const r=s.default.dirname(e);await(0,c.mkdirp_)(r),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",r)}function h(e,t){const r=s.default.dirname(e);(0,c.mkdirpSync_)(r),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",r)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const r=(0,u.crlf)(...(0,o.wrap)(t));await d(e,r)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=i(r(73024)),s=r(76760),o=r(46466),a=r(38522),l=r(19851),u=r(40958),c=r(98553),d=r(80875),h=r(50213),f=r(57159),m=r(29882),g=r(57902),p=r(32323),y=r(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,r){const i=[],s=[n.default.createReadStream(e,{autoClose:!0,...r}).on("error",(e=>i.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>i.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>i.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(i))throw new f.WrappedError("zPipe("+e+") failed",{causes:i,path:e})}async function b(e,t){const r=new y.WritableToBuffer;return await S(e,r,t),await r.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const r=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new p.ReadableBuffer(r),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=g.LogLevels.warn){try{return await P(e)}catch(r){return void v().log(t,"readJsonGz("+e+"): failed",r)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,r=g.LogLevels.warn){try{await _(e,t)}catch(t){v().log(r,"outputJsonGz("+e+"): failed",t)}}},33866:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const i=r(50989);t.HealthCheckIds=(0,i.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},52086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const i=r(50989);t.CropStrategies=(0,i.strEnum)("center","entropy","attention")},48584:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const i=r(50989);t.SharpFailOns=(0,i.strEnum)("none","truncated","error","warning")},32105:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const i=r(19851),n=r(23560),s=r(66184),o=r(72210);class a{log(e,t,r,i){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:r,meta:i})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,i.lazy)((()=>new a))},14593:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const i=r(57975),n=r(22573),s=r(26905),o=r(55835),a=r(68708),l=r(13538),u=r(50213),c=r(97352),d=r(45255),h=r(76740),f=r(57159),m=r(57902),g=/logger|lazy/i;class p{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!g.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[i.inspect.custom](){return this.toLogJSON()}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const r=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(r),this.log(!0===r.ignorable?"warn":"error",".throw() "+r.message,{stack:r.stack,...t}),r}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let r;try{r=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const i=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:i,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(r,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const r of this.loggers())if(r.enabled(e,t??this.context))return!0;return!1}log(e,t,r){for(const i of this.loggers())i.log(e,this.context,t,r)}elapsed(e,t,r){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...r})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=p},28981:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const i=r(19851),n=r(51879);t.DefaultLogFormatter=(0,i.lazy)((()=>new n.PlaintextLogFormatter))},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},4904:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const i=r(76790),n=r(31586),s=r(51926),o=r(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,i.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const i=r(19851),n=r(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,i.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,i.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,r){return(0,t.logFilter)().enabled(e)?r():void 0},t.isLogged=function(e,r){return(0,t.logFilter)().enabled(e,r)}},57902:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const i=r(31586),n=r(50989),s=r(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,r){return(0,i.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(r))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},72210:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const i=r(92322),n=r(82328),s=r(28981),o=r(20839),a=r(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new i.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const r of e)l?t.logEntries.add(r):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(r))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},51879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(68708),a=r(54993),l=r(23560),u=r(81168),c=r(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,i.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:r,meta:i})}}},82647:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=r(57975),a=r(40958),l=r(96249),u=r(55835),c=r(31586),d=r(68708),h=r(59455),f=r(48884),m=r(89788),g=r(22454),p=r(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const r=t.clone();return r.pushAll(e.samples),r}if(t.n<=t.maxSamples){const r=e.clone();return r.pushAll(t.samples),r}{const r=new y(Math.max(e.maxSamples,t.maxSamples));r._n=e.n+t.n,r._min=Math.min(e._min,t._min),r._max=Math.max(e._max,t._max),r._m=e._m*e.n/r.n+t._m*t.n/r.n,r._s=e._s*e.n/r.n+t._s*t.n/r.n;const i=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return r._samples.push(...i),r._weightedTotalAvg=(0,p.weightedAvg)([r._m,...i]),r}}constructor(e=20){i.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(i=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,p.min)([this._min,e.min]),this._max=(0,p.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),r={};return r.k=t(this.n),this.empty||(r.mean=t(this.avg),r.sum=t(this.sum),r.sd=t(this.stdDev),r.max=t(this.max),r.min=t(this.min)),r}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,i,"m",n).call(this,-1)}get p29(){return s(this,i,"m",n).call(this,-.5)}get p38(){return s(this,i,"m",n).call(this,-.25)}get p69(){return s(this,i,"m",n).call(this,.5)}get p84(){return s(this,i,"m",n).call(this,1)}get p98(){return s(this,i,"m",n).call(this,2)}get p99(){return s(this,i,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new g.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,p.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,p.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,p.avg)}get sampleSlope(){return(0,p.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,p.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const i=r(40958),n=r(55835),s=r(31586),o=r(30976),a=r(48884),l=r(70417);function u(e,t){const r=Math.pow(2,t),i=[];for(;e>0;)i.unshift(e%r),e=Math.floor(e/r);return i}t.concatBits=function(e,t){const r=Math.pow(2,t);return e.reduce(((e,t)=>e*r+(0,s.clamp)(0,r,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,r){return(0,n.map2)(e,t,((e,t)=>(0,i.sum)((0,a.zip)(u(e,r),u(t,r)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,r[t]=o):i[t]=o}return s}unzip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max));for(let n=0;n(r[e]+i[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,r){return!0!==r&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let r=0;rs?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const r=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,i.sum)(e,((r,i)=>t(r,i)?Math.pow(2,e.length-i-1):0))}},55222:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const i=r(77598),n=r(22573),s=r(55835),o=r(32639),a=r(88158),l=r(81168),u=BigInt(0);function c(e,t,r=0){if(!isFinite(t)||e<=1)return[];const i=[];if(0===t)i.unshift(0);else for(;t>0;)i.unshift(t%e),t=Math.floor(t/e);for(;i.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const r=e<0;return r&&(e=Math.abs(e),t--),(r?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],r=BigInt(this.base);let i=e;for(;i>u;)t.push(Number(i%r)),i/=r;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let r of e)for(t.forEach(((e,i)=>{r+=e<<8,t[i]=r%this.base,r=Math.floor(r/this.base)}));r>0;)t.push(r%this.base),r=Math.floor(r/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const r=BigInt(this.base);let i=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;i=i*r+BigInt(e)}return t?BigInt(-1)*i:i}randomChars(e){return this.encodeBuffer((0,i.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,r="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(r)}tokenEql(e,t,r){const i=this.normalizeToken(e),n=this.normalizeToken(t);return i.length>=r&&i===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const i=r(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,i.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},70417:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=r(40958),l=r(55835),u=r(31586),c=r(59455),d=r(22454),h=r(77377),f=r(82647);function m(e){let t;for(const r of e)null!=r&&(null==t||rt)&&(t=r);return t}function y(e,t){const r=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&r.incr(t);return r.topKeys(t)}function v(e,t){let r=0,i=0;for(const n of e){if(null!=n){const e=t(n,r);(0,u.isNumber)(e)&&(i+=e)}r++}return i}t.min=m,t.max=p,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,r)=>e-t[r]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const r of e)(0,u.isNumber)(r)&&(t+=r);return t},t.sumf=v;class w{constructor(){i.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,i,"f")/(s(this,i,"f")+1)+e/(s(this,i,"f")+1),"f"),o(this,i,(t=s(this,i,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const r of e)t.push(r);return t.mean}function b(e){const t=S(e);if(null==t)return;let r=0,i=0;for(const n of e)(0,u.isNumber)(n)&&(i++,r+=(n-t)*(n-t));return r/i}function P(e){let t=0;for(const r of e)t+=r*r;return Math.sqrt(t)}function _(e,t){let r=0;for(let i=0;i(1-t)*e+t*(r+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),r=S(t);if(null!=r){const e=(t.length-1)/2,i=v(t,((t,i)=>(t-r)*(i-e))),n=v(t,(e=>(e-r)**2));return 0===n?0:i/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let r;t=(0,u.clamp)(0,1,t);for(const i of e)r=null==r?i:r*t+i*(1-t);return r},t.centroid=function(e){const t=e[0].length,r=[];for(let i=0;ie[i]))));return r},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},45969:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const i=r(73024),n=r(38639),s=r(19851),o=r(59958),a=r(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,i.existsSync)("/.running-in-container"))))},29325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const i=r(76760),n=r(19851),s=r(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,i.join)("core","platform","IsPacked"))))},43334:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(22573),a=r(38639),l=r(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=i(r(73024)),s=r(19851),o=r(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const i=r(58587),n=r(59455),s=r(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(i.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,i.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=r(58587),d=u(r(31421)),h=u(r(1708)),f=r(40958),m=r(22573),g=r(42659),p=r(55835),y=r(31586),v=r(97790),w=r(59455),S=r(54993),b=r(54557),P=r(19851),_=r(50213),E=r(88158),M=r(409),C=r(78406),T=r(25764),x=r(99331),D=r(56519),k=r(46292),O=r(8769),I=r(83278),A=r(32144),F=r(29882),N=r(43334),L=r(24399),R=r(58261),j=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),B=10*g.secondMs;function V(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const r=(0,p.map)(t.start,(e=>e.getTime())),i=e.startTime;return(0,y.gt0)(r)&&(0,y.gt0)(i)&&Math.abs(r-i){const e=Date.now()-2*g.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,A.isJsonExt)(t)&&(0,F.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:g.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,r=e.force??N.isWin,i=await this.pidfiles(),n=await this.pids(i??[]);if((0,f.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,R.pidInfos)(n);if(null!=a){for(const n of i){const i=await n.readJson();if(null==i){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=i.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:i,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!V(i,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:i,pidEntry:u}),await n.unlink("debug"),s.push(i);continue}const c=(0,y.gt0)(i.timeoutMs)?i.startTime+i.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(i.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:i}),o.push(W(l,r,!1)),s.push({...i,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,r=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(r&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const r=a(this,i,"m",s).call(this,e.pid),n=(0,v.opt)((0,E.Try)((()=>(0,F.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await r.writeJson_(l),j().debug("addPid() wrote "+r,l),r}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,i,"m",s).call(this,e);return(0,D.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,g.ago)(g.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new C.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*g.minuteMs,rank:T.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=q,n=new WeakMap,o=new WeakMap,i=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},q.instance=(0,P.lazy)((()=>(0,p.map)((0,k.configDir)(),(e=>new q(I.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return q.instance()?.addPid_(e,t)}},58261:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=r(31421),s=r(48161),o=i(r(1708)),a=r(40958),l=r(22573),u=r(42659),c=r(31586),d=r(68708),h=r(59455),f=r(54993),m=r(48884),g=r(53507),p=r(19851),y=r(50213),v=r(84968),w=r(48963),S=r(56519),b=r(84777),P=r(8103),_=r(45879),E=r(43334),M=r(24399),C=r(45643),T=(0,p.lazy)((()=>(0,y.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){if(E.isLinux)return async function(e){const t=[];for(const r of e)t.push(z(await(0,_.readFileMaybe)("/proc/"+r+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,C.existingPids)(e),r=(await(0,m.collectBatchedAsync)(t,20,E.isWin?A:R)).filter((e=>x(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:r,meta:{pids:e}})}t.isProcEntry=x,t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,C.existingPids)(e),(t=>{const r=[o.default.pid,...t];return e.filter((e=>!r.includes(e)))}))},t.pidInfos=D;const k="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function A(e){if(M.PowerShell.instance().ended)return L(e);const t=[k,"-Id",I(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},N=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const r=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",r)}t.push("get",N.join(","));const r=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),i=(0,d.onlyReqValued)((0,g.parseFixed)(N,r.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return i.find((e=>e.pid===o.default.pid))||i.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),i}async function R(e){return t=(await(0,b.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,g.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=L;const j=(0,p.lazy)((()=>{try{if(E.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){T().warn("clk_tck failed",{error:e})}return 100})),B=(0,p.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),V=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function z(e){const t=V.exec((0,f.toS)(e))?.groups,r=(0,c.toInt)(t?.pid),i=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(r)&&!(0,l.blank)(i)&&(0,c.gt0)(n)?{pid:r,cmd:i,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},24399:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const i=r(58587),n=r(19851),s=r(22573),o=r(42659),a=r(41400),l=r(55835),u=r(13538),c=r(36557),d=r(14121),h=r(50213),f=r(7282),m=r(45255),g=r(81168),p=r(25764),y=r(38836),v=r(99331),w=r(56519),S=r(31562),b=r(84777),P=r(34102),_=r(43334),E=r(28874),M=r(63870),C="{ready}",T=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),p.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new i.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",E.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${C}"}`,...(0,s.mapNotBlankOr)(E.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:C,fail:"Error",exitCommand:"exit",maxProcs:E.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),p.EndableRanks.postdb),E.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(E.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,g.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const r=this.mockResults.get(e);return t(r.stdout,r.stderr,r.passed)}try{const r=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new i.Task(e,((r,i,n)=>t((0,l.map)(r,(t=>(0,g.stripPrefix)(t,e))),i,n)))));return this.logger.tap({msg:"execute()",result:r.result,meta:{elapsedMs:r.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,g.ensureSuffix)(e,T),((e,t,r)=>({stdout:e,stderr:t,passed:r})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const r=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,g.ellipsize)(t.stdout),after:(0,g.ellipsize)(r)}),JSON.parse(r)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,n.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const i=r(50989);t.AggregateTypes=(0,i.strEnum)("union","intersection")},71988:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const i=r(50989);t.AssetFileSortCriteria=(0,i.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const i=r(22573),n=r(38639),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(i.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const i=r(50989);t.ColorDistanceFunctions=(0,i.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const i=r(36507),n=r(22573),s=r(45599),o=r(50213),a=r(81168),l=r(98314),u=r(8769),c=r(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,i.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,r){try{return(0,n.blank)(t)?void 0:(0,i.Cron)(t,{name:e,unref:!0,protect:!0,catch:r=>(0,u.onError)(r,{name:e,crontab:t}),...r})}catch(r){return void d().warn("invalid cron",{name:e,crontab:t,error:r})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const i=r(70488),n=r(91655),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration})}get valueOrDefault(){return(0,i.decodeDuration)(super.valueOrDefault)}get value(){return(0,i.decodeDuration)(super.value)}set value(e){super.userValue=(0,i.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,i.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,i.decodeDuration)(this.defaultValue)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const i=r(22573),n=r(53265),s=r(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,i.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const i=r(51926),n=r(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,i.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=r(19851),a=r(40958),l=r(79666),u=r(50357),c=r(57924),d=r(98553),h=r(55835),f=r(68708),m=r(39926),g=r(46891),p=r(42279),y=r(59455),v=r(40583),w=r(81168),S=r(44198),b=r(96706),P=r(34102),_=r(28283),E=r(81075),M=r(98778),C=r(10357);t.settingsToObj=function(e){const t={};for(const r of e)r.hasValue()&&(t[r.name]=r.value);return t},t.Setting=class{constructor(e){i.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,i,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const r=this.opts.whyInvalid?.(e);return null!=r?s(this,i,"m",n).call(this,e??t)+": "+r:null==this.fromEnv(e)?s(this,i,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const r=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=r)return r}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const r=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(r)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return E.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,p.tot)(this.optsOverrides.defaultValue)??(0,p.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,p.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const r=e??(0,S.env)(),i=t??this.value;return null!=i&&(r[this.key]=this.toEnv(i)),null==e&&b.caseInsensitiveEnv.unset(),r}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const r=e??(0,S.env)(),i=this.toEnvValue(t);return null!=i&&(r[this.key]=i,null==e&&b.caseInsensitiveEnv.unset()),r}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const r of t.delete(e)??[])delete process.env[r];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],C.WrapComments);function r(e,r){(0,a.isEmpty)(r)||t.push(...(0,w.wrap)(["",(1===r.length?e:(0,g.pluralize)(e))+": "+(0,c.orList)(r.map((e=>(0,d.stringify)(e))))],C.WrapComments))}r("alias",this.opts.aliases),r("environment alias",this.altKeys);for(const[e,r]of(0,f.entries)(this.addToJSON())){const i=Array.isArray(r)?(0,c.orList)(r.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(r);t.push(...(0,w.wrap)(["",e+": "+i],C.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Example value:"],key:this.name,value:(0,p.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Default value:"],key:this.name,value:(0,p.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,p.tot)(this.fileValue)}),e}},i=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const i=r(50989);t.SettingCategories=(0,i.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const i=r(58587),n=r(51168),s=r(76760),o=r(19851),a=r(40958),l=r(76790),u=r(22573),c=r(42659),d=r(73722),h=r(68708),f=r(50989),m=r(12168),g=r(54993),p=r(37975),y=r(9092),v=r(40583),w=r(79840),S=r(7282),b=r(12801),P=r(4328),_=r(70488),E=r(84248),M=r(5531),C=r(99315),T=r(34365),x=r(34580),D=r(96706),k=r(50274),O=r(33866),I=r(52086),A=r(48584),F=r(45969),N=r(43334),L=r(24540),R=r(70379),j=r(71300),B=r(33209),V=r(48987),z=r(68268),W=r(61208),q=r(99023),U=r(30577),G=r(1485),H=r(19861),J=r(55111),K=r(30933),$=r(22859),Y=r(71988),Z=r(38483),X=r(90536),Q=r(75164),ee=r(10546),te=r(90967),re=r(67958),ie=r(55948),ne=r(57039),se=r(9945),oe=r(74589),ae=r(844),le=r(96093),ue=r(23561),ce=r(69005),de=r(87652),he=r(81075),fe=r(58305),me=r(57571),ge=r(72564),pe=r(80372),ye=r(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new pe.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new pe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new pe.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,p.noColor)()}),logContextLimit:new oe.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new pe.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>G.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:G.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>G.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>N.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new pe.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new pe.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,F.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new ge.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:J.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!N.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new i.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>N.isMac?"100ms":N.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new pe.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:E.AutoVacuumModes,defaultValue:E.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:C.RepairModes,defaultValue:C.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,F.isDocker)()}),skipHealthCheckIds:new ge.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new pe.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>N.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new pe.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:U.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new pe.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new pe.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new pe.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,K.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:k.SidecarExts,defaultValue:k.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new pe.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ie.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:re.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,K.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:I.CropStrategies.attention,strEnum:I.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(N.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:A.SharpFailOns.truncated,strEnum:A.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>V.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:R.DateTagFormats.ym,strEnum:R.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:q.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,F.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,r]of(0,h.entries)(t.Settings))r._setName(e);function be(e){const r=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,F.isDocker)()&&r.unshift("/opt/photostructure/tools/bin"),r.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(r).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,D.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const r of(0,t.persistedSettings)()){for(const t of r.names)e.set(t,r);for(const t of r.keys)e.set(t,r)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,g.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const i=r(19851),n=r(31586),s=r(7282),o=r(49776),a=r(46292),l=r(32774),u=r(55086),c=r(46296),d=r(55939),h=r(96706),f=r(83278),m=r(92234),g=r(45969),p=r(60865),y=r(30933),v=r(15674),w=r(28874);t.setSettingsDefaults=(0,i.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,g.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=p.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const i=r(76760),n=r(40958),s=r(22573),o=r(98553),a=r(55835),l=r(59455),u=r(19851),c=r(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function h(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",i.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const r=t.split("|");for(const t of r)e.set(t,r)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const i=r(40958),n=r(98553),s=r(55835),o=r(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,i.uniq)(e)))),fromEnv:t=>{return r=t,n=e.strEnum,(0,i.compact)((0,o.splitStringArray)(r)?.map((e=>n.getCI(e))));var r,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const i=r(22573),n=r(81168),s=r(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,i.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const i=r(76760),n=r(55835),s=r(46292),o=r(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,i.join)(e,o.SettingsToml)))}},80496:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const i=r(50989);t.TagInferenceSettingValues=(0,i.strEnum)("never","always","auto")},6707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const i=r(90858),n=r(44652),s=r(22573),o=r(76850),a=r(50213),l=r(81168),u=r(84542),c=r(17217),d=r(68284),h=r(98778);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,i.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const i=r(22573),n=r(96249),s=r(98553),o=r(68708),a=r(51926);function l(e,t,r){if((0,i.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,i.blank)(r?.prefix)?[n]:(0,a.wrap)(n.split("\n"),r)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,i.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},65162:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const i=r(4001),n=r(81168);t.bname=function(e,t=!0){let r=(0,n.isString)(e)?e:e.name;return t&&(r=(0,i.stripCopySuffixFromName)(r)),r=(0,n.trimLeftPadding)((0,i.stripDSC)(r)),r.toLowerCase().normalize()}},70379:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const i=r(50989);t.DateTagFormats=(0,i.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},68268:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const i=r(50989);t.KeywordReparentingStrategies=(0,i.strEnum)("move","copy","retain")},61208:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const i=r(50989);t.NameTagFormats=(0,i.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const i=r(50989);t.NameTagOrders=(0,i.strEnum)("western","eastern")},60865:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const i=r(37805),n=r(30577);t.channel=function(){return(0,n.extractUpdateChannel)(i.version)},t.baseVersion=()=>[i.versionMajor,i.versionMinor,i.versionPatch].join("."),t.versionMajorMinor=i.versionMajor+"."+i.versionMinor},30577:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const i=r(50989);t.UpdateChannels=(0,i.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const r of t.UpdateChannels.values)if(e.includes("-"+r))return r;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},1485:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const i=r(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,i.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69375:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const i=r(19851),n=r(22573),s=r(50213),o=r(9103),a=r(7282),l=r(29882),u=r(43334),c=r(28874),d=(0,i.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,g=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function p(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),r=t[0],i=t[t.length-1];return c.Settings.excludedRootDirectories.has(r)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(i)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===r&&!1===m?.test(e)?"LinuxRunRE":!0===g?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=p(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=p},63870:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const i=r(42659),n=r(12168),s=r(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/i.secondMs},55111:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const i=r(50989);t.HelmetPlugins=(0,i.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},30933:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=i(r(48161)),s=r(19851),o=r(42659),a=r(31586),l=r(50213),u=r(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),r=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??r)),meta:{availableParallelism:e,cpuInfoLength:r}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=i(r(48161)),s=r(19851),o=r(31586),a=r(12168),l=r(50213),u=r(45879),c=r(70417),d=r(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),r=(2*e+t)/3;if((0,d.isDocker)()){const i=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(i))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([i,r]),meta:{freemem:e,totalmem:t,cgroupMem:i}})}return h().tap({msg:"estimatedFreeMem() ",result:r,meta:{result:(0,a.fmtBytes)(r),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},15674:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const i=r(19851),n=r(42659),s=r(41400),o=r(31586),a=r(12168),l=r(50213),u=r(7282),c=r(34102),d=r(57902),h=r(28874),f=r(30933),m=r(58444),g=r(22751),p=(0,i.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,i.lazy)((()=>{const e=(0,o.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*a.MB;return p().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,r=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return p().tap({msg:"timeoutPenalization()",level:r>1?d.LogLevels.warn:d.LogLevels.debug,result:r,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,i.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const r=g.timeoutRate.prior()?.eventsPerMinute??0,i=w();if(1!==i){const e=t;t*=i,p().warn("Recent timeouts! Throttling down.",{penalization:i,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),p().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:i,timeoutsPerSecond:r,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,i.lazy)((function(){return(0,o.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const i=r(58587),n=r(87997),s=r(19851),o=r(42659),a=r(41400),l=r(50213),u=r(7282),c=r(45255),d=r(34102),h=r(976),f=r(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new i.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const g=(0,s.lazy)((()=>(0,n.setInterval)(p,o.minuteMs).unref()));function p(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),g()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),p()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const i=r(76790),n=r(22573),s=r(50357),o=r(98553),a=r(49769),l=r(34666),u=r(30976),c=r(42279),d=r(32639),h=r(59455),f=r(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function g(e){return null==e||0===(0,h.toA)(e).length}function p(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,r)=>e===t[r]))}function v(e,t){for(let r=0;r=e.length||r>=e.length)return e;const i=e[t];return e.splice(t,1),e.splice(r,0,i),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&(0,a.getOrSet)(r,e,(()=>i))}return[...r.values()]}function P(e,t,r=1,i=(e=>e)){const n=[];if(et;s-=r)n.push(i(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=g,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,r){return m(e)?t(e):(0,c.tot)(r)},t.toPrimitive=p,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let r=0;rt.includes(e)))},t.includesAll=function(e,t){if(g(e)||g(t))return!1;for(const r of t)if(!e.includes(r))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const r=(0,i.sortBy)(e,p),n=(0,i.sortBy)(t,p);return r.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const r of t)null==r||e.some((e=>(0,s.eql)(e,r)))||e.push(r);return e},t.pushUniqBy=function(e,t,r){const i=e.map(r);for(const n of t){const t=r(n);i.includes(t)||(e.push(n),i.push(t))}return e},t.insertAt=function(e,t,...r){return e.splice(t,0,...r),e},t.insertUniq=function(e,t,r){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let i=0;i0)return e.splice(i,0,t),e}return e.push(t),e},t.remove=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),r!==e.length},t.removeSame=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>e!==t)))),r!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const r of e)null==r||(0,s.eql)(t[t.length-1],r)||t.push(r);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const r=[];for(const e of(0,i.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))r.some((t=>t.includes(e)))||r.push(e);return(0,i.sortBy)(r,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&r.set(e,i)}return[...r.values()]},t.uniqBy2=function(e,t){const r=[];for(const i of e)null!=i&&r.every((e=>!t(i,e)))&&r.push(i);return r},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,r,i)=>e+(t(r,i)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,r,i)=>e+t(r,i)),0)},t.firstMatch=function(e,t){for(const r of S(t)){const t=e.exec(r);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let r=0;for(;e[r]===t[r];)r++;return r},t.anneal=function({array:e,expense:t,allowedDelta:r}){const i=Math.round(r);if(i<2)return e;for(let r=0;re)){return P(e,t,1,r)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,r,i=t.primitiveValueOfOrElse){const n=new Set(r.map(i));return e.filter((e=>!n.has(i(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const i=r(40958),n=r(36783),s=r(41801),o=r(98553),a=r(49769),l=r(55835),u=r(34666),c=r(59455);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const r=new Map;for(const i of e)(0,a.getOrSet)(r,(0,o.stringify)(t(i)),(()=>i));return f(r.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,l.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,i.compact)(e),i.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,r)=>0===r||t>=e[r-1]))},t.sortedBy=function(e,t){return e.every(((r,i)=>0===i||t(r)>=t(e[i-1])))},t.sortBy=f,t.deepSortBy=function e(t,r){return f(t,r).map((t=>(0,s.isIterable)(t)?e(t,r):t))},t.pushSorted=function(e,t,r){const i=e.findIndex((e=>r(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const i=r(32639);t.asPromise=async function(e){const t=await e;return(0,i.isFunction)(t)?t():t}},5233:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const i=r(41400),n=r(31586),s=r(13538),o=r(41583);t.retryOnReject_=async function(e,t){const r=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return r();const a=t.onRetryWaitUntil??(e=>(0,i.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await r()}catch(e){const r=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(r)||l>t.maxRetries)throw r;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},22573:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const i=r(55835),n=r(42279),s=r(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const r=(0,s.toS)(e);return a(r)?t(r):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const r=(0,s.toS)(e).trim();return r.length>0?r:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,r){return(0,i.orElse)(l(e,t),r)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function r(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function i(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const r=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(r)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=r,t.toBoolean=function(e){return!!r(e)||!i(e)&&void 0},t.toNotBoolean=function(e){return!r(e)&&(!!i(e)||void 0)},t.boolToInt=function(e){return r(e)?1:0},t.isFalse=i,t.isDisabled=function(e){return i(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>r(e)))},t.and=function(e){return e.every((e=>r(e)))},t.maybeAnd=function(e){let t;for(const r of e){if(!1===r)return!1;!0===r&&(t=!0)}return t},t.mapBoolean=function(e,t){return r(e)?t(!0):i(e)?t(!1):void 0},t.mapTrue=function(e,t){return r(e)?t():void 0}},79666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const i=r(98553);t.clone=function(e){return null==e?e:JSON.parse((0,i.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const i=r(40958),n=r(22573),s=r(30301),o=r(55835),a=r(31586),l=r(39926),u=r(51926),c=r(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function g(e){return e instanceof Date}function p(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=g,t.thisYear=function(){return(new Date).getFullYear()},t.ago=p,t.hence=function(e,t){return p(-e,t)},t.unixtime=function(e){const r=g(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(r/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,r={includeMs:!0}){const i=Math.floor(e/t.hourMs);e-=i*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(i)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(r.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const r=()=>{const e=t%100;return t=Math.floor(t/100),e},i=10*r(),n=r(),s=r(),o=r(),a=r(),l=r();return new Date(t,l-1,a,o,s,n,i)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,r="ago"){return e<1e3?"just now":(r=(0,n.blank)(r)?"":(0,u.ensurePrefix)(r," "),et.ms<=e)))){const s=Math.floor(e/i.ms);e-=s*i.ms,s>0&&(i.ms>=t.dayMs?r:n).push(s+i.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+r.join("")+((0,i.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=g(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const i=r(38639),n=r(73872);function s(e,t,r){if(null==r||y(e)||y(t))return null;const i=r.get(e)?.get(t);return"boolean"==typeof i?i:null}function o(e,t,r,i){if(null==r||y(e)||y(t))return;let n=r.get(e);null!=n?n.set(t,i):(n=new WeakMap,n.set(t,i),r.set(e,n))}function a(e,t,r,i){if(null!=r?.comparator)return u(e,t,r,i);const n=l(e,t);return null!==n?n:u(e,t,r)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,r,i){r??(r={});const u=!1===r.memoize?void 0:r.memoize??(r.memoize=new WeakMap),d=r?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const r=d(e,t,i);if(!1===r||!0===r)return o(e,t,u,r),r;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,r,i){switch(r){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return g(e,t,["name","message","code"],i);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,i);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,r){return c(h(e),h(t),r)}(e,t,i);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),i);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),i);case"Set":case"Map":return function(e,t,r){if(e.size!==t.size)return!1;if(0===e.size)return!0;const i=[],n=[];return e.forEach((function(e,t){i.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(i.sort(),n.sort(),r)}(e,t,i);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return p(e,t,i)}}(e,t,y,r);return o(e,t,u,v),v}function c(e,t,r){const i=e.length;if(i!==t.length)return!1;if(0===i)return!0;let n=-1;for(;++n{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,r,i=!1;const n=function(){if(i){if(null!=r)throw r;return t}try{return i=!0,t=e()}catch(e){throw r=e,e}};return n.prior=()=>t,n.hasPrior=()=>i,n}},41400:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const i=r(42659),n=r(35556),s=r(31586),o=r(68708);function a(e,t=!0){return new Promise((r=>{if(e<=0)r();else{const s=setTimeout((()=>r()),Math.ceil(e+.5));e>i.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const r=Math.max(1,Math.ceil(t)),s=n.isNode&&r<=1?setImmediate(e):setTimeout(e,r);return n.isBrowser||t<=i.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},50357:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const i=r(12487),n=r(68708),s=r(34666),o=r(32639);function a(e,t){return(0,i.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const r of(0,n.keys)(e))if(!a(e[r],t[r]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,r){if(null==e||null==t)return e===t;if(null!=r){const i=d.get(r);if(null!=i)return i(e,t)??null}for(const r of c){const i=r(e,t);if(null!=i)return i}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(31586),a=r(68708),l=r(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const r=[];for(const t of e)null!=t&&(t instanceof Error?r.push(u(t),c(t),t?.message):r.push((0,l.toS)(t)));return(0,i.uniq)((0,i.compactBlankish)((0,s.flatten)((0,i.compact)(r).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const r=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,i.isEmpty)(r)?["(missing stack)"]:r}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},96249:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const i=r(59455);t.flatten=function(e,t=[]){for(const r of(0,i.toA)(e))if(null!=r)for(const e of(0,i.toA)(r))null!=e&&t.push(e);return t}},57924:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const i=r(40958);function n(e,t){return null==(e=(0,i.uniq)((0,i.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},73722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const i=r(50989);t.FitSizes=(0,i.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,i.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const i=r(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,r){if((0,i.lt0)(t))return[...e].slice(t,r);const n=e[Symbol.iterator]();if((0,i.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,r){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(r))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],r=[];return function e(i,n){if((0,isFunction_1.isFunction)(i))return;let s,o,a,l=toJSON(i);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(i===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let i=0;t.Latch=class{constructor(e=i++){this.id=e,this[r]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},r=Symbol.toStringTag},30301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const i=r(40958),n=r(50357),s=r(31586),o=r(65812);t.lazy=function(e,t){let r,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return r=Date.now(),async function(e,r){if((0,i.isEmpty)(l))return;const s=await e,a=await r;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==r||(0,s.gt0)(t)&&r+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,r){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const i=r();return null!=i&&e.set(t,i),i}},t.deleteIf=function(e,t){for(const[r,i]of e.entries())t(r,i)&&e.delete(r)}},55835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const i=r(42279),n=r(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,r){return null==e||null==t?void 0:r(e,t)}function a(e,t){return null!=e?e:(0,i.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,r,i){return null==e||null==t||null==r?void 0:i(e,t,r)},t.orElse=a,t.mapOr=function(e,t,r){return null!=e?t(e):(0,i.tot)(r)},t.map2Or=function(e,t,r,i){return a(o(e,t,r),i)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const i=r(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,i.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const i=r(40958),n=r(76790),s=r(50357),o=r(98553),a=r(49769),l=r(55835),u=r(51926),c=r(59455);class d{static fromJSON(e){const t=new d;for(const[r,i]of Object.entries(e))t.add(r,...i);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,i.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const r=(0,a.getOrSet)(this.store,e,(()=>[]));return r.push(...t),r}addUniq(e,...t){return(0,i.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const r=this.store.get(e);if(null==r)return!1;{const i=r.filter((e=>!(0,s.eql)(e,t)));return 0===i.length?this.store.delete(e):this.store.set(e,i),r.length!==i.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,i.uniq)(t))){for(const t of this.keys()){const r=this.store.get(t),n=null==r?[]:e(t,r);(0,i.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,i.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield[t,r])}()}tuples(){const e=this;return function*(){for(const[t,r]of e.store.entries())for(const e of(0,c.toA)(r))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[r,n]of this.store.entries()){const s=(0,i.findIndexes)(n,(t=>!e(r,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(r)}return t}inverse(){const e=new d;for(const[t,r]of this.store.entries())for(const i of r)e.add(i,t);return e}findKeyByTuple(e){for(const[t,r]of this.tuples())if(e(t,r))return t}filterKeysByTuple(e){const t=[];for(const[r,i]of this.entries())i.some((t=>e(r,t)))&&t.push(r);return t}toJSON(){const e={};for(const[t,r]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=r;return e}}function h(e,t){const r=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>r.add(t,e))))),r}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const r=h(e,t);return(0,n.sortBy)((0,c.toA)(r.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const r=globalThis;t.isBrowser="object"==typeof r?.window&&"object"==typeof r?.document,t.isNode="string"==typeof r?.process?.versions?.node},31586:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const i=r(76790),n=r(22573),s=r(42279),o=r(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,r)=>a(t)&&a(r)&&e(t,r);function f(e,r,n){return!(null==n||!a(n))&&([e,r]=(0,i.sort)([e,r]),(0,t.lte)(e,n)&&(0,t.gte)(r,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function p(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return p(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const r=Math.pow(10,t);return P(e*r)/r}function E(e,t,r){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${r})`);return a(r)?rt?t:r:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,r=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(r>=1)return!1;const i=(0===t?1e-5:t)*(1-r);return f(t-i,t+i,e)},t.within=f,t.max_=function(...e){let t;for(const r of e)a(r)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const r=y(e);return null==r?void 0:t(r)},t.mapFloat=function(e,t){const r=v(e);return null==r?void 0:t(r)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,r){return b(e,(e=>b(t,(t=>r(e,t)))))},t.mapNumericOr=function(e,t,r){return a(e)?t(e):r},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const r=t-P(Math.ceil(Math.log10(Math.abs(e)))),i=Math.pow(10,Math.abs(r));return r<0?P(e/i)*i:P(e*i)/i},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!w(e))return[];const r=Math.round(e);return r<=0?[]:[...Array(r)].map(((e,r)=>t(r)))},t.pct=function(e,t){return E(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const r=Math.round(e??-1);return null==t||f(0,t,r)?r+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const r of e){if(!a(r))return;t+=r}return t}},68708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(32639),a=r(55835),l=r(31586),u=r(34666),c=r(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function g(e){return h(e).map((t=>e[t]))}function p(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const r of e)if(null!=r&&Array.isArray(r)){const[e,i]=r;null!=e&&void 0!==i&&("object"!=typeof t&&(t={}),t[e]=i)}return t}function v(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>null!=e)))return e;const r=t.filter((([,e])=>null!=e));return(0,i.isEmpty)(r)?void 0:y(r)}function w(e,t,r={}){return y((0,i.compact)((0,n.sort)(h(e)).map((r=>t(r,e[r])))).filter((([e,t])=>null!=e&&void 0!==t)),r)}function S(...e){const t=(0,i.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const r=t.filter(d);if(t.length!==r.length)return t;const n={};for(const e of(0,i.uniq)((0,i.flatMap)(r,h)))n[e]=S(...r.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const r=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(r.test(t))return{key:t,value:e[t]}}function P(e){return g(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const r=v(e);return m(r)?t(r):void 0},t.values=g,t.entries=p,t.fromEntries=y,t.assignFields=function(e,t,r){if(null==t)return e;for(const[i,n]of p(t))!0!==r?.omitKeys?.includes(i)&&(null==n&&!0!==r?.assignNullish||(e[i]=n));return e},t.assignUndefinedFields=function(e,t,...r){if(null==t)return e;for(const i of r){const r=t[i];void 0!==r&&void 0===e[i]&&(e[i]=r)}return e},t.assignAllFields=function(e,t){for(const[r,i]of p(t??{}))e[r]=i;return e},t.definedValues=function(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>void 0!==e)))return e;const r=t.filter((([,e])=>void 0!==e));return(0,i.isEmpty)(r)?void 0:y(r)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,i.compact)(t.map(e));{const r=(0,i.compact)(p(t).map((([t,r])=>(0,a.map)(e(r),(e=>[t,e])))));return 0===r.length?void 0:y(r)}}},t.compactBlankValues=function(e){if(null==e)return;const t=p(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,i.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickCompact=function(e,...t){if(null==e)return;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickNonBlank=function(e,...t){if(null==e)return e;const r={};for(const i of t){const t=e[i];(0,s.notBlank)(t)&&(r[i]=t)}return r},t.pickFirst=function(e,t,r=a.defined){if(null!=e)for(const i of t)if(r(e[i]))return e[i]},t.pickDeep=function e(t,...r){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...r)));const i={};function n(e,t){if(null==t)return;const r=i[e];i[e]=null==r?t:S(r,t)}for(const i of r){const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const i of h(t))((0,l.toInt)(i)??-1)>=0&&n(i,e(t[i],...r));return i},t.pluck=b,t.pluckDeep=function e(t,r){if(null==t||(0,s.blank)(r))return;if(Array.isArray(t)){const n=(0,i.compact)(t.map((t=>e(t,r))));return(0,i.isEmpty)(n)?void 0:{key:n[0].key,value:(0,i.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(r,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const r=p(e).filter((([e])=>!t.includes(e)));return(0,i.isEmpty)(r)?void 0:y(r)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(p(e).filter((([e,r])=>t(e,r))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,i.uniq)(t)},t.maybeCall=function(e,t,...r){const i=e?.[t];return(0,o.isFunction)(i)?i.bind(e)(...r):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const r=t.toLowerCase().normalize();for(const t of h(e))if(r===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const r=w(t,((t,r)=>[t,e(r)])),i=g(r);return 1===i.length?i[0]:r}},97790:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(r||(r={})),t.None=r;class i{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new i(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,r){return s(e).flatMap((e=>s(t).flatMap((t=>r(this.a,e,t)))))}zip3(e,t,r,i){return s(e).flatMap((e=>s(t).flatMap((t=>s(r).flatMap((r=>i(this.a,e,t,r)))))))}}function n(e){return e instanceof i||e===t.None}function s(e){return n(e)?e:null!=e?new i(e):t.None}t.Some=i,t.isOpt=n,t.opt=s},39926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const i=r(31586),n=r(54993),s={};function o(e,t){if(t<1)return"";if(!(0,i.gte)(s[e]?.length,t)){let r=s[e]??e;for(;r.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const i=r(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,i.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const i=r(40958),n=r(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,r){return o(e)?t(e):r()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,r){if(null==e&&null==r)return 0;if(null==e)return-1;if(null==r)return 1;const i=typeof e,s=typeof r;if(!("string"!==i&&"symbol"!==i||"string"!==s&&"symbol"!==s)){const i=(0,n.toS)(e),s=(0,n.toS)(r),o=i.localeCompare(s);return i[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(r)?u(e,r):i!==s?a.indexOf(i)-a.indexOf(s):e>r?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const i=r(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const r=await e;return null==r?void 0:t(r)},t.thenCollect=async function(e,t){const r=[];for(const n of(0,i.toA)(await e))if(null!=n){const e=await n;if(null!=e){const i=await t(e);null!=i&&r.push(i)}}return r},t.thenTap=async function(e,t=console.dir.bind(console)){const r=await e;return await t(r),r},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:r}){const i=await e;return t(i)?r(i):void 0}},57153:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const i=r(50989);t.PromiseStates=(0,i.strEnum)("pending","resolved","rejected")},30976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const i=r(40958),n=r(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,r){return null==r||0===r.length?s(e,t):a(e,t,1,r)[0]}function a(e,t,r,i){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(i??[]);if(t===e&&0===n&&0===o.size&&1===r)return[e];const a=n-o.size;if(r>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:r,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const r=Math.floor(Math.random()*(e+1));e!==r&&([t[e],t[r]]=[t[r],t[e]])}return t},t.sample=function(e,t){const r=[];for(const i of a(0,e.length,t))r.push(e[i]);return r},t.pickWeightedRandom=function(e){if((0,i.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let r=l(0,(0,i.sum)(t,(e=>e.priority)));return t.find((e=>(r-=e.priority,r<=0)))}},5670:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const i=r(50989);t.ServiceNames=(0,i.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const r=e.indexOf(t);return-1===r?[e]:[e.slice(0,r),e.slice(r+t.length)]}},50989:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const i=r(68708),n=r(42279);t.strEnum=function(...e){const t=Object.freeze(e),r=(0,i.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?r[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const r=o(e),i=o(t);return null==r||null==i?void 0:r>i?1:r{const r=o(e);return null==r?void 0:t[r]}}}},51926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const i=r(40958),n=r(17586),s=r(22573),o=r(96249),a=r(41801),l=r(31586),u=r(59455),c=r(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,r){if(d(e))return t<0&&(t+=e.length),e.slice(t,r);{const i=f();return null!=i?(0,a.sliceIterable)(i.segment(e),t,r).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,r).join("")}}function g(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function p(e,t){const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.startsWith(i)?r.slice(i.length):r}function y(e,t){if(null==t)return e;const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.endsWith(i)?r.slice(0,-i.length):r}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,r){null==r&&(r=e.length);for(let i=r;i>=0;i--)if(m(e,i).startsWith(t))return i;return-1}function b(e,t,{normalize:r=!0}={}){if(null==e||null==t)return!1;const i=(0,c.toS)(e),n=(0,c.toS)(t);return i.length===n.length&&(i===n||i.toLowerCase()===n.toLowerCase()||"function"==typeof i.localeCompare&&0===(r?i.normalize():i).localeCompare(r?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,i.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,r){return d(e)?e.slice(t,null==r?void 0:t+r):m(e,t,null==r?void 0:t+r)},t.charArr=g,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=p,t.stripPrefixes=function e(t,r){if(null==t)return"";const i=(0,c.toS)(t);for(const t of r)if(null!=t&&t.length>0&&i.startsWith(t))return e(i.slice(t.length),r);return i},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:r}){return y(p(e,t),r)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:r}){return w(v(e,t),r)},t.ellipsize=function(e,t=80,r=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),r=(0,l.clamp)(0,t-1,(0,l.round)(r));const i=g(e);return i.length<=t?i.join(""):i.slice(0,t-1-r).join("")+"…"+(r>0?i.slice(-r).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,r){const i=r?.maxLineLen??80,n=r?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const i=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(i.map((t=>e(t,r))))}if((t=v((0,c.toS)(t),n).trim()).length<=i)return[t];const s=S(t," ",i);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),r)];{const i=t.indexOf(" ",n.length+1);return i>0&&i{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const i=r(42659),n=r(68708),s=r(42279),o=r(83104),a=r(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,r=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(r,i)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,r(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,r(t))}catch(e){n&&(n=!1,i(e))}finally{clearTimeout(s)}}))}async function c(e,t,r=!0){const n=await u(e,t,r);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,r=!0){return u(e,t,r).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,r=!0){const i=t-Date.now();return i<=0?o.Timeout:u(e,i,r)},t.thenOrOnTimeout=async function(e,t,r){return t<=0?e:new Promise((async(i,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{i(await r())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),i(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,r=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(n)+")");return c(e,n,r)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:r,unref:i=!0}){if(null==e)return(0,s.tot)(r);const n=await u(e,t,i);return n===o.Timeout?(0,s.tot)(r):n}},42279:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const i=r(32639);t.tot=function(e){return(0,i.isFunction)(e)?e():e},t.tol=async function(e){return(0,i.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class r extends Error{}t.TimeoutError=r},12168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const i=r(22573),n=r(30301),s=r(31586),o=r(46891),a=r(50989),l=r(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let r=0;for(const i of e)(0,s.isNumber)(i)&&(r+=i/t.MB);return(0,s.round)(r)},t.fmt=c,t.fmtToInt=function(e){return(0,i.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const r=Math.floor(Math.log10(e)),i=Math.floor(r/3),n=Math.pow(10,3*i),o=d[i];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,r=3){return f(e*t.MB,r)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const r=Math.floor(Math.log2(e)),i=Math.floor(r/10),n=Math.pow(2,10*i),o=h[i];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,r){return null==e?"":(0,i.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(r??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,r){return r??(r=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:r}}},65812:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const i=r(68708);t.setUnrefTimeout=function(e,t){const r=setTimeout(e,t);return(0,i.maybeCall)(r,"unref")??r}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const i=r(41801),n=r(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,i.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const i=r(40958),n=r(23541),s=r(59455),o=r(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,i.compact)((0,s.toA)(e).map(a))}},54993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const i=r(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,i.stringify)(e)}}t.toStr=s},92636:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(6858),s=i(r(73024)),o=i(r(76760)),a=r(1708),l=r(37805),u=r(41269),c=r(80061),d=r(94361);function h(e){for(const t of["bin",__dirname]){const r=o.default.join(t,e);if(s.default.existsSync(r))return r}return console.error("failed to find command "+e),e}n.program.version(l.version),n.program.description("Welcome to PhotoStructure, your new home for all your photos and videos.\nSee https://photostructure.com/server/tools/ for details about these tools."),(0,d.verifyUidGid)(),(0,c.addHelpFooter)(n.program).command("main",u.CliDesc.main+" (default)",{isDefault:!0,executableFile:h("main.js")}).command("info",u.CliDesc.info,{executableFile:h("info.js")}).command("list",u.CliDesc.list,{executableFile:h("list.js")}).command("logcat",u.CliDesc.logcat,{executableFile:h("logcat.js")}).command("logtail",u.CliDesc.logtail,{executableFile:h("logtail.js")}).command("web",u.CliDesc.web,{executableFile:h("web.js")}).command("sync",u.CliDesc.sync,{executableFile:h("sync.js")}).parse(a.argv)},90858:e=>{e.exports=require("@iarna/toml")},58587:e=>{e.exports=require("batch-cluster")},6858:e=>{e.exports=require("commander")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}var __webpack_exports__=__webpack_require__(92636);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/sync.js b/bin/sync.js index 8c1209a..e6056d7 100755 --- a/bin/sync.js +++ b/bin/sync.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463:(e,t,i)=>{const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),w=m(y,f);return a(s,t,o,p,w)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),w=m(g,p);if(!l(s,w))throw new o("decryption failed");const v=await y(a,f,r.subarray(16));if(!v)throw new o("decryption failed");return v},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),w=u.subarray(32),v=await g(e,y,w),b=n(o,l,v,t,s),S=m(b,p);return a(o,t,l,v,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),w=p.subarray(0,32),v=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,w,v);if(!P)throw new o("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const s=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*s);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*s);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(s*t);case"day":case"days":case"d":return Math.round(864e5*s);case"week":case"weeks":case"w":return Math.round(6048e5*s);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*s)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227:(e,t,i)=>{const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120:(e,t,i)=>{const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827:(e,t,i)=>{const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015:(e,t,i)=>{const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function w(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...w(e.slice(i+1))]}function v(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function k(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return w(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=v,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await k(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),w=i(25764),v=i(38836),b=i(99331),S=i(95937),P=i(98314),M=i(38835),_=i(70025),T=i(8769),E=i(43334),D=i(95402),k=i(28874),x=i(63870);class F extends v.EndableWrapper{constructor(e,t,i=w.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>n(this,r,"m",s).call(this)),i,"worker"===e?(0,x.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,D.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,S.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+M.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&D.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,b.ending)()||!0===(0,_.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,T.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=F,r=new WeakSet,s=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(E.isWin?3:1)*c.minuteMs,maxTasksPerProcess:k.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:k.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:k.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,x.commandTimeoutMs)(),taskTimeoutMillis:k.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,s.set(this,void 0),n.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,s,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]=t))}get length(){return u(this,n,"f")}set length(e){l(this,n,(0,d.clamp)(0,u(this,n,"f"),e),"f")}clear(){this.length=0}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,n,"f")),e<0||e>=u(this,n,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,s,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,n,"f"){u(this,s,"f")[e]=c}));return u(this,n,"f")}pop(){return u(this,r,"m",o).call(this,u(this,n,"f")-1,(e=>{var t;return l(this,n,(t=u(this,n,"f"),--t),"f"),u(this,s,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,n,"f"){u(this,s,"f")[e]=c,l(this,a,e,"f")}));return u(this,n,"f")}shift(){return u(this,r,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,n,(i=u(this,n,"f"),--i),"f"),u(this,s,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",o).call(this,u(this,n,"f")-1-e,(e=>{const i=u(this,s,"f")[e];u(this,s,"f")[e]=u(this,s,"f")[t],u(this,s,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=n(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),s=i(31586),n=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),s=i(65843),n=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),s=i(20014),n=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)((()=>!1))},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),s=i(98553);var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},57206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(77988),s=i(51168),n=i(45599),a=i(98553),o=i(68708),l=i(24689),u=i(21330),c=i(57159),d=i(28544),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},19851:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function w(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(w()??await(m.isWin?P():m.isMac?_():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(w);const v=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=v.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function T(){return S(w((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),s=i(32105),n=i(14593);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),s=i(55835),n=i(59455),a=i(48884);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),s=i(54557);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),s=i(42659),n=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,s]of(0,l.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,l.keys)(e))if(r[n]=t(n,e[n]),s++,(0,o.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,n.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),s=i(73024),n=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),w=i(30933),v=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return F();case"win32":return C();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){v().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=T;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function k(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function F(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return k(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return v().warn("osNameMac(): unknown release",e),b()}}function C(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":k(e,D);return null!=t?`Windows ${t} (${e})`:(v().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=F,t.osNameWin=C,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,w.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(C())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},45393:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=4},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(72993),s=i(50213),n=i(23560),a=i(43334);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(85949).title=t}catch(e){(0,s.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},92782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),s=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),s=i(56409),n=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}async function w(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return s.promise}const v=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return w(...e)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),w(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),s=i(54993);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),w=i(34102),v=i(43334),b=i(24399),S=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,w.ee)().on("clearCache",(()=>T.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>v.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(v.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(1708)),n=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),s=i(57150),n=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,n.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,s.logStartup)())}},28850:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),s.set(this,void 0),n(this,r,e,"f")}_call(){return(0,l.time)(a(this,r,"f")+(null==a(this,s,"f")?"(local)":"(remote)"),null==a(this,s,"f")?this.impl():a(this,s,"f").call(this))}setShim(e){n(this,s,e,"f")}hasShim(){return null!=a(this,s,"f")}clearShim(){n(this,s,void 0,"f")}}r=new WeakMap,s=new WeakMap},12089:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=a,s.set(this,void 0),n.set(this,void 0),l(this,s,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",a).call(this,e),(()=>u(this,r,"m",o).call(this,e)))}setShim(e){l(this,n,e,"f")}hasShim(){return null!=u(this,n,"f")}clearShim(){l(this,n,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",a).call(this,e))}}s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,s,"f")+(null==u(this,n,"f")?"(local)":"(remote)"),null==u(this,n,"f")?this.impl(e):u(this,n,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return s(this,r,"f")[Symbol.iterator]()}get length(){return s(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=s(this,r,"f").length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),a=this.valueOf(s(this,r,"f")[n]);if(e===a)return{found:!0,index:n};e>a?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&s(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...s(this,r,"f")];const a=t=>t<0||t>s(this,r,"f").length-1?null:(i??this.diff)(s(this,r,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return s(this,r,"f").shift()}at(e){return(0,a.at)(s(this,r,"f"),e)}toA(){return[...s(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===s(this,r,"f").length-1){const e=[...s(this,r,"f")];return s(this,r,"f").length=0,e}return s(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return s(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),s=i(82328),n=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),s=i(95705);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const w=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" …(+"+s+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const v=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return v.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['‘’].*['‘’]$/,D=/^["“”„«»〃].*["“”„«»〃]$/;function k(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>w.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=k,t.splitUp=x,t.sortNaturalBy=F,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>F(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const C=/#.*$/gm;t.stripComments=function(e){return e.replace(C,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function w(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=v(i),t=v(r);return 2*b(e,t).length/(e.length+t.length)}))}function v(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=w,t.bigrams=v,t.nonUniqIntersection=b,t.lnsDiff=M;const _=/[^\da-z]+/gi;function T(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:w(e,t),lns:M(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),s=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},88264:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TTLArray=void 0;const r=i(31586);class s{constructor(e,t){this.ttlMs=e,this.maxLength=t,this.times=[],this.a=[],this.expirationListeners=[]}[Symbol.iterator](){this.vacuum();const e=[...this.a];return function*(){for(const t of e)yield t}()}push(...e){(0,r.times)(e.length,(()=>this.times.push(Date.now()))),this.a.push(...e),null!=this.maxLength&&this.vacuum()}pushUniq(...e){e.forEach((e=>{this.includes(e)||this.push(e)}))}includes(e){return this.vacuum(),this.a.indexOf(e)>=0}find(e){return this.vacuum(),this.a.find(e)}some(e){return this.vacuum(),this.a.some(e)}shift(){return this.vacuum(),this.times.shift(),this.a.shift()}first(){return this.vacuum(),this.a[0]}last(){return this.vacuum(),this.a[this.a.length-1]}shiftOrFirst(){return this.length>1?this.shift():this.first()}pop(){return this.vacuum(),this.times.pop(),this.a.pop()}onExpire(e){this.expirationListeners.push(e)}slice(e,t){return this.vacuum(),this.a.slice(e,t)}get length(){return this.vacuum(),this.a.length}clear(){return this.times.length=0,this.a.length=0,this}get values(){return this.vacuum(),[...this.a]}map(e){return this.vacuum(),this.a.map(e)}oldestEntryAge(){return this.vacuum(),this.times[0]}vacuum(){if(0===this.a.length)return;const e=this.a.length;if(null!=this.maxLength){const e=this.a.length-this.maxLength;this.times.splice(0,e),this.a.splice(0,e)}const t=Date.now()-this.ttlMs,i=this.times.findIndex((e=>e>t));if(-1===i?this.clear():i>0&&(this.times.splice(0,i),this.a.splice(0,i)),e!==this.a.length)for(const e of this.expirationListeners)e()}}t.TTLArray=s},75387:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},65211:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(19851),s=i(76790),n=i(22573),a=i(54993),o=i(7282),l=i(55222);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!(0,o.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),u=0}},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),s=i(55835),n=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},79184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(59455),s=i(48884),n=i(22859),a=i(28874),o=i(79781),l=i(92434);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(50357),o=i(55835),l=i(31586),u=i(68708),c=i(12168),d=i(23467),h=i(73168),f=i(50213),m=i(86580),p=i(48368),g=i(80361),y=i(28874),w=i(28544),v=i(75767),b=i(16170),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} ≠ ${o}`}function M(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function _(e,t){return[M(e),M(t)]}function T(e,t,i){const r=(0,v.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.aKey}:${r.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=w.CapturedAt.fromAssetFile(e),f=w.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const M=a.isFuzzy||f.isFuzzy;if(M&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",_)??P(e,i,"model",_);if(null!=E)return E;const D=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),k={cameraId:T(e,i,"cameraId")??null,imageId:T(e,i,"imageId")??null,lensId:T(e,i,"lensId")??null,exposureSettings:(0,v.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(D,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(D)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:k});const x=(0,s.compact)((0,u.values)(k));if((0,s.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:M});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(k).filter((e=>null==k[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos ≠ images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=E(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},13991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(19851),s=i(55835),n=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function w(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function v(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([w(e),v(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=w,t.assetFileStatFields_=v,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),w=i(14036),v=i(45200),b=i(34238),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=T;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,F).reverse()}function k(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,w.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function F(e){const t=k(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=k,t.assetFileSortFields=x,t.assetFileSortCriteria=F,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,v.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),s.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,n(this,s,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return n(this,s,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,n(this,s,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=n(this,r,"f")&&clearTimeout(n(this,r,"f")),a(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,s=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(87997)),n=i(31586);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const w=y(i(87997)),v=y(i(57975)),b=i(45599),S=i(26905),P=i(55835),M=i(31586),_=i(68708),T=i(20214),E=i(57153),D=i(85556),k=i(50213),x=i(70025),F=i(95937),C="TIMEOUT",A=(0,b.defer)((()=>(0,k.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,M.gt0)(t)?new s(C).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const s=i[r];if(s.isSettled){if(s.name===C)return void A().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield s.value}}if(i.every((e=>e.name===C)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,k.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[v.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(w.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,M.gt0)(e)&&(g(this,h,w.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,F.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,s=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),w.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},83412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DoneWrapper=void 0;const r=i(56409),s=i(38836);class n extends s.EndableWrapper{constructor(){super(...arguments),this.doneLatch=new r.Latch}isDone(){return this.doneLatch.isSettled()||this.ended}donePromise(){return this.doneLatch.promise}}t.DoneWrapper=n},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>v()),10*n.minuteMs);const y=5*n.secondMs;async function w(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function v(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>w(e))))},t.end=w,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),v();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>w(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,s.compact)(g.valuesFlat()).map((e=>w(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class w extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=w,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,s=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function w(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=w,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{w({reason:`${e}:${t}`,status:0,error:i})}))}))},39250:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(23838),a=i(54993),o=i(15674),l=i(73568),u=i(76740),c=i(99331),d=i(42638);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new d.Promises(e,t)}vacuum(){return s(this,r,"f").filterInPlace(((e,t)=>t.isPending&&!0!==t.payload?.aborted)),s(this,r,"f").valueCount()}enqueue({key:e,abortable:t,fn:i}){for(const t of s(this,r,"f").get(e)??[])t.payload?.abort("aborted by new work");if(this.vacuum(),(0,c.ending)())throw new l.AbortError("ending");const n=t??new u.Abortable,o=this.p.serial((0,a.toS)(e),(()=>i(n)),n);return s(this,r,"f").add(e,o),o}},r=new WeakMap},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),w=i(22911),v=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new b(e,t,i,r)};class b extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,n,0,"f"),d(this,s,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,r,"m",u).call(this,w.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,n,"f")}isStale(){return null==c(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,s,"f")?void 0:Date.now()-c(this,s,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(v().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,n,(i=c(this,n,"f"),++i),"f")}},u=function(e){d(this,s,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof w.Deferred?e:new w.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),s=i(80049);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},22781:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),s.set(this,!1),n.set(this,!1)}_call(){return a(this,s,"f")?(o(this,n,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,r,"f")):(o(this,s,!0,"f"),o(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,s,!1,"f"),!0===this.runLaterIfBusy&&a(this,n,"f")&&(o(this,n,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,s,"f")}prior(){return a(this,r,"f")}async force(){return await a(this,r,"f"),this._call()}}r=new WeakMap,s=new WeakMap,n=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),w=i(15674),v=i(42638);var b=i(20214);async function S(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,l.gt0)(s)?(0,c.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function _({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,w.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:n});const u=a??(o.length<=s?v.PermissivePromises:new v.Promises(i,(()=>s))),d=(0,l.gt0)(n)?e=>(0,c.thenOrTimeoutError)(t(e),n):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=S,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await S(s);r.push(...await S(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await _({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){s=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await _({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),w=i(25764),v=i(38836),b=i(73614);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new v.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),w.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},42638:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),w=i(54993),v=i(89788),b=i(82647),S=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,w.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new v.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},59189:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(1708)),n=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),w=i(50213),v=i(7282),b=i(88158),S=i(45969),P=i(43334),M=i(28874),_=i(3790);function T(e){return E().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const E=(0,n.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(M.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,b.sortedKeys)((0,l.filter)((0,d.env)(),(e=>T(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,M.allSettings)())t.watchLater(e)}));const D=["HOME","LANG","USER"],k=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?D:k),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,M.pathWithDefaults)(),e}));function F(e){const t={NODE_ENV:(0,v.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,S.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,M.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,o.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(s.default.env,(e=>T(e)||!(0,_.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=F,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:A({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let C=!1;function A({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,g.childProcLocale)():{},...F(r),...e??{}});for(const e of(0,M.transientSettings)())e.deleteFromEnv(s);if((0,y.isLogged)("debug")&&!C){C=!0;const e=(0,w.mkLogger)("child.ChildEnv"),t=(0,l.entries)(s).map((([e,t])=>[e,(0,_.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>T(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return s}t.childEnv=A},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),w=i(79089),v=i(45255),b=i(22911),S=i(4867),P=i(73614),M=i(70025),_=i(57159),T=i(36868),E=i(66184),D=i(45643),k=i(95402),x=i(9727),F=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function C(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function A(e,t=30*u.secondMs){if(null==e)return!1;F().debug("endProcess()",C(e));const i=e.pid;if(null==i||i<=0)return F().warn("endProcess(): asked to end invalid pid",C(e)),!1;if(i===n.default.pid)return F().warn("endProcess(): asked to end MY pid",C(e)),!1;if(i===n.default.ppid)return F().warn("endProcess(): asked to end my parent pid",C(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();F().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,k.killPid)(i).catch((e=>{F().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,D.waitForPidExit)(i,t))return F().debug("endProcess(): exitted",C(e)),!0;{k.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");F().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,k.killPid)(i,!0).catch((e=>{F().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,D.waitForPidExit)(i,5e3)}function I(e,i,r,s=0){const a=new Date,o=[];return(0,w.niceable)(i,r)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,w.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&A(e)}),s-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,k.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,E.isLogged)("trace",F().context)?F().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):F().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new b.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,T.endStream)(a.stdin);const w=new d.Latch;null==a.stdout?w.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>w.resolve())));const P=new d.Latch;null==a.stderr||s?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),F().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,S.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),F().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:w.state(),stderr:P.state()}),await(0,S.thenOrTimeoutError)({p:w.promise,timeoutMs:v.ShortCommandTimeoutMs,halt:i.halt}),await(0,S.thenOrTimeoutError)({p:P.promise,timeoutMs:v.ShortCommandTimeoutMs,halt:i.halt});const E=p.join("");(0,l.notBlank)(E)&&g.push(new Error(E)),!r&&(0,o.isNotEmpty)(g)&&F().warn(f+" resulted in errors:",g);const D=i.isIgnorableError??M.isIgnorableError,k=g.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new _.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!n&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:E}}catch(e){throw F().error("stdoutResult_() failed",e),await(0,k.killPid)(a.pid,!0),e}}t.endProcess=A,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return F().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return F().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},86335:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(77598),u=o(i(1708)),c=i(19851),d=i(40958),h=i(22573),f=i(50268),m=i(68708),p=i(5670),g=i(50989),y=i(12168),w=i(59455),v=i(41583),b=i(54993),S=i(80875),P=i(50213),M=i(81168),_=i(27395),T=i(25764),E=i(59958),D=i(70025),k=i(83278),x=i(85021),F=i(29325),C=i(43334),A=i(28874),I=i(84777),O=i(55534),L=i(85100),R=i(34330),N=(0,c.lazy)((()=>(0,P.mkLogger)("child.ChildService")));async function B(e){const t=(0,M.ensureSuffix)(e,".js"),i=k.BaseFile.projectRoot(),r=k.BaseFile.for(u.default.cwd()),s=(0,F.isPacked)()?[i.join("bin",t),C.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];(0,F.isPacked)()||(C.isElectron?(s.push(r.join("dist","app",t)),s.push(i.join("src","desktop","dist","library",t))):s.push(i.join("src","library","dist","library",t)));for(const e of s)if(null!=e&&!0===await e.isNonEmptyFile((0,F.isPacked)()?y.KB:128))return N().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:F.isPacked,paths:s.map(b.toS)}});return N().throw("Failed to find path to "+e,{paths:s,fatal:!0})}t.pathToService=B,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=(0,g.strEnum)(...p.ServiceNames.pick("web","sync"));class j{static async mk_(e,t={}){const i=t.pathToService??await B(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,w.toA)(t.nodeArgs),new j(e,i,t)}constructor(e,t,i){var o,l;r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,L.serviceExitTimeoutMs)(e),this.logger=(0,P.mkLogger)(this.name);const c=[...(0,w.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&c.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale","forWorker"),this.spawnOpts.forceCLocale=!1,(l=(o=this.spawnOpts).env??(o.env={}))[E.UV_THREADPOOL_SIZE]??(l[E.UV_THREADPOOL_SIZE]=(0,b.toS)(("web"===e?A.Settings.webUvThreads:A.Settings.syncUvThreads).valueOrDefault)),this.wc=new R.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&await(this.opts.onPreRestart?.()),this.restartCount++,(0,I.spawn)(u.default.execPath,c,-1,this.spawnOpts)),endableRank:T.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:a(this,r,"m",n).bind(this),onStderr:a(this,r,"m",s).bind(this),onError:this.opts.onError??(e=>!1===(0,D.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:O.ServiceExitCommand,...i}),(0,_.addEndable)(T.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(x.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(O.ServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,M.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,v.toErr)(i)),this.write(e,t-1)}}}t.ChildService=j,r=new WeakSet,s=function(e){const t=(0,S.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},n=function(e){if(!(0,h.blank)(e))try{const t=(0,S.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){const e="failed"===t.state||"error"===t.level;this.logger.log(e?"error":"info",".onStdout(): health check summary",t),e&&this.wc.onError(this.name+".onStdout()",t,e)}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),s=i(41400),n=i(19851),a=i(28874);(0,s.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,n.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},85100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(23560),s=i(28874),n=i(45255);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?s.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},34330:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),w=i(54993),v=i(27395),b=i(25764),S=i(99331),P=i(42638),M=i(38835),_=i(8769),T=i(57159),E=i(66003),D=i(50213),k=i(45643),x=i(28874),F=i(84777);t.mkBasicWatchedChild=function(e){return new C({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,F.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class C{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,v.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=C,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,k.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,F.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,w.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),s=i.sibling(r);if(s.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",s.posixPathFrom((0,l.examples)()));const n=(0,d.originalsDir)();if(s.isSelfOrDescendantOf(n))return a.join("$library",s.posixPathFrom(n));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",s.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(6858),a=i(1708),o=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return s(this,r,"f").push(...e),this}async parse(e=a.argv,t){let i=(0,m.addHelpFooter)(new n.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of s(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":o.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,a.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of s(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),s=i(38639),n=i(17181),a=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,s.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),a.Settings.logColor.envValue=e,(0,n.setupLogFormatter)()}))}}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(1708)),n=i(22573),a=i(38639);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},53978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},43380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(28874),s=i(2858),n=i(22573),a=i(38639),o=i(46292);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},54772:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),w=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function v(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void w().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void w().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(v)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=v,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(v(e))}function y(e){return(0,f.clampRGB)(T(_(e)))}function w(e){return(0,t.LabBitZip)().clampValue(e)}function v(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return w([116*i-16,500*(t-i),200*(i-r)])}function _(e){const[t,i,r]=w(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=T,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function k(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function F(e){return C(x(e))}function C(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function A(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function I(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(D,e,(()=>k(e,t))):k(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return F((0,f.rgbhex2triplet)(e))},t.rgb2hsl=F,t.hsl2rgb=function(e){return I(A(e))},t.hsv2hsl=C,t.hsl2hsv=A,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},42079:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(31586),s=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),w=(0,s.sqrt)(g*g+h*h);let v=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);v+=2*(v<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=w-y;let M=y*w==0?0:b-v;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,s.sqrt)(y*w)*Math.sin(M/2),T=(i+c)/2,E=(y+w)/2;let D;y*w==0?D=v+b:(D=(v+b)/2,D-=(Math.abs(v-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const k=(T-50)**2,x=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),F=1+.015*k/(0,s.sqrt)(20+k),C=1+.045*E,A=1+.015*E*x,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*I)*O;return(0,s.sqrt)(Math.pow(S/(n*F),2)+Math.pow(P/(a*C),2)+Math.pow(_/(o*A),2)+L*P/(a*C)*_/(o*A))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(40958),s=i(31586),n=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},32848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(48884),o=i(31843),l=i(70417),u=i(3048);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},40401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),w=i(85810),v=i(3048),b=i(76490),S=i(1971),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,w.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??v.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,w.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function k(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const F=f.length<=g?[]:(0,s.compact)(M.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...T,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&k(g-1);const n=s.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,w.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n),2);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:F.map((e=>(0,u.pick)(e,"description","score")))});const C=(0,c.leastBy)(F,(e=>e.score));if(null==C)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),D(a,t);const A=(0,o.stringify)({...C?.description,elapsedMs:Date.now()-i}),I=(0,n.sortBy)(C?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:A,score:C?.score,totalColors:a.size,totalPixels:f.length,iters:C?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:A,dominantColorScore:C?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,v.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,v.ciede2000_delta_e)(e.centroid,r))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:v.cie76_delta_e,cie94:v.cie94_delta_e,ciede2000:v.ciede2000_delta_e},T=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function D(e,t){const i=e.countSum,r=e.size;k(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function k(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,w.unlabhash)(r),a=i.find((e=>(0,v.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,v.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=k,t.mergeNearCentroids=x},85409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(31586),s=i(68708),n=i(50989);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),w=i(21330),v=i(928),b=i(54261),S=i(73389),P=i(51275),M=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof w.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof w.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),k(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof w.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function k(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,v.getMillisecond)(e)))return 0;if((0,c.gt0)((0,v.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,v.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,v.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,v.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,v.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function F(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function C(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??w.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=k,t.isoToPrecisionMs=function(e){return(0,u.map)(C(e),k)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=k(e)),r??(r=k(t)),F(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,w.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,w.setZone)(t,s)??t),F(e,t,i,r)},t.isoToDated=C,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),s=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),s=i(31586),n=i(54557),a=i(91655),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),s=i(40958),n=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function w(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),w=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(w)??i,rawValue:e,tzoffsetMinutes:w})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??w(e,b(),t)},t.parseExifDateTimeRe=w;const v=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,v,p.monthRE,v,p.dayRE,/[T\s]/,p.hourRE,v,p.minuteRE,v,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),w=i(79842),v=i(66649),b=i(98247),S=i(98725),P=i(928),M=i(54261),_=i(73389),T=i(89724),E=i(17415),D=i(88600),k=i(51275);function x(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class F{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,D.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(S.ISO_YMD_RE.exec(e)?.groups??S.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tx(e))).join("-")}toLocal(){return(0,T.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new F(t.year,t.month,t.day)}}function C(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,M.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,E.zoneToTzOffsetMinutes)((0,v.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(s=>(0,d.map)((0,P.getDay)(e),(n=>(0,d.map)((0,P.getHour)(e),(a=>(0,b.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=F,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,h.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${x(n)}:${x(a)}`},t.toExifDateTime=C,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,M.hasTime)(e)||(i??(0,w.datedToPrecisionMs)(e))>=c.dayMs?O(e):C(e,(0,k.getZoneName)(e))?.toISOString({includeOffset:t})};const A="yyyy:MM:dd HH:mm:ss.SSS",I=A+"ZZ";function O(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>x(e))).join(t)}function L(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new F(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(v.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,w.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,k.hasZone)(t)?I:A):void 0},t.datedToYMD=O,t.toFuzzyDate=L,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,v.datedToMillis)(e)||null==(0,v.datedToMillis)(t))return;const[s,n]=[e,t].map((e=>(0,v.datedToMillis)(e))).sort(),o=(n-s)/(r+1),l=(0,k.getZoneName)(e),u=l===(0,k.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,M.hasTime)(e)))?L(c):c},t.setZone=function(e,t,i){const r={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,k.hasZone)(e)},s=(0,E.normalizeZone)(t);return null!=e&&null!=s&&(0,M.hasTime)(e)?e instanceof y.DateInterval?e.setZone(s,r):C(e)?.setZone(s,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,w.datedToDateTime)(e);if(null==i)return;const r=(0,k.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),w=i(68852),v=i(4001),b=i(28874),S=i(24689),P=i(79842),M=i(66649),_=i(98247),T=i(21330),E=i(54261),D=i(73389),k=i(16400),x=i(88600),F=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return F().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,w.concatRegexp)([/^/,t.yearRE,w.RegExpOptional.from(/-/,t.monthRE,w.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,w.concatRegexp)([/^/,t.yearishRE,w.RegExpOptional.from(/-/,t.monthishRE,w.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const C=new Map;function A(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(C,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void F().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void F().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(v.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>A(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const e of n){const t=a(e);if(null!=t&&(0,x.isValidDate)(t))return t}}t.parseDated=I;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new w.RegExpEscaped("(?"+(0,k.monthNames)().map(w.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,w.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,k.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),s=i(31586),n=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),s=i(31586),n=i(68708);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),s=i(19851),n=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,s.lazy)((()=>w(l.Settings.datesBeforeAreEstimated.valueOrDefault)??w(l.Settings.datesBeforeAreEstimated.defaultValue)));function w(e){return(0,a.map)((0,c.isoToDated)(e),v)}function v(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return v(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},42499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(51168),s=i(19851),n=i(19043),a=i(28874);t.setupLuxon=(0,s.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,n.locale)()}))},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,T=/(?[-±+−])/,E=/[-−]/,D=/(?[01]\d)/,k=/(?[01]?\d)/,x=/(?::(?\d\d))/;function F(e){return b(e)?0:C((0,t.TimezoneOffsetRE)().exec(e))}function C(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return w(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),T,D,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=F,t.timezoneOffsetFromRegExpMatch=C;const A=/\b(?(?:Etc\/)?GMT)\b/,I=(0,n.lazy)((()=>(0,m.concatRegexp)([A,T,k,m.RegExpOptional.from(x)])));function O(e){return C(I().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??F(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),w=(0,s.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),v=(0,s.lazy)((()=>(0,n.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),b=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,p.datedToISO)(e)))))),S=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,y.datedToLocal)(e)))))),P=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,m.datedToMillis)(e))))));function M(e){if(null==e)return!1;const t=T(e);return w().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return M(e)?e:void 0},t.isValidDate=M;const _=String(new Date("bad"));function T(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===_)return _;const t=(0,n.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,E())&&s.push("year is in the future"),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):S().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):b().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(t)).join("; "))}catch(t){return w().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=T;const E=(0,s.lazy)((()=>r.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return M(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==T({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),s=i(31586),n=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},82261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},92407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(19851),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},55332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(19851),s=i(50213),n=i(76187),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},91872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i,r){const a=Date.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}))}},12943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(79842),s=i(66649),n=i(40958),a=i(68708);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},65753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(19851),s=i(7282),n=i(28874);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*((0,s.isTest)()?.25:5))))},80632:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(54993),u=i(50213),c=i(23560),d=i(65211),h=i(29882),f=i(53265),m=i(66430),p=i(66184),g=i(28874),y=i(15674),w=i(87550);function v(){const e=g.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,a.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=g.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=g.Settings.logSql.valueOrDefault}){e=(0,f.resolve)(e),(0,h.mkdirpSync_)((0,r.dirname)(e));const b=(0,h.posixPathFromGrandparent)(e),S=(0,m.nativePathSizeSync)(e),P=(0,u.mkLogger)("db.mkdb("+b+")");if(null!=S){const E=Math.round(S/o.MiB),D=Math.ceil(1.5*E);D>g.Settings.dbCacheSizeMb.valueOrDefault&&(P.info("Dynamically setting dbCacheSize to "+g.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:E}),g.Settings.dbCacheSizeMb.envValue=D);const k=Math.round(1.5*E);k>g.Settings.maxMemoryMb.valueOrDefault&&(P.warn("Large database: setting maxMemoryDb to "+k+"MB",{dbFileSizeMb:E,"Settings.maxMemoryMb":g.Settings.maxMemoryMb.valueOrDefault}),g.Settings.maxMemoryMb.envValue=k)}P.info("Opening "+e+"...");const M={fileMustExist:!1,readonly:!1};if((0,a.gt0)(t)&&(M.timeout=Math.ceil(t)),i){const x=(0,u.mkLogger)("SQLite("+b+")"),F=(0,p.defaultLogLevel)();function C(e,...t){var i;(0,n.blank)(e)||x.log(F,(i=e,(0,l.toS)(i).replace(/\s{2,}/g," ")),{args:t})}M.verbose=C}const _=new w(e,M);P.info("Open. Setting PRAGMAs...");for(const A of(0,s.compact)(['encoding = "UTF-8"',"threads = "+(0,y.maxCpus)(),"foreign_keys = ON","page_size = "+v(),"trusted_schema = 0","cache_size = -"+Math.round(g.Settings.dbCacheSizeMb.valueOrDefault*o.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL",(0,a.gt0)(g.Settings.dbBusyTimeoutMs.valueOrDefault)?"busy_timeout = "+g.Settings.dbBusyTimeoutMs.valueOrDefault:null,"temp_store = MEMORY","synchronous = "+g.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,c.isDbJanitorService)()?(0,l.toS)(g.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+g.Settings.dbAutoVacuumMode.valueOrDefault]))P.tapThunk({msg:"PRAGMA "+A,result:()=>_.pragma(A)});const T=_;return T.__uid=(0,d.uid)(),T},t.pageSizeBytes=v},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},95704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(40958),s=i(31586),n=i(59455),a=i(65753),o=i(51040);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},76187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(17217),s=i(87391),n=i(7311);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},51040:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+$/gm,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(19851),s=i(50357),n=i(30976),a=i(50213),o=i(95696),l=i(80632),u=i(76187),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},87391:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),w=i(70698),v=i(64680),b=i(29882),S=i(45969),P=i(43334),M=i(28874),_=i(41692),T=i(32774),E=i(80612),D=i(32551),k=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function x(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+k(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+k()),preexistingDir:i});return e}}function F(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:T.DefaultDockerLibraryDir+"/.photostructure/cache"+k(),preexistingDir:T.DefaultDockerLibraryDir},...x()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,D.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,D.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,D.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...x()),i}t.tmpCacheDirs=x,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:x(),desc:"tmp"})},t.cacheDirs=F,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:F(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),M.Settings.cacheDir.watchLater(A)}));function A(){M.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=M.Settings.cacheDir.valueOrDefault;try{return(0,b.mkdirpSync_)(e),(0,w.writeCachedirTag_)(e).then((()=>(0,v.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=A},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),s=i(45969),n=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),s=i(45969),n=i(32774);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),s=i(96706),n=i(29882);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),s=i(49776),n=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),s=i(54993),n=i(29882),a=i(28874);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),s=i(55835),n=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function w(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function v(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(v(e),!1)}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function T(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await w(t);return(0,r.uniq)([t,i,await b(t),await P(t),await _(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=w,t.libraryOriginalsDirPosixFile=v,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=T},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),w=i(80612),v=i(32551);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,v.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,v.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,w.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,v.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),s=i(7282),n=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),s=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),w=i(59958),v=i(6012),b=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(w.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,n.join)((0,m.homeDir)(),".psenv"));const t=(0,b.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,d.debom)(s.default.readFileSync((0,g.resolve)(r))),n=(0,v.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(n))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),s=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(1708)),n=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),s=i(19851),n=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),w=i(70025),v=i(57159);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,w.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,w.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function M(e,t){return e instanceof v.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),s=i(26905),n=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},68301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(19851),s=i(42659),n=i(75240),a=i(55835),o=i(31586),l=i(68708),u=i(59455),c=i(54993),d=i(50213),h=i(45255),f=i(37628),m=i(99331),p=i(46292),g=i(38835),y=i(32144),w=i(29882),v=i(95696),b=i(55222),S=i(28874),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*s.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=s.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,w.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),s=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=s,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:s,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new _(v.PosixFile.for(e).join("events"))))))},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),s=i(38639),n=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function w(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function v(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function b(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function S(e){return!!((0,s.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||b(e))||void 0}t.isSqliteBusyError=w,t.isSqliteDisconnectedError=v,t.isSqliteConstraintError=b,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===S(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||w(e)||v(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=S;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),s=i(31586),n=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),s.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(n(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),s=i(19851),n=i(15197);t.ee=(0,s.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new n.CapturingEventEmitter(e)}))},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(73024)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(76760)),n=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),s=i(76760);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),w=f(i(1708)),v=i(46466),b=f(i(57975)),S=f(i(38522)),P=i(19851),M=i(40958),_=i(5233),T=i(22573),E=i(42659),D=i(50357),k=i(96249),x=i(98553),F=i(55835),C=i(31586),A=i(68708),I=i(97790),O=i(39926),L=i(51926),R=i(59455),N=i(54993),B=i(48884),j=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),q=i(76850),H=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Z=i(43334),Y=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),se=i(89968),ne=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),we=i(27794),ve=i(73428),be=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const Se=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const s=(0,fe.resolve)(i),n=new Pe(s,t);return Se().set(i,n),Se().set(s,n),n}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,F.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,C.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(T.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,F.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,k.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,F.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,q.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,be.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,ve.writeFileSync_)(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,A.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,we.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,we.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,C.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),Me)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,F.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,C.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,n=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,F.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,v.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*E.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let Me=!0;t.useFsWatch=function(e){Me=e},t.execDir=function(){return Pe.for(w.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),s=i(88840),n=i(14036),a=i(29882);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,n.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),w=i(14427),v=i(17217),b=i(16287),S=i(68284);class P{constructor(e,t){this.base=e,(0,w.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,v.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},60652:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b,S,P,M,_,T=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},E=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryIterator=t.Undone=t.Done=void 0;const D=i(76760),k=i(19851),x=i(40958),F=i(22573),C=i(41400),A=i(57924),I=i(31586),O=i(68708),L=i(34666),R=i(13538),N=i(83104),B=i(12168),j=i(59455),z=i(48884),V=i(45255),W=i(81168),U=i(38836),q=i(98314),H=i(32144),G=i(28874),$=i(79915),J=i(59107),K=i(98604),Z=i(69385),Y=i(92423),X=i(29882),Q=i(62105),ee=i(74128);t.Done={done:!0},t.Undone={done:!1};class te extends U.EndableWrapper{constructor(e,i,s){super("dir.DirectoryIterator("+e+")",(()=>this.cancel({details:"DirectoryIterator was ended"}))),r.add(this),this.dir=e,this.ctx=i,this.parent=s,this.start=Date.now(),n.set(this,[]),a.set(this,[]),o.set(this,[]),l.set(this,[]),u.set(this,void 0),c.set(this,!1),d.set(this,0),h.set(this,0),f.set(this,0),m.set(this,0),p.set(this,0),this.rootDir=(0,k.lazy)((()=>this.parent?.rootDir()??this.dir)),this.pathFromRoot=(0,k.lazy)((()=>(0,X.posixPathFrom)({nativePath:this.rootDir().dir},this.dir))),this.nextTimeout=(0,k.lazy)((()=>G.Settings.statTimeoutMs.valueOrDefault+(0,I.clamp)(0,512,10*(512-this.depth())))),y.set(this,(0,k.lazy)((async()=>{const e=await(0,Y.whyExcludedDirectory)(this.dir)??(!this.isRoot&&await(0,J.isPosixMountpoint)(this.dir)?"nested mountpoint":void 0);if(null!=e)return this.logger.info("skipping ignorable dir, "+this.dir,{details:e}),await(this.ctx.onExcludedDirectory?.(this.dir,e)),this.cancel({state:ee.SyncDirStates.skipped,details:e}),t.Done}))),b.set(this,(0,k.lazy)((async()=>{const[e,t]=(0,z.partition)((0,j.toA)(await this.dir.children()),(e=>T(this,r,"m",v).call(this,e)));for(const t of e)(0,ee.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.skipped,details:"this was scanned in a prior incomplete sync"});T(this,l,"f").push(...t.filter((e=>e.isDirectory()))),E(this,m,T(this,l,"f").length,"f");const i=t.filter((e=>e.isFile())),[s,a]=(0,z.partition)(i,H.isSidecarExt);T(this,n,"f").push(...a),T(this,o,"f").push(...s),E(this,h,T(this,n,"f").length,"f")}))),(0,ee.syncReport)().onProgress({path:e.nativePath+D.sep,from:"DirectoryIterator",state:ee.SyncDirStates.scanning})}get isRoot(){return null==this.parent}isDone(){return this.ended||T(this,c,"f")}status(){return{root:this.rootDir().nativePath,path:this.pathFromRoot(),isDone:this.isDone()}}cancel(e){return T(this,c,"f")||(E(this,c,!0,"f"),(0,ee.syncReport)().onProgress({path:this.dir.nativePath+D.sep,from:"DirectoryIterator",state:ee.SyncDirStates.canceled,...e,elapsedMs:Date.now()-this.start})),t.Done}depth(){return(0,W.countChars)(this.dir.nativePath,D.sep)}async run(e=V.ShortCommandTimeoutMs){for(;!this.isDone();)await this.next(Date.now()+e),await(0,C.delay)(1)}async next(e){var i;const s=e-Date.now();try{this.logger.trace("next() starting",{runMs:s});const n=await(0,R.thenOrTimeout)(T(this,r,"m",g).call(this,e),this.nextTimeout());return this.logger.trace("next() finished",{result:n}),n===N.Timeout?(E(this,p,(i=T(this,p,"f"),++i),"f"),this.logger.warn(".next() timed out",{runMs:s,timeoutCount:T(this,p,"f")}),T(this,p,"f")>3?(this.logger.warn(".next(): too many timeouts, giving up on this directory."),this.cancel({state:ee.SyncDirStates.timeout,details:"Failed to scan, even after 3 retries"})):t.Undone):(E(this,p,0,"f"),n)}catch(e){return this.logger.warn("next() failed",{error:e}),this.cancel({state:ee.SyncDirStates.failed,details:"Error thrown during scan: "+(0,q.errorToS)(e)})}}}t.DirectoryIterator=te,s=te,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,y=new WeakMap,b=new WeakMap,r=new WeakSet,g=async function(e){return(T(this,c,"f")?t.Done:void 0)??await T(this,y,"f").call(this)??await T(this,b,"f").call(this)??await T(this,r,"m",S).call(this,e)??await T(this,r,"m",P).call(this,e)??await T(this,r,"m",M).call(this,e)??await T(this,r,"m",_).call(this)},w=function(e){return this.ended||!0===this.ctx.ended?.()?this.cancel({details:"DirectoryIterator was ended"}):T(this,c,"f")?t.Done:(0,Z.isPaused)()||Date.now()>e?t.Undone:void 0},v=function(e){return this.logger.tap({msg:"shouldSkipChild()",result:(0,x.isNotEmpty)(this.ctx.startAtNativePath)&&(0,L.cmpArr)((0,X.splitNativePath)(e.nativePath),this.ctx.startAtNativePath,!1)<=0,meta:{child:e.base}})},S=async function(e){var t;const i=[];let s;for(;null==s&&(0,x.isNotEmpty)(T(this,n,"f"))&&this.ctx.hasCapacity();){const a=T(this,n,"f").shift();E(this,d,(t=T(this,d,"f"),++t),"f");const o=await(0,Q.whyRejectFileSimple)(a);null!=o?(this.logger.debug("maybePopChildFile()",{child:a,whyReject:o}),await(this.ctx.onExcludedFile?.(a,o)),(0,ee.syncReport)().onProgress({path:a.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.rejected,details:o})):i.push(a),s??(s=T(this,r,"m",w).call(this,e)),null!=s&&this.logger.trace("maybePopChildFile() timeout",{timeout:s})}return(0,x.isNotEmpty)(i)&&(this.logger.trace("maybePopChildFile()",{toAdd:i}),await this.ctx.fileHandler(i),T(this,a,"f").push(...i)),s},P=async function(e){for(;(0,x.isNotEmpty)(T(this,o,"f"));){const t=T(this,o,"f").shift();if(G.Settings.tagAlbumFilenames.values.includes(t.base))(0,ee.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.note,details:"sidecar will be checked for for album metadata"});else{const e=T(this,a,"f").filter((e=>(0,$.isSidecarOf)(e,t)));(0,x.isNotEmpty)(e)?(0,ee.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.note,details:"sidecar will be processed with "+(0,A.andList)(e.map((e=>e.base.normalize())))}):(0,ee.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.rejected,details:"sidecar will be ignored (no importable file was found to be relevant to this sidecar's name)"})}const i=T(this,r,"m",w).call(this,e);if(null!=i)return this.logger.trace("handleSidecars() timeout",{timeout:i}),i}},M=async function(e){var t;let i;for(;null==i&&(null!=T(this,u,"f")||(0,x.isNotEmpty)(T(this,l,"f")))&&this.ctx.hasCapacity();){if(null==T(this,u,"f")){const e=T(this,l,"f").shift();null==e||(this.logger.trace("delegating to child dir, "+e),E(this,f,(t=T(this,f,"f"),++t),"f"),E(this,u,new s(e,this.ctx,this),"f"))}if(null!=T(this,u,"f")){const t=await T(this,u,"f").next(e);(t?.done??!0===T(this,u,"f")?.isDone())&&E(this,u,void 0,"f")}i=T(this,r,"m",w).call(this,e)}return i},_=async function(){if((0,x.isNotEmpty)(T(this,n,"f"))||(0,x.isNotEmpty)(T(this,l,"f"))||null!=T(this,u,"f"))return this.logger.error("maybeCompleteResult: not done (?!)",(0,O.pick)(this,"result","pendingChildren","childDelegate","pendingChildDirs")),t.Undone;if(!T(this,c,"f")){E(this,c,!0,"f");const e=await(0,K.mkFolderUrl)(this.dir.nativePath),t=e?.with({query:null}),i=t?.toString(),r=0===T(this,h,"f")?"":`${T(this,d,"f")}/${(0,B.plur)(T(this,h,"f"),"file")}`,s=0===T(this,m,"f")?"":`${T(this,f,"f")}/${(0,B.plur)(T(this,m,"f"),"directory","directories")}`,n=(0,F.mapNotBlank)((0,A.andList)([r,s]),(e=>"Accepted "+e))??"No files or directories found";(0,ee.syncReport)().onProgress({path:this.dir.nativePath+D.sep,state:ee.SyncDirStates.scanned,from:"DirectoryIterator",details:n,url:i,elapsedMs:Date.now()-this.start}),await this.ctx.directoryListener(this.dir)}return t.Done}},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),w=i(54557),v=i(50213),b=i(88158),S=i(56519),P=i(46292),M=i(32551),_=i(35280),T=i(87290),E=i(96706),D=i(57902),k=i(43334),x=i(78984),F=i(33995),C=i(28874),A=i(21144),I=i(83278),O=i(48313),L=i(85772),R=i(78133),N=i(46356),B=i(17217),j=(0,u.lazy)((()=>(0,v.mkLogger)("fs.ExcludeGlobs"))),z=new w.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:C.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((k.isWin?"*":"")+"/"+t.s+"/",t.desc));if(k.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}k.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Z=(0,u.lazy)((()=>{C.Settings.excludeGlobsOmitDefaults.watchLater(J),C.Settings.excludeGlobsAdd.watchLater(J),C.Settings.excludeGlobsOmit.watchLater(J),C.Settings.globsCaseInsensitive.watchLater(J),C.Settings.libraryDir.watchLater(K),C.Settings.originalsDir.watchLater(K),C.Settings.scanPaths.watchLater(K),C.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ne,whyNoMedia:L.whyNoMedia,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ne}])),t.excludeGlobs=(0,u.lazy)((()=>{Z();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!C.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of C.Settings.excludeGlobsOmit.values)i(e);for(const e of C.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Y=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return C.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return F.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return C.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return C.Settings.disableAllFilters.valueOrDefault?void 0:x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ne(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),...C.Settings.argvScanPaths.values,...C.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,A.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ne},88561:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class w extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=w,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},79267:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const c=i(19851),d=i(40958),h=i(42659),f=i(31586),m=i(71371),p=i(50213),g=i(7282),y=i(409),w=i(78406),v=i(25764),b=i(99331),S=i(91655),P=i(34102),M=i(89968),_=i(85772);class T{static for(e){return new T(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,a,d=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=a,this.minRetained=d,s.set(this,void 0),this.intervalMs=(0,c.lazy)((()=>(0,f.clamp)((0,g.isTest)()?0:5*h.minuteMs,h.dayMs,this.staleMs/2))),n.set(this,void 0),this.cleanup=(0,y.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>u(this,r,"m",o).call(this)}),l(this,s,(0,p.mkLogger)("fs.FileCleanup("+e+")"),"f")}scheduleInterval(){return(null==u(this,n,"f")||u(this,n,"f").ended)&&l(this,n,new w.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:v.EndableRanks.first}),"f"),u(this,n,"f")}cancelInterval(){u(this,n,"f")?.end(),l(this,n,void 0,"f")}}t.FileCleanup=T,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(e){if(!(0,f.gt0)(this.minRetained))return new Set;const t=new m.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},o=async function(){try{if((0,b.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await M.DirectoryEntry.for(e);if(null==t)return[];u(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,S.fmtFullDuration)(this.staleMs," ")});const i=await u(this,r,"m",a).call(this,t),n=Date.now()-this.staleMs,o=new Set,l=[],c=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,_.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,f.gte)(e.mtimeMs(),n)))if(e.isDirectory())try{await e.rmdir_(),c.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(u(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,P.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&u(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),l.push(e.nativePath),o.add(e.dir)}catch(t){u(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const h=[...l,...c];return(0,d.isNotEmpty)(h)&&t.clear(),u(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:l.length,pruned_dir_count:c.length}),h}catch(e){return void u(this,s,"f").error("cleanup() failed",{error:e})}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,n.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),s=i(17217),n=i(16287),a=i(68284);async function o(e){return(0,r.pick)(await(0,n.stat_)((0,s.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,s.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),s=i(19851),n=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,s.set(this,[]),n.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,n,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,s,"f").push(e)}close(){u(this,n,"f").close()}}t.FileWatcher=m,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,s,"f"))t(e,this.nativePath)}}},13829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(55835),s=i(13538),n=i(81168),a=i(37628),o=i(46292),l=i(73209),u=i(95696);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},73209:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const M=i(58587),_=P(i(44652)),T=i(87997),E=i(40958),D=i(17586),k=i(42659),x=i(50357),F=i(75240),C=i(55835),A=i(31586),I=i(30976),O=i(13538),L=i(54993),R=i(7282),N=i(68852),B=i(23560),j=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),q=i(55222),H=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,s,Math.max(Date.now(),b(this,s,"f",n)+1),"f",n),(0,E.compactBlanks)([q.TokenRadix.encode(b(this,s,"f",n)),B.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,A.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return b(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>b(this,r,"m",v).call(this)),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=s,s,(i=b(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(b(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await b(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+b(this,l,"f")),this.staleMs=(0,A.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),b(s,s,"f",o).push(this)}get acquired(){return b(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await b(this,r,"m",f).call(this,e)??b(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,D.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,x.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==b(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:k.secondMs);S(this,c,setInterval((()=>b(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=b(this,c,"f")&&(clearInterval(b(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(b(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(b(this,d,"f"),(e=>(0,T.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?b(this,r,"m",w).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>b(this,r,"m",w).call(this)),(0,A.toGt0)(this.staleMs)??k.secondMs),"f"),b(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(b(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,A.gt0)(this.staleMs)&&Date.now()>b(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await b(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await b(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,A.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+k.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,A.gt0)(t)&&!(0,M.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),b(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await b(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},w=async function(){await b(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},v=function(){(0,E.filterInPlace)(b(s,s,"f",o),(e=>b(e,l,"f")!==b(this,l,"f")))},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),s=i(51926),n=i(54993),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(73024)),n=i(57075),a=i(46466),o=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44652)),n=r(i(73024)),a=i(46466),o=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),w=i(16287),v=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return v().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;v().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(n.default.createReadStream(i)),stats:(0,u.pick)(await(0,w.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),s=i(42659),n=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),s=i(54993),n=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,n.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,n.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,n.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,n.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(51926),n=i(54993);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(76760)),n=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},61704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(21144),s=i(17217);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=n(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),w=i(83278),v=i(70698),b=i(88561),S=i(65238),P=i(16287),M=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),_="NoMedia",T=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+_+"$","im"),E=Object.freeze(["."+_,_]),D=Object.freeze((0,u.flatten)(E.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function k(e){return null!=T.exec(e)}t.isNoMediaName=k;const x=(0,o.lazy)((()=>new b.FileCache({name:"fs.noMediaDirsCache"})));async function F(e,t){if(null==e)return null;const i=w.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return k(i.base)||await(0,v.isCachedirTagFile)(i)?x().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):F(i.parent());{const e=await x().getOrSetAsync(i.nativePath,(()=>C(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:F(i.parent())}}async function C(e){if(k(e.base))return x().set(e.parent().nativePath,e.nativePath),M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,S.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([A(e.nativePath,i),(0,S.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,v.isCachedirTagDirectory)(e)?M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(v.CACHEDIR_TAG).nativePath)}):null}async function A(e,t){for(const i of g.isCaseSensitiveFs?D:E){if(!0===t?.aborted)return null;const r=a.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return M().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(k(r.basename))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,r.basename))});if(r.basename===v.CACHEDIR_TAG){const t=(0,a.join)(e,r.basename);if(await(0,v.isCachedirTagFile)(t))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await F(e,t)},t.whyNoMedia=F,t.whyNoMediaDir=C,t._dirHasNoMediaChild=A},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),w=i(78133),v=i(53265),b=i(17217),S=i(16287),P=i(66430),M=i(5545);function _(e){return((0,b.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return F(e).some(_)},t.isNotHiddenPosixPath=function(e){return F(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,b.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,w.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return n.default.dirname((0,b.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const T=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=T.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function D(e){const t=n.default.parse((0,b.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,n.default.sep)}function k(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,b.toNativePath_)(e.ancestor),i=(0,b.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function x(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(y.isLinux?r===s:(0,p.equalsIgnoreCase)(r,s))}function F(e){return(0,b.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return(0,u.notBlank)(e)&&F(e).length===(y.isWin?1:0)}function A({p:e,maxLength:t}){const i=(0,b.toNativePath_)(e);if(i.length<=t)return i;const r=F(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),O([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),O([...s,...n])}function I(e){return e.startsWith("\\\\")}function O(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),y.isWin?"":n.default.sep)}t.parseNativePath=E,t.parentBasename=D,t.grandParentBasename=function(e){return D(n.default.parse((0,b.toNativePath_)(e)).dir)},t.containedByNativePath=k,t.eqlBasename=function(e,t){return x(b.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return x(b.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return x(b.toNativePath_,e,t)},t.toPathnames=F,t.pathIsRoot=C,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:F(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,b.toNativePath_)(e),r=(0,b.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,w.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,w.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=A,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(A({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return F(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return F(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(M.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;if(C(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await s.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,b.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>k({ancestor:t,descendant:e,acceptSelf:!0})?[(0,b.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),w=i(64660),v=i(21144),b=i(16287),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,w.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await M(i))return y.isLinux?i:(0,v.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,w.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),w=i(76790),v=i(5233),b=i(22573),S=i(42659),P=i(26905),M=i(75240),_=i(55835),T=i(31586),E=i(68708),D=i(13538),k=i(89937),x=i(12168),F=i(54993),C=i(48884),A=i(50213),I=i(45255),O=i(81168),L=i(56519),R=i(56038),N=i(31562),B=i(84777),j=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),q=i(43334),H=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Z=i(34238),Y=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),se=i(73209),ne=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,C.contextFilter)(function(e){return(0,w.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,A.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),r=new fe(i,t);return(0,O.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,F.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===k.PS_LIBRARY_SCHEME?1:t.scheme===k.PS_LOCAL_FILE_SCHEME?2:t.scheme===k.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,C.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,v.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,D.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,T.clamp)(I.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),w=i(83278),v=i(19748),b=i(92423),S=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):null}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function k(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function F(e){return(0,w.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function C(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function A(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function I(e){return[{isSupportedFileExtension:v.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:F},{notFileTooSmall:C,notFileTooBig:A}]}function O(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:T},{notRejectedRating:D},{notExcludedKeyword:k}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=F,t.notFileTooSmall=C,t.notFileTooBig=A,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(76760)),n=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(s.default.join((0,p.execDir)(),"resources"),s.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=s.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),s=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),s=i(84542);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(51455)),n=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),w=i(28874),v=i(63870),b=i(88561),S=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(w.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function M(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=M;const _=(0,a.lazy)((()=>new b.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function T(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function E(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=D(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(w.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(s===f.Timeout&&(0,g.onTimeout)({soft:!1}),s!==f.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=T,(0,c.later)((()=>{w.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),M()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?M():T(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){T(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(w.Settings.readdirCacheMs.valueOrDefault)?E(e):D(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=D},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const s=i(73024),n=r(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=n.default.resolve(t,...e);if((0,s.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??n.default.resolve(...e))},t.execDir=(0,l.defer)((()=>n.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(22454),s=i(28874),n=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),s=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const s=r(i(73024)),n=r(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,g.statTimeoutMs)(),!0)}function v(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function S(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(S(r),S(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}t.stat_=w,t.statMaybe=v,t.statToType=b,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await v(e,t)},t.isEmptyFile=async function(e,t){const i=await v(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await v(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await v(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await v(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await v(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await v(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await v(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),s=i(56409);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(57075)),n=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),w=i(19851),v=i(40958),b=i(22573),S=i(42659),P=i(98553),M=i(31586),_=i(68708),T=i(50989),E=i(51926),D=i(85556),k=i(54993),x=i(89788),F=i(23467),C=i(7282),A=i(23560),I=i(77377),O=i(71567),L=i(73568),R=i(25764),N=i(38836),B=i(99331),j=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),q=i(5012),H=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Z=i(84542),Y=i(73428);t.AssetFileSyncStates=(0,T.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,T.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,T.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,T.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const X={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,_.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,T.strEnum)(...(0,_.keys)(new class{constructor(e,t,i,r,s,n,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,w.lazy)((()=>(0,Y.writeTextfile_)(re().nativePath,(0,E.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(X)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=S.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,H.isCsvExt)(e)&&(0,M.gte)(e.mtimeMs(),t)))},t.syncReport=(0,w.lazy)((()=>new se));class se extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new x.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,s,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,b.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,q.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,k.toS)(e.path),state:e.state,details:(0,k.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:t,at:new Date(t).toISOString(),...i,...(0,_.pick)(e,"from","elapsedMs","url")};(0,_.isEmptyObj)(e.meta)||(s.meta=(0,P.stringify)(e.meta)),(0,C.isTest)()&&process.stdout.write((0,P.stringify)(e)+Z.Newline),f(this,r,"m",u).call(this,s)}}maybeSystemData(e){(0,A.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:n}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,B.ending)()||r instanceof L.AbortError?t.SyncFileStates.canceled:r instanceof D.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return f(this,n,"f")??f(this,r,"m",h).call(this)}async flushClose(){return f(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,n,"f");return m(this,n,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,s,"f")}}t.SyncReport=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,F.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,r,"m",c).call(this,i):(f(this,r,"m",c).call(this,{...i,details:(0,v.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Z.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,s,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,j.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,s,"f").nativePath),this.logger.info("Opening new report: "+f(this,s,"f")),(0,C.isTest)()&&(0,O.stdoutWrite)({syncReport:f(this,s,"f").nativePath},!1),m(this,n,(0,g.createWriteStream)(f(this,s,"f").nativePath),"f"),f(this,n,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Z.Newline),f(this,n,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(48161)),n=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44652)),n=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},79847:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkFileUri=t.trashOrUnlinkFileUris_=void 0;const o=n(i(51455)),l=a(i(49378)),u=i(40958),c=i(22573),d=i(13538),h=i(83104),f=i(45255),m=i(31562),p=i(98314),g=i(34102),y=i(28874),w=i(45200),v=i(63870),b=i(16287),S=i(74128),P=i(84258),M="fs.Trash";async function _(e){const t=Date.now(),i=(0,v.commandTimeoutMs)(),r=(0,c.toNotBlank)(e.nativePath)??await(0,d.thenOrTimeout)((0,w.uri2nativePath)(e.uri,e.mountpoint),i);if((0,c.blank)(r)||r===h.Timeout)return(0,S.syncReport)().onProgress({from:M,state:"failed",details:"Could not convert URI to native path",path:e.uri,elapsedMs:Date.now()-t}),{uri:e.uri,unlinked:!1};const s=await(0,b.statMaybe)(r);if(null==s)return(0,S.syncReport)().onProgress({from:M,state:"noop",details:"Failed to delete: no such file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(!s.isFile())return(0,S.syncReport)().onProgress({from:M,state:"noop",details:"Failed to delete: not a file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(y.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,d.thenOrTimeoutError)((0,l.default)(r,{glob:!1}),i),await function(e){return(0,m.untilTrue)((async()=>null==await(0,b.statMaybe)(e)),{timeoutMs:f.ShortCommandTimeoutMs})}(r))return(0,S.syncReport)().onProgress({from:M,state:"deleted",details:"Moved file to trash",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0};(0,P.logger)().warn("soft-delete("+r+") didn't seem to work: the file is still there?")}catch(e){(0,S.syncReport)().onProgress({from:M,state:"note",details:"Failed to soft-delete file to trash: "+(0,p.errorToS)(e),path:r,elapsedMs:Date.now()-t}),(0,P.logger)().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}try{return await(0,d.thenOrTimeoutError)(o.unlink(r),i),(0,g.ee)().emit("fileChanged",r),(0,P.logger)().info("unlink("+r+") successful"),(0,S.syncReport)().onProgress({from:M,state:"deleted",details:"Permanently deleted file",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0}}catch(i){return(0,S.syncReport)().onProgress({from:M,state:"failed",details:"Could not move file to trash or delete: "+(0,p.errorToS)(i),path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!1}}}t.trashOrUnlinkFileUris_=async function(e){const t=[];for(const{uri:i,mountpoint:r}of(0,u.uniqBy)(e,(e=>e.uri)))try{t.push(await _({uri:i,mountpoint:r}))}catch(e){t.push({uri:i,unlinked:!1,error:e})}return t},t.trashOrUnlinkFileUri=_},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),s=i(41400),n=i(55835),a=i(92782),o=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),h=i(87128),f=i(95696);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=n(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await a.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(76760)),n=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),w=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function v(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=v,t.zcat=async function(e,t){try{return v(e,t)}catch(t){return void w().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void w().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){w().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},63664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const r=i(22573),s=i(45599),n=i(41400),a=i(50268),o=i(98553),l=i(50213),u=i(23560),c=i(45255),d=i(5916),h=i(28874),f=i(34238),m=i(51140),p=i(4988),g=i(18454),y=(0,s.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({desc:"health.getRemoteHealthSummary",later:async()=>{try{if((0,u.isWebService)())return;const e=await(0,p.get_)(f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}),{timeoutMs:c.ShortCommandTimeoutMs}),t=(0,o.parseJSON_)(e.data);if(m.HttpStatusIs.ok(e.statusCode)&&(0,a.isHealthCheckSummary)(t))return"ready"===t.state&&(0,r.toNotBlank)(t.libraryDir)!==(0,r.toNotBlank)(h.Settings.libraryDir.valueOrDefault)&&(y().error("getHealthSummary(): libraryDir mismatch! Switching to that library directory...",{local:h.Settings.libraryDir.valueOrDefault,remote:t.libraryDir}),h.Settings.libraryDir.value=t.libraryDir),y().debug("getHealthSummary()",{response:e}),t;y().warn("getHealthSummary(): invalid response",{response:e})}catch(e){y().warn("Failed to get health check summary from web service",{error:e})}}}),t.getLocalHealthSummary=(0,d.lazyAsync)({desc:"health.getLocalHealthSummary",later:()=>g.HealthCheck.awaitSettled()}),(0,n.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},87408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(63870),s=i(18454),n=i(89035),a=i(82638);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...s.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:s.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},18454:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b,S,P,M=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},_=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const T=i(19851),E=i(40958),D=i(76790),k=i(22573),x=i(41400),F=i(50357),C=i(26905),A=i(50268),I=i(55835),O=i(68708),L=i(30976),R=i(51926),N=i(13538),B=i(42279),j=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),q=i(50213),H=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Z=i(77740),Y=i(98314),X=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),se=i(21525),ne=i(82638),ae=(0,T.lazy)((()=>(0,q.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{M(this,s,"f",l).push(e+": failed: "+(0,Y.errorToS)(t)),this.onResultChange()})),M(this,s,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return M(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){M(this,s,"f",l).push((0,R.isString)(e)?e:(0,Y.errorToS)(e)),this.onResultChange()}static lastErrors(){return M(this,s,"f",l).toA()}static addLoadingMsg(e){M(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,E.compact)((0,j.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:M(this,s,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[M(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=M(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>M(this,s,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return M(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,A.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=M(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=s.summary();if(e.pendingCount>0){const t=await Promise.all(s.testResultsCritical());e=s.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){s.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,C.shortStack)());else{this.onResultChange(),M(this,s,"f",l).clear(),M(this,s,"f",d).clear(),M(this,s,"f",h).clear(),M(this,s,"f",c).clear(),this.summary.clear(),_(this,s,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new s(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return M(this,s,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,n,o,l,u,c,d,h,f,m,S,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=n,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=S,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),v.set(this,(0,T.lazy)((async()=>{await M(this,p,"f").prior(),(0,F.eql)(M(this,g,"f"),M(this,r,"m",w).call(this))||(this.onReset?.(),await this.refresh(),M(this,v,"f").unset())}))),this.refresh=(0,T.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await M(this,p,"f").prior();const e=M(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,q.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[A.HealthCheckSections.ordinal(this.section),l??999,this.id],_(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>M(s,s,"f",a).enqueue({name:this.id,l:()=>M(this,r,"m",b).call(this,o)}),ttlMs:S}),"f"),this.isCritical&&M(this,p,"f").watchLater({onChange:s.onCriticalResult,onError:s.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>M(this,v,"f").call(this)))}isStale(){return M(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return M(this,p,"f").settledCount()}reset(){return M(this,p,"f").unset(),this.onReset?.(),_(this,g,{starting:!0},"f"),this}setTTL(e){M(this,p,"f").setTTL(e)}result(){return M(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return M(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return M(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??M(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,E.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,E.isNotEmpty)(i)&&(r.links=(0,E.uniqBy)(i)),(0,E.isNotEmpty)(t)&&(r.buttons=(0,E.uniqBy)(t)),r}t.HealthCheck=oe,s=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,v=new WeakMap,r=new WeakSet,o=function(){return(0,E.filterInPlace)(M(this,s,"f",n),(e=>!e.isPending)),M(this,s,"f",n)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,ne.summarizeHealthChecksSync)({errors:M(this,s,"f",l),skipPending:M(this,s,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&_(this,s,!0,"f",u),i.state!==M(this,s,"f",c).last?.state&&M(this,s,"f",c).push({state:i.state,ts:Date.now()}),i},w=function(){return(0,O.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},b=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,C.shortStack)()}),_(this,g,M(this,r,"m",w).call(this),"f");try{if((0,Z.getDevEnvFlag)("PS_SLOMO")&&await(0,x.delay)((0,L.randomInt)(.3*i,.7*i)),this.isSkipped())return M(this,r,"m",S).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const s=await(0,N.thenOrTimeoutError)(e(),i);return M(this,r,"m",S).call(this,{test:s,elapsedMs:Date.now()-t})}catch(e){return M(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},S=function({test:e,src:t="#toResult",elapsedMs:i}){var r,n;const a=s.normalizeMsg(e.msg),o=e.level??((0,z.toS)(a).toLowerCase().includes("error")?"error":(0,z.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,E.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(_(this,y,(n=M(this,y,"f"),r=n++,n),"f"),r),(0,$.ending)()?u:this.logger.tap({level:se.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const s=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,k.toNotBlank)((0,Y.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,X.isFatalError)(e)&&s.toLowerCase().includes("warn")?"warn":"error"),M(this,r,"m",S).call(this,{test:{msg:s,level:t},src:"#toErrorResult",elapsedMs:i})},n={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new U.CountingSet},f={value:[]},oe.all=(0,T.lazy)((()=>Object.freeze((0,D.sortBy)(M(s,s,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,H.debounce)((()=>{ae().info("onCriticalResult()",s.summary.refresh())}),250),oe.summary=(0,T.lazy)((()=>M(s,s,"m",m).call(s))),oe.resetDebounced=(0,H.debounce)((()=>s.reset()),50)},85021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function w({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await w(e)})};const v=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...v(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...v(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...v(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>v.unset()))})),t.summarizeHealthChecksSync=b},95242:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),w=i(57159),v=i(83278),b=i(95696),S=i(62105),P=i(84258),M=i(38156),_=i(69589),T=i(28874),E=i(47783),D=i(29990),k=i(16047),x=i(42725),F=i(4192),C=i(32876),A=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class O{constructor(e,t,i){r.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,_.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(r=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,S.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await n(this,r,"m",s).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:n,height:a,sha:l,mimetype:u}=t;if(null==s||null==n||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,D.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:n,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(x.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,D.equivalentFitSizes)(r,s)){const n=(0,D.fitSizes)(e,e.mimetype),a=(0,o.diff)(r,s);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=n.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:n});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=O,s=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new M.PushProgressObserver({path:e.nativePath,op:"Building previews"},x.ImageSize.sq().length+x.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:x.ImageSize.largestFit().max});if(null==a)throw new w.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,k.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,v.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,D.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=x.ImageSize.largestSq(),b=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,h.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of l){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&r.reducer===C.Fit&&T.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of x.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=T.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(r)+" -> "+(0,u.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new w.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),w=i(70417),v=i(35721);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,v.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,v.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,w.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,v.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},33106:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(9288)),n=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(40958),s=i(33374),n=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),w=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function v(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){w().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void w().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=v(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void w().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=v,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void w().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),s=i(54993),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),s=i(19851),n=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),w=i(55222),v=i(63870),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+w.TokenRadix.randomChars(2),w.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,v.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(9288)),n=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),w=i(88561),v=i(95696),b=i(17217),S=i(50213),P=i(23624),M=i(28874),_=i(12089),T=i(16170),E=i(1078),D=i(33106),k=i(86580),x=i(78011),F=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const C=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void C().warn("imageHash() failed for "+e,t)}};const A=(0,n.lazy)((()=>new w.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=v.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,k.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),n=await(0,F.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,k.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,F.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,F.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),w=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),v=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(w.meanHash),diffHash:(0,P.b64encodeBits)(w.diffHash),dctHash:(0,P.b64encodeBits)(v),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:A,impl:I}),t._imageHash_=I,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},80361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(33374),l=i(57924),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(21605),m=i(48884),p=i(50213),g=i(97352),y=i(85810),w=i(3048),v=i(32848),b=i(82647),S=i(38812),P=i(70417),M=i(23624),_=i(28874),T=i(86580),E=i(48368),D=i(2090),k=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,w.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,w.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function F(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function C(e,t,i=E.HashDim){const r=(0,M.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function A({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=C(e,i,r),l=C(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));k().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function I(e,t,i="debug",r={}){return k().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??F(r.meanHash))||(s.isGreyscale??F(s.meanHash))),f=A({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(r,s)}),m=A({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=A({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,v.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void k().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,w=(0,T.aspectRatio)(r),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=w&&null!=S&&!(0,o.isCloseAspectRatio)(w,S);let M=0,x=0;n&&(x+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,M+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,M+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(M+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const C=R((M+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),I=R((x+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,D.fmtAspectRatio)(w)} vs ${(0,D.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,C)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,C)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=I,z=j&&N.avg>=C;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:C,imageCoeffDelta:M,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:I,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:w,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return k().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=F,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=C(e,t,i);return f.Rotations.map((e=>(0,M.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=A,t.isSimilarImage=I,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return I(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},42725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},4192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},78011:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(9288)),n=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},52121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const r=i(19851),s=i(78923),n=i(95696),a=i(50213),o=i(28874),l=i(12089),u=i(16170),c=i(13940),d=i(4192),h=i(5733),f=i(50961),m=(0,r.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=n.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,s.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},48604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),s=i(31586),n=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(9288)),n=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,n.lazy)((()=>{s.default.simd(l.Settings.enableSIMD.valueOrDefault),s.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),s.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(77988),n=r(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),w=i(56519),v=i(56038),b=i(57159),S=i(95696),P=i(17217),M=i(28874),_=i(47783),T=i(16170),E=i(95141),D=i(54979),k=i(1078),x=i(63870),F=i(86580),C=i(277),A=i(16047),I=i(13940),O=i(5733),L=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await z(e,t))?.nativePath}async function j(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=j,t.toSharp=function(e){const t=e;if((0,O.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,v.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=N().addParameterContext(e.nativePath);(0,O.setupSharp)();const n=await(0,D.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,k.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const I=(0,F.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),z=(0,T.isSharpMimeType)(n)&&null==t,V=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||z||V)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:z,isMirrorOrientation:V});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>j(e,n,t,x,I)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,C.isHeifSupported)()&&f("heif",(()=>(0,w.thenMap)((0,C.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,w.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,L.isVideoSupported)())try{return await(0,w.thenMap)((0,L.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,v.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=z},21473:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=void 0;const s=r(i(34589)),n=i(76760),a=r(i(9288)),o=i(50357),l=i(98553),u=i(68708),c=i(23560),d=i(43899),h=i(28874),f=i(5733);t.testSharp_=async function e(t){try{(0,f.setupSharp)();const e=t??(0,n.join)(d.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(e,{failOn:"error"}),r=await i.resize(24,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,o.eql)((0,u.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:24,height:32,channels:3}),"Unexpected sharp output: "+(0,l.stringify)(r.info))}catch(i){if(!(0,c.isWorkerService)()&&h.Settings.enableSIMD.valueOrDefault)return h.Settings.enableSIMD.envValue=!1,e(t);throw i}}},181:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(9288)),n=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),w=i(54979),v=i(63870),b=i(5733),S=i(50961),P=i(66106),M=i(51210),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&_().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,v.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,w.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),w=i(56038),v=i(31562),b=i(98314),S=i(34102),P=i(88561),M=i(95696),_=i(17217),T=i(74128),E=i(31843),D=i(70417),k=i(33847),x=i(28874),F=i(94678),C=i(43207),A=i(47783),I=i(16170),O=i(95141),L=i(1078),R=i(63870),N=i(89782),B=i(13940),j=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,j.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,E.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function q(e){return await(0,t.isVideoSupported)()?M.PosixFile.for(await(0,t._extractVideoFrame_)((0,_.toNativePath_)(e))):void 0}async function H(e,t){const i=V("extractVideoFrame",e),r=M.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,j.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,B.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,A.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,N.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,C.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,j.ffmpegFrame_)(t),!1===await(0,v.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,A.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,j.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,A.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,C.extractDurationSec)(i);if(!(0,c.gt)(n,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=q,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await G())return;const n=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,A.readTags)(e),h=(0,L.extractSizeInfoFromTags)(d),m=(0,C.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,A.readRawTags)(t),r=await(0,A.readRawTags)(e),s=(0,C.extractDurationSec)(r),n=(0,C.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),s=x.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,F.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,w.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new k.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:r.halt,...g},m=x.Settings.transcodeMaxDim.valueOrDefault,p=(0,D.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,j.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-n})}catch(t){throw(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:Date.now()-n}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await q(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,j.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),w=i(84258),v=i(28874),b=i(76280),S=i(63870),P=i(19769),M=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function _(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:v.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=_;const T=/ffmpeg version n?(?\S+)/i,E=(0,u.lazy)((async()=>{const e=await _();if(null==e)return void M().info("failed to find ffmpeg in $PATH",{ffmpegPath:v.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=T.exec(t.result)?.[1];return M().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function D(){E.unset(),t.ffmpegVersionDescription.unset()}function k(e){const t=e?.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function x(e){const t=[...v.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(v.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function F(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function C(e){const t=v.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(E(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",D),(0,g.ee)().on("clearToolCache",D)})),t.ffmpegVersion_=async function(){return await E.prior()??E.refresh()},t.isFFmpegSupported=async function(){return null!=await E()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=x,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...x(t),...C(t),...k(t),"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...F(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){M().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return M().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return M().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await _(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(19851),s=i(42659),n=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),w=i(89782),v=i(13940),b=i(42725),S=i(19769),P=(0,r.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,v.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>D(e,t)})};const M=["-T"],_=["-Z","-"],T=["-o","1"],E=["-t","0","-j"];async function D(e,t){const i=await(0,w.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=b.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[...M,..._,...T,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],v={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:v});const D=(0,c.execFile)(g,y,void 0,v),k=[];function x(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});k.push(r)}}if(D.on("error",x),D.stderr.on("data",x),await t.writeStream_(D.stdout),(0,s.isNotEmpty)(k))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:k,path:e.nativePath});(0,c.endProcess)(D)}t.dcraw_emu_=D},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},42042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(22573),s=i(28874),n=i(81674);t.getEmail=async function(){const e=s.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),w=i(50213),v=i(56519),b=i(76596),S=i(46292),P=i(87290),M=i(77740),_=i(34102),T=i(83278),E=i(28874),D=i(37692),k=i(71706),x=i(83950),F=i(72042),C=i(33603),A=i(48132);t.k=(0,y.rolazy)((()=>(0,k.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,w.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,F.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function L(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:x.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,v.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await L((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,A.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function B(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=L,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await L(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof x.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:A.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),s=(n=(0,l.flatten)((await(0,v.someOrTimeout)([()=>function(e){return L(E.Settings[(0,t.k)().L].value,"Settings",A.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:A.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,f.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l))),(e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,o.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset())),D.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=B,t.l=async function(){try{return await B()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await B()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},84194:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(40958),a=i(76790),o=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),h=i(19851),f=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function w(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=w,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(w(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const v=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||v.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=w(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==w(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(45599),o=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),h=i(50213),f=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),w=i(45879),v=i(70854),b=i(57902),S=i(72308),P=i(43334),M=i(24399),_=i(7014),T=i(30933),E=i(71706),D=i(84194);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const k=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const F=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),C=/o\.e\.m\./i;async function A(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,w.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(C)))}async function I(){return P.isLinux?(await A("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function O(){return P.isLinux?(await A("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await A("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void k().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,r.compactBlanks)(await A("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,v.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,v.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,F,R,V,W,z,I,O,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return k().tap({msg:"sids()",result:(0,D.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,f.isTest)())for(const t of e)H.add(t)},t.clearSids=function(){(0,f.isTest)()&&H.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},34474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(40958),s=i(42659),n=i(41400),a=i(96249),o=i(68708),l=i(34666),u=i(20214),c=i(71371),d=i(50213),h=i(42638),f=i(31562),m=i(98314),p=i(89968),g=i(28874),y=i(4904),w=i(57902),v=i(89241),b=i(83954);function S(e=10*s.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(w.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-s.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new v.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*s.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-s.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),s=i(23560),n=i(66184),a=i(72210);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),s=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function w(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...w(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),w=i(31256),v=i(28538),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new w.GelfLogFormatter,this.logFilter=new v.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),s=i(42659),n=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},12495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(19851),s=i(42659),n=i(23560),a=i(79267),o=i(32144),l=i(28874);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isLogExt)(e.ext)})))},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),s=i(31586),n=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),s=i(57902);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,s.set(this,[]),n.set(this,(0,l.lazy)((()=>{o(this,s,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,s,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,n,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,r,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,r,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){if(null==e||0===o(this,s,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,s,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),s=i(50989),n=i(28874);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=n.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},89241:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),h=i(38522),f=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),w=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),s.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,s,!0,"f")})),this.stream.on("end",(()=>{u(this,s,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,s,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,s,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,s,!0,"f");else{const t=(0,w.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),s=i(76760),n=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),w=i(22277),v=i(25764),b=i(38836),S=i(99331),P=i(42638),M=i(76596),_=i(98314),T=i(89968),E=i(29882),D=i(28874),k=i(28981),x=i(20839),F=i(21727),C=i(66184),A=i(57902),I=i(72210),O=i(98192);function L(e){const t=(0,k.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),v.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new w.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,C.ifLog)(A.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,_.errorToS)(t))))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,F.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,_.errorToS)(e))))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),s=i(82328),n=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),w=i(31586),v=i(409),b=i(23560),S=i(81168),P=i(78406),M=i(25764),_=i(20197),T=i(14977),E=i(36868),D=i(28874),k=i(32105),x=i(20839),F=i(21727),C=i(66184),A=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:M.EndableRanks.logger,unref:!0,onEnd:()=>c(this,s,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:k.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:C.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,v.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,A.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,w.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,F.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),s=i(84542),n=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),s=i(76790),n=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),s=i(41400),n=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),w=i(66184),v=i(28538),b=i(24068),S=i(43705),P=i(51879);function M(){(0,w.logFilter)()instanceof v.LogFilterImpl||w.logFilter.set(new v.LogFilterImpl),_();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new S.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,n.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&b.LogTail.instance()}function _(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=M,t.setupLogFormatter=_,(0,s.later)((()=>{h.Settings.logStdout.watchLater(M),h.Settings.logDir.watchLater(M),h.Settings.tailLogs.watchLater(M),h.Settings.logColor.watchLater(_),h.Settings.logLevel.watchLater((()=>w.defaultLogLevel.unset()))}))},83954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(89179);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},82647:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p69(){return n(this,r,"m",s).call(this,.5)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,s=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},76752:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtEstimate=t.ETA=void 0;const r=i(42659),s=i(75240),n=i(31586),a=i(97352),o=i(82647);function l(e){return(0,n.gt0)(e)?e<=r.minuteMs?"less than a minute remains":"about "+(0,s.fmtDuration)(e,1,{plural:"remains",singular:"remain"}):void 0}t.ETA=class{constructor(){this.taskMillis=new o.Average(10)}push(e){(0,a.mapGt0)(e,(e=>this.taskMillis.push(e)))}clear(){this.taskMillis.clear()}avg(){return this.taskMillis.p69}etaMs(e){const t=this.avg();if(null==t)return;const i=t*e;return i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(76790),s=i(93973);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},36372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(76790),s=i(42659),n=i(31586),a=i(97238),o=i(50597),l=i(9103),u=i(55222);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},38812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(21605);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}×${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),s=i(65713);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function w(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=w;class v{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new v;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=w(t,((t,r)=>(t-i)*(r-e))),s=w(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(38522),s=i(22573),n=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(48161)),n=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),w=i(34102),v=i(26293),b=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==b.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=S.exec(e)}function M(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=M,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=M(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const _=(0,s.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,w.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=M(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),s=i(19851),n=i(54993);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(22573),s=i(51926),n=i(83556);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),s=i(59455),n=i(31562);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),w=i(97790),v=i(59455),b=i(54993),S=i(54557),P=i(19851),M=i(50213),_=i(88158),T=i(409),E=i(78406),D=i(25764),k=i(99331),x=i(56519),F=i(46292),C=i(8769),A=i(83278),I=i(32144),O=i(29882),L=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,M.mkLogger)("proc.Pids"))),j=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,O.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,v.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,T.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??L.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,f.isEmpty)(s))return B().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,N.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){B().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!z(r,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:r}),a.push(W(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,C.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,s,"f").delete(l),o(this,s,"f").getOrSet(l,(async()=>{const i=o(this,r,"m",n).call(this,e.pid),s=(0,w.opt)((0,_.Try)((()=>(0,O.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:s,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,s,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,v.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,r,"m",n).call(this,e);return(0,x.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new E.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:D.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=U,s=new WeakMap,a=new WeakMap,r=new WeakSet,n=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,F.configDir)(),(e=>new U(A.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const s=i(31421),n=i(48161),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),w=i(84968),v=i(48963),b=i(56519),S=i(84777),P=i(8103),M=i(45879),_=i(43334),T=i(24399),E=i(45643),D=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function k(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){if(_.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,M.readFileMaybe)("/proc/"+i+"/stat")));return D().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,E.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:N)).filter((e=>k(e)&&t.includes(e.pid)));return D().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=k,t.pidInfo=async function(e){return(0,b.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,b.thenMap)((0,E.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const F="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function A(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(T.PowerShell.instance().ended)return R(e);const t=[F,"-Id",A(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(T.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,v.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,v.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===a.default.pid))||r.push({pid:a.default.pid,start:new Date(w.StartTs),cmd:"node "+a.default.title}),r}async function N(e){return t=(await(0,S.stdoutResult_)("ps",["-p",A(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(_.isLinux)return(0,c.toGt0)((0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){D().warn("clk_tck failed",{error:e})}return 100})),j=(0,g.lazy)((()=>Date.now()-(0,n.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,s=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(s)?{pid:i,cmd:r,start:new Date(j()+s/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),s=i(42659),n=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),w=i(99331),v=i(56519),b=i(31562),S=i(84777),P=i(34102),M=i(43334),_=i(28874),T=i(63870),E="{ready}",D=" | ConvertTo-Json -Compress";function k(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=k,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,v.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,w.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,v.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+k(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,w.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),s=i(91655),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874),l=(0,n.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,s.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,s.pick)(e??{},"retries","halt","path"),...(0,s.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},86941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(19851),s=i(59455),n=i(72993),a=i(46292),o=i(95696),l=i(50213),u=i(83179),c=i(28874),d=i(2858),h=i(84438),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),n=await t.resolve_();if(null==r||null==n||n.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=n.join("licenses");for(const r of(0,s.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=n.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),s=i(22573),n=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function w(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function v(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){M(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&w(),y("strictDeduping",e)&&v(),(y("optOut",e)||y("noNetwork",e))&&_()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(m.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=w,t.setStrictDeduping=v;const b=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],S={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function M(e){for(const t of b)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:S;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function _(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=M,t.disableExternalNetworkRequests=_},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),s=i(53265),n=i(87652);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},4936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(55835),l=i(51926),u=i(50213),c=i(81168),d=i(79842),h=i(21330),f=i(51275),m=i(29882),p=i(28874),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+e.replace(/'/g,"′")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),s=i(83556);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),w=i(40583),v=i(81168),b=i(44198),S=i(96706),P=i(34102),M=i(28283),_=i(81075),T=i(98778),E=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?n(this,r,"m",s).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?n(this,r,"m",s).call(this,e??t)+": "+i:null==this.fromEnv(e)?n(this,r,"m",s).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,v.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,S.caseInsensitiveEnv)():new w.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,b.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,M.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(M.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return _.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,b.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&S.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,b.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&S.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new w.CaseInsensitiveValued(e)))??(0,S.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,v.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],E.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,v.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],E.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,v.wrap)(["",e+": "+r],E.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,T.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,T.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,T.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,s=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),s=i(51168),n=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),w=i(40583),v=i(79840),b=i(7282),S=i(12801),P=i(4328),M=i(70488),_=i(84248),T=i(5531),E=i(99315),D=i(34365),k=i(34580),x=i(96706),F=i(50274),C=i(33866),A=i(52086),I=i(48584),O=i(45969),L=i(43334),R=i(24540),N=i(70379),B=i(71300),j=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),q=i(30577),H=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Z=i(71988),Y=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),se=i(57039),ne=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(b.isProd);const we=()=>!(0,t.isProd)();function ve(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function be(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>we()?"1":"25"}),imageCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>we()?32:1024}),quiet:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:be}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Y.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:be}),useFsWatch:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new se.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>H.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:H.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>H.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Y.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new Y.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),minDelayBetweenSpawnMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,M.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>we()?"5s":"5m"}),streamFlushMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>v.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ne.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>we()?50:500,min:1,max:5e3}),enableArchive:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ve()}),enableRemove:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ve()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:T.CheckpointTypes,defaultValue:T.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:D.SynchronousModes,defaultValue:D.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>we()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:we()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>we()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Y.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Y.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!we()||!(0,O.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:C.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Y.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Y.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:q.UpdateChannels}),autoUpdateCheck:new Y.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Y.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Y.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,k.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Y.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Y.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Y.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Y.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Y.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":s.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Y.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Y.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!we()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:F.SidecarExts,defaultValue:F.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new ne.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Y.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Y.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!we()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:A.CropStrategies.attention,strEnum:A.CropStrategies}),videoFrameAtSec:new ne.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Y.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Y.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Z.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Y.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>j.DefaultIncludedPreviewTags}),disableAllFilters:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Y.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new se.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ne.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!we()}),tagKeywordsFromPath:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Y.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new ne.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!we()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Y.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Y.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function Se(e){const i=((0,u.blank)(e)?"":e).split(n.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(n.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=Se,t.pathWithDefaults=(0,a.lazy)((()=>Se((0,x.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const Me=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Me().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new w.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(31586),n=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),w=i(15674),v=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=c.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,v.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>(0,n.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,n.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,w.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel,v.Settings.minBusyPct.opts.defaultValue=()=>(0,s.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),w=i(54993),v=i(50213),b=i(81168),S=i(83556),P=i(87290),M=i(98314),_=i(34102),T=i(83278),E=i(95696),D=i(60865),k=i(4175),x=i(83179),F=i(81075),C=i(28874),A=i(41692),I=i(84438),O=i(32707),L=i(6707),R=i(98778),N=i(55018),B=i(10357),j=(0,r.lazy)((()=>(0,v.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,O.systemSettingsFile)()){if(null!=e)return X(T.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,L.readTomlFile_)((0,O.systemSettingsFile)()))?.[C.Settings.libraryDir.name])}catch{return}}function U(e){return(0,L.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function q(){return U((0,O.systemSettingsFile)())}function H(e){return U(z(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:C.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,x.settingsToObj)(i),wip:r}),r){const t=await(0,L.readTomlFile_)(s),i=await(0,L.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function K(e=(0,O.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,C.persistedSystemSettings)()),t}function Z(e){return X(z(e))}async function Y(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,C.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,C.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,M.errorToS)(e)),[]}}async function Q(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,L.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,C.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,C.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}})));return t.info("loaded",{settings:(0,x.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(a),{settings:a,warnings:n}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return C.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=q,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await q()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await H()&&await Y()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",G),(0,_.ee)().on("settingsChanged",G),C.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,D.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(E.PosixFile.for(e),(0,C.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=Y,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([C.Settings.noNetwork,C.Settings.httpPort,C.Settings.license,C.Settings.logStdout,C.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(C.Settings))ee().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),C.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(E.PosixFile.forMaybe((0,O.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,_.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${(0,D.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,w.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,s=e.strEnum,(0,r.compact)((0,a.splitStringArray)(i)?.map((e=>s.getCI(e))));var i,s},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),s=i(55835),n=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),s=i(44652),n=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),s=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),s=i(81168);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),w=i(81168),v=i(76596),b=i(79842),S=i(66649),P=i(21330),M=i(98725),_=i(928),T=i(54261),E=i(89724),D=i(17415),k=i(88600),x=i(51275),F=i(29882),C=i(17217),A=i(68284),I=i(57902),O=i(28874),L=i(65162),R=i(71300),N=i(14036),B=i(61424),j=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,b.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,b.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,A.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,M.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,D.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,D.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,x.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,T.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,_.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,k.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,x.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,D.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,b.datedToStartDateTime)(this.date)??(0,b.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,b.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function q(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],s=r;if((0,k.isValidDate)(t)){if((0,D.isValidZone)(e.tz)&&(!(0,x.hasZone)(t)||R.OverrideUTCZoneTags.includes(s))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,w.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,b.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,b.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,b.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,x.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function H(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,M.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,b.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,M.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,k.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,w.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,F.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",q(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??s("tags",q(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("stat+bname",await(0,B.extractStatBname)(e)))??(n?void 0:s("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",H(e,t)))??(n?void 0:s("path",G(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await $(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return q(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),s=i(97352),n=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(77988),n=r(i(76760)),a=r(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),w=i(12168),v=i(56038),b=i(4867),S=i(36557),P=i(98247),M=i(21330),_=i(98725),T=i(23467),E=i(88561),D=i(95696),k=i(17217),x=i(16287),F=i(50213),C=i(17921),A=i(7282),I=i(88158),O=i(23560),L=i(28874),R=i(12089),N=i(45255),B=i(81168),j=i(63870),z=i(15674),V=i(28544),W=i(43207),U=i(72180),q=i(75767),H=i(12788),G=i(80495),$=i(14036),J=i(67083),K=i(3432),Z=i(28630),Y=i(15912),X=i(30748),Q=i(16170),ee=i(95141),te=i(7330),ie=i(54979),re=i(1078),se=i(61424),ne=i(8791),ae=(0,o.lazy)((()=>(0,F.mkLogger)("exiftool.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ce()};const le=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,S.batchClusterOptions)((0,A.isTest)()?8:(0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function ue(){const e=le();return e.ended?le.refresh():e}function ce(e=!1){return(0,d.map)(le.clear(),(t=>t.end(e)))}t.exiftool=ue,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeoutError)({p:ue().version(),timeoutMs:N.ShortCommandTimeoutMs})},t.exiftoolVersionMaybe=function(){return(0,d.map)(le.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,j.commandTimeoutMs)()})))},t.shutdownExiftool=ce,t.extractBinaryTag=function(e,t,i){return ue().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),ie.mimetypeCache.prior()?.clear()};async function de(e){return(0,f.omit)(await ge(e,!1),...t.IgnoredSidecarFields)}function he(e){return null==e?void 0:(0,t._readTags)((0,k.toNativePath_)(e))}async function fe(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function me(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*w.GB)&&t.push("-api LargeFileSupport=1"),t}async function pe(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ae().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,ie.readMimeType)(e),s=await e.sidecar(),n=(0,Q.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Q.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ae().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function ge(e,i=!0){const r=D.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void ae().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ae().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,Z.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,Q.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ae().debug("readRawTags() sidecar had values",{sidecar:e.base})):ae().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,J.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,ee.orientationToRotation)(a.Rotation),ae().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ye(e,t){return null==t?void 0:(0,v.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Q.normalizeMimetype);if((0,u.blank)(r))return void ae().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ae().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,se.canInferForDir)(e.parent()),l=await(0,K.maybeInferTimezone)(e,n,o);if(ae().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values])if(!(0,U.isUtcTagName)(t)){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l)}const c=o?(0,X.extractMakeAndModel)(n):await(0,se.inferMakeAndModel)(e,n);c.Make!==(0,X.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ae().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,G.extractExposureSettings)(n),g=await(0,re.extractSizeInfoFromFile)(e,n);if(null==g)return void ae().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,ne.extractTitleDescription)(n),...d,cameraId:(0,q.cameraIdFromTags)(n),imageId:(0,q.imageIdFromTags)(n),lensId:(0,q.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,te.extractRating)(n)};(0,A.isTest)()&&(y.__parsedBy__=a.default.pid);const w={...n,...y};return ae().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(w,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(w)}catch(e){return void ae().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(de(e),de(t))},t.readTags=he,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ye(t,await ge(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,k.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await he(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await ue().readRaw((0,k.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ae().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,ee.extractRotation)(await ge(e,!0))},t.moveOriginal=fe,t.overwriteTags_=async function(e,t){try{await(0,v.time)("exiftool.overwriteTags:"+e,(async()=>{await ue().write(e.nativePath,t,await me(e)),e.clearThisAndParent()}))}catch(i){ae().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,v.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await ue().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=me,t.writeTagDest=pe,t.writeTags_=function(e,t,i){return(0,v.time)("exiftool.writeTags:"+e,(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await pe(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=D.PosixFile.for(t),s=(0,f.fromEntries)(i);ae().info("writeTags()",{src:e,dest:t,t:s}),await ue().write(r.nativePath,s,await me(r)),L.Settings.overwriteOriginal.valueOrDefault||await fe(r),r.clearThisAndParent()}}))},t.readRawTags=ge,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ae().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ae().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...L.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,$.isVideoExt)(n.default.extname(e))?[]:["-fast"]],r=await(0,v.time)("exiftool.read()",(()=>ue().read(e,i).catch((t=>{ae().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ae().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,Q.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),oe&&(r.__instance=(0,C.safeUUID)()),r}}),t.parseTags=ye},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),w=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const v=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of v){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of v)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of v){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,w.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),s=i(40958),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function w(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=w,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return w(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return w(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return w(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return w(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return w(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return w(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return w(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return w(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),s=i(45599),n=i(68708),a=i(50213),o=(0,s.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,n.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:s}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[s])&&(t[i]=t[s]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,n.pick)(e,"Directory","FileName"));for(const t of(0,n.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),w=i(50213),v=i(81168),b=i(66649),S=i(17415),P=i(29882),M=i(95696),_=i(17217),T=i(28874),E=i(47783);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>k({action:e,key:t,value:i})))}function k({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=k,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,w.mkLogger)("tags.History")));function F(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function C(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function A(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,v.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!F(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=F,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,v.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=C(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=C,t.inferredToTags=A,t.ensureInferredHistoryRecords=async function(e,i,r){const s=D(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?A(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),I(i,s,n)},t.ensureHistoryRecords=I},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(53705)),n=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),w=i(72180),v=i(14245),b=i(61424),S=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,v.omitInvalidGeolocationTags)(t);{const e=M(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,w.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=_(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function M(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return S().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function _(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,u.toDated)(t[r]);if(null==s||(0,f.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return S().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return S().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=M,t.inferTzOffsetMinutesFromFilename=_},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),w=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function v(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):v(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>w.unset()))})),t.keywordToPath=function(e){const t=w();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=v,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(_(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const w=/([\d. -]+)\s?mm\b/i,v=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=w.exec(e)?.[1].replace(/\s/g,""),i=v.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function w(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=w(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=w;const v={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(v))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},38010:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(50213),g=i(84885),y=i(66649),w=i(98725),v=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return v().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return v().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return v().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,w.parseDated)({input:e.When}));return null==r?v().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?v().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):v().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),s=i(54993),n=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},66039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(75020),u=i(59455),c=i(50213),d=i(68852),h=i(81168),f=i(70417),m=i(28874),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,w=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,v=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,w),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function M(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,v),null!=e&&(M(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const _=(0,s.compactBlanks)(t.split(/\s+/)),T=l.length,E=b.length;if(_.length>0)if(0===T&&E>0)l.push(..._);else if(0===E&&T>0&&1===_.length)b.push(..._);else if(1===_.length)l.push(..._);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?_.pop():_.shift()),l.push(..._)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function M(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function _(e,t,i){return M("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=M([t.modifier,t.lifespan]),r=M(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?M([r,e]):_(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),s=i(54993),n=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),s=i(40958),n=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,s.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),w=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),v=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return w().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return w().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return v().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},3127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(54993),s=i(42231);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),w=i(79842),v=i(21330),b=i(98725),S=i(51275),P=i(35280),M=i(19748),_=i(88561),T=i(95696),E=i(65238),D=i(17217),k=i(57902),x=i(28874),F=i(80496),C=i(65162),A=i(28544),I=i(47783),O=i(88840),L=i(30748),R=i(16170),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===F.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===F.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:k.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,v.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,v.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,v.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7,i=!0){if(!await j(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(r,(e=>(0,C.bname)(e))),n=(0,D.findFileIndex)(e,s);if(n<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),H(e,t,!1)):void 0;const l=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[s.slice(n-2*t,n),s.slice(n+1,n+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,C.bname)(e,!0),(0,C.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,w.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,w.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function w(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function v(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=w,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(w(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=v,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>v(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),s=i(22573),n=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),w=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function v(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await v(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void w().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?w().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=v,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),s=i(57975),n=i(90595),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",w=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class v{static isUri(e){return e instanceof v||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=w.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?v.file(r.win32.join(T(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=v;const b=h.isWinPortable?1:void 0;class S extends v{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:M;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:M(o,!1)),r}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=T;const k=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(k)?e.replace(k,(e=>D(e))):e}t.percentDecode=x,t.toURI=function(e){return v.isUri(e)?e:v.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),s=i(40958),n=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),s=i(22573),n=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(9103),a=i(37628);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),s=i(30577);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),s=i(22573),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),s=i(9595),n=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},42233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(45200),s=i(98770),n=i(7014);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),s=i(22573),n=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),w=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function v(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=v,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await w());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(v)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),w=i(24399),v=i(28874),b=i(24541),S=i(60224),P=i(63870),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(T(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function k(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return w.PowerShell.instance().executeJsonToA(x())};const F=/\{([-a-z\d]{7,})\}/i;function C(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function A(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([C(e.HealthStatus,"healthy"),C(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(F.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function I(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>w.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:v.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(k)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>w.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:v.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(A)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=A,t.volumeInfoWin=I},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),w=i(83278),v=i(8103),b=i(16287),S=i(45969),P=i(43334),M=i(69108),_=i(98770),T=i(44224),E=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,v.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>w.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await k(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,E.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const k=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),s=i(5233),n=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),w=i(98770),v=i(63870),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,w.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,v.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,w.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,v.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),s=i(19851),n=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),w=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(v)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?w().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){w().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const v=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),w=i(84777),v=i(34330),b=i(8769),S=i(34102),P=i(17217),M=i(16287),_=i(43334),T=i(28874),E=i(8540),D=i(68884),k=i(44224),x=i(24541),F=i(69375),C=i(63870),A=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function O(e=(0,C.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function L(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{T.Settings.libraryDir.watchLater(I),T.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&T.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),O((0,C.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux){const i=(0,k.maybeWatchProcMounts)();await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),O((0,C.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),O((0,C.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?x.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,C.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,S.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),I()})),T.Settings.mountpointsTtlMs.watch(O)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>L(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),L()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,w.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,C.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>L(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),w=i(28874),v=i(69108),b=i(68884),S=i(59107),P=i(69375),M=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await D()??await(0,c.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,b.isGioSupported)())try{await(0,c.thenMap)((0,b.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){M().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function T(e){return!w.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,P.isExcludedMountpoint)(e)&&(!w.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function D(e=_,t=T,i=E){if(y.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return M().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return M().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void M().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=T,t.readProcMounts=D,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(_)?new h.FileWatcher(_,{recursive:!1,persistent:!1},(()=>{M().info("detected change in "+_),(0,d.setUnrefTimeout)((()=>S.mountpoints.refresh()),n.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),s=i(42659),n=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),w=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await T()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const v=["LocalName","RemoteName","Status"],b=["NETUSE","get",v.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,u.parseFixed)(v,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const T=(0,w.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),s=i(12168),n=i(28874);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),w=i(95696),v=i(45969),b=i(28874),S=i(59107),P=i(63870),M=i(68995),_=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),T=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function E(e){return(0,a.isTrue)(e.ignorable)||(0,v.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function D(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function k(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=D(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(b.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of b.Settings.volumeUuidFilePaths.values){const i=w.PosixFile.for(e.mountpoint).join(t),r=await k(i).catch((e=>_().info("Failed to read "+i,{error:e})));if(null!=r)return _().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,M.volumeUuidSubpath)());if("/"===e.mountpoint)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(b.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(b.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,M.writeVolumeUuid)(e);if(!(0,n.blank)(t))return _().tap({msg:"readVolumeUUID(): wrote new "+(0,M.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return _().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>T.clear())),S.mountpoints.watchLater((()=>T.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(E(e))return;if((0,a.isFalse)(e.ok))return;const t=await T().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>_().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=E,t.toVolumeUUID=D,t.readUuidFile_=k,t.readVolumeUUID=x},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),w=i(59455),v=i(48884),b=i(50213),S=i(7282),P=i(23560),M=i(28850),_=i(45255),T=i(81168),E=i(56519),D=i(4867),k=i(49776),x=i(9595),F=i(77740),C=i(44198),A=i(96706),I=i(8769),O=i(57159),L=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),j=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),q=i(43334),H=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Z=i(27461),Y=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=s.default.platform(),ne=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,ne),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,x.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ne.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:se}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))n.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function me(e,i){const r=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(r))return;const s=await(0,L.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function pe(e,t,i){const r=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,W.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,T.equalsIgnoreCase)(n,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,S.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,w.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,D.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,O.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if((0,S.isTest)()){const e=(0,p.toInt)((0,C.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeoutError)({p:q.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeoutError)({p:q.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,v.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),h=i(34238),f=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const a=n(i(37067)),o=n(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),h=i(50213),f=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),w=(0,u.defer)((()=>(0,h.mkLogger)("net.get")));async function v(e,t){return b({...t,url:e})}async function b(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?a.request:"https"===t.scheme?o.request:w().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??f.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",h=e?.agent??!1,b=r(t.toString(),{method:c,headers:u,timeout:n,agent:h},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const a={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&y.HttpStatusIs.redirect(a.statusCode)&&!(0,l.blank)(e.headers.location)?(w().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(v(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(w().debug("complete",{...a,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(a))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||b.write(e.body),b.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=v,t.httpRequest_=b},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},14854:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(48161)),h=i(42659),f=i(45599),m=i(55835),p=i(31586),g=i(68708),y=i(19851),w=i(50213),v=i(7282),b=i(78406),S=i(25764),P=i(38835),M=i(74128),_=i(82647),T=i(43334),E=i(28874),D=i(30933),k=i(15674),x=(0,y.lazy)((()=>(0,w.mkLogger)("work.CpuUsage"))),F=(0,y.lazy)((()=>{const e=C.instance().busyPct();(0,M.syncReport)().maybeSystemData({from:"cpuUsage",state:"note",details:"Current system load is too high to schedule more work",meta:(0,g.compactValues)({loadCpuPct:I(),cpuBusyPct:e})}),x().warn("Current system load is too high to schedule more work",{cpuBusyPct:e,max:E.Settings.cpuBusyPercent.valueOrDefault})}),((0,v.isTest)()?15:60)*h.secondMs);t.isTooBusy=function(){if(E.Settings.cpuBusyPercent.valueOrDefault<=0)return!1;const e=C.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(4*E.Settings.cpuBusyPercent.valueOrDefault/3));return(0,p.gte)(e,t)?(F(),!0):(F.unset(),!1)};class C extends b.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,k.singleThreadedMode)()?60:T.isWin?20:10)*h.secondMs,rank:S.EndableRanks.first}),r.add(this),s.set(this,new _.Average(5)),n.set(this,new A),(0,p.mapFinite)(I(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??I()}}t.CpuUsage=C,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,I());const e=new A;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},C.instance=(0,f.defer)((()=>new C));class A{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?(0,p.sigFigs)(t/r*100,3):void x().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+P.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function I(){return T.isWin?void 0:(0,p.sigFigs)(d.default.loadavg()[0]/(0,D.cpuInfo)().length*100,3)}},73328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyDoNotRun=t.doNotRun=void 0;const r=i(68708),s=i(99331),n=i(74128),a=i(63664),o=i(14854);t.doNotRun=function(e){return null!=u(e)};const l=["error","no-library","stop-sync"];function u(e){if(!0===e?.ended)return"endable ended";if((0,s.ending)())return"service is ending";if((0,o.isTooBusy)())return"system is too busy";const t=(0,a.getRemoteOrLocalHealthSummarySync)();if(null==t||!l.includes(t.level))return;const i=t.level+": "+t.msg.join("\n");return(0,n.syncReport)().maybeSystemData({from:"whyDoNotRun",state:"note",details:t.level,meta:(0,r.omit)(t,"links","buttons")}),i}t.whyDoNotRun=u},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),s=i(37692);let n=!1;function a(){return n}function o(e=!0){l(e),(0,s.writeStateFile)({paused:e})}function l(e){e!==n&&(n=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=a,t.pause=o,t.resume=function(){return o(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return a()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),s.minuteMs);function v(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=v,t.targetCpuLoadPct=b,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(b()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(b()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=v();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,w());return t=(0,a.clamp)(1,s,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const s=r(i(78474)),n=i(40958),a=i(76790),o=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),h=i(87290),f=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),w=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let v;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new s.default;let b=0;function S(){const e=(0,h.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-b>o.minuteMs;i&&(b=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(v?.nativePath)||(v?.close(),v=void 0),r&&null!=e&&(v??(v=new f.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=S()?.readJsonSync();for(const i of e?.events??[])M.get(i.e)!==i.ts&&(w().info("emitting event "+i.e),t.stateEvents.emit(i.e),M.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const M=new Map;function _(e){const i=S();if(null==i)w().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),s=function(e){const t=Date.now()-10*o.minuteMs;return(0,n.uniqByLast)((0,a.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:s};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=_,t.addStateEvent=function(e){const t=Date.now();M.set(e,t),_({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),s=i(87997),n=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},83600:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.RequestTask=void 0;const a=i(58587),o=i(80875),l=i(19851),u=i(50213),c=i(34102),d=i(84542),h=i(87445),f=i(40958),m=i(26905),p=i(98553),g=i(31586),y=(0,l.lazy)((()=>(0,u.mkLogger)("worker.RequestTask")));class w extends a.Task{constructor(e){super((0,p.stringify)(e),(e=>n(this,r,"m",s).call(this,e))),r.add(this),this.request=e}}t.RequestTask=w,r=new WeakSet,s=function(e){for(const t of(0,f.compactBlanks)((0,d.splitLines)(e))){const e=(0,o.parseJSON)(t);if(null==e)y().warn("ignoring non-json line from worker",{line:t});else{if(null!=e.error)throw y().warn("worker threw error",{response:e}),(0,m.errorFromJson)(e.error);if((0,g.isNumber)(e.id))return e.id!==this.request.id?y().throw(`bad request: #parse given mismatching requests (${e.id} != ${this.request.id})`,{response:e,request:this.request}):e.response;(0,h.isProgressEvt)(e)?(0,c.ee)().emit("progress",e):y().warn("ignoring json line from worker",{response:e})}}return y().throw("bad request: #parse missing valid response")}},93493:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearShims=t.setupShimDelegates=void 0;const r=i(19851),s=i(5233),n=i(68708),a=i(13538),o=i(57206),l=i(50213),u=i(23560),c=i(70025),d=i(28874),h=i(15674),f=i(22751),m=i(83600),p=i(58800),g=i(24817),y=(0,r.lazy)((()=>(0,l.mkLogger)("worker.ShimDelegation")));let w=0;async function v(e,t){const i=d.Settings.taskTimeoutMs.valueOrDefault;return(0,s.retryOnReject_)((async()=>{y().throwIfAborted_();const r={id:w++,fn:e,args:t},s=new m.RequestTask(r),n=await(0,p.workerCluster)(),o=n?.t,l=null==n||null==o?g.WorkerFunctions[e](...t):n.awaitOrAbort(o.enqueueTask(s));return(0,a.thenOrOnTimeout)(l,i/3,(()=>{y().warn("soft timeout servicing work request",{request:r,timeoutMs:i}),(0,f.onTimeout)()})),(0,a.thenOrTimeoutError)(l,i)}),{maxRetries:d.Settings.maxRetries.valueOrDefault,timeoutMs:i,retryDelay:d.Settings.minDelayBetweenRetriesMs.valueOrDefault,errorIsRetriable:e=>!1!==(0,c.isRetriableError)(e)})}function b(){for(const e of(0,n.values)(g.WorkerFunctions))(0,n.maybeCall)(e,"clearShim")}t.setupShimDelegates=async function(){if((0,o.addDefaultJsonRevivers)(),(0,u.isWorkerService)())b(),y().warn("setupShimDelegates(): in worker service, skipping");else if((0,h.singleThreadedMode)())y().warn("setupShimDelegates(): single-threaded mode, clearing shims"),b(),await(0,p.endWorkerCluster)();else for(const[e,t]of(0,n.entries)(g.WorkerFunctions))t.setShim((t=>v(e,t)))},t.clearShims=b},24817:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequest_=t.isWorkRequest=t.mkWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=t.AllWorkerFunctionCandidates=void 0;const r=i(98553),s=i(31586),n=i(68708),a=i(50989),o=i(32639),l=i(13991),u=i(50597),c=i(48368),d=i(52121),h=i(48604),f=i(181),m=i(66106),p=i(47783),g=i(83966);t.AllWorkerFunctionCandidates={_extractVideoFrame_:m._extractVideoFrame_,_readRawTags:p._readRawTags,_readTags:p._readTags,assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkerFunctions={assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkRequestMethods=(0,a.strEnum)(...(0,n.keys)(t.WorkerFunctions));let y=0;t.mkWorkRequest=function(e,t){return{id:++y,fn:e,args:t}},t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,s.isNumber)(e.id)},t.handleWorkRequest_=async function(e){const i=t.WorkerFunctions[e?.fn];if((0,o.isFunction)(i))return i(e?.args);throw new Error("invalid method "+(0,r.stringify)(e))}},58800:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerCluster=t.endWorkerCluster=t.workerClusterPriorEnd=void 0;const r=i(58587),s=i(36557),n=i(19851),a=i(50213),o=i(71567),l=i(25764),u=i(84777),c=i(86335),d=i(38835),h=i(84542),f=i(87445),m=i(41944),p=i(15674),g=i(42659),y=i(98553),w=i(31586),v=i(67478),b=i(54993),S=i(27395),P=i(5916),M=i(55534),_=i(29325),T=i(28874),E=i(30933),D=i(41657),k=(0,n.lazy)((()=>(0,a.mkLogger)("worker.cluster")));t.workerClusterPriorEnd=async function(){return(await t.workerCluster.prior())?.t.closeChildProcesses()},t.endWorkerCluster=function(){return(0,S.end)(t.workerCluster.prior())},t.workerCluster=(0,P.lazyAsync)({desc:"worker.workerCluster",later:async()=>{const e=await(0,c.pathToService)("worker");if(null==e)return k().throw("Could not find worker.js"+d.FatalErrorFlag);k().info("worker.js found at "+e);const t={id:-1,fn:"ping",args:{}},i=new r.BatchCluster({processFactory:async()=>(k().info("Spawning new worker",{execPath:process.execPath,worker:e.nativePath,maxProcs:(0,p.maxCpus)()}),(0,u.spawn)(process.execPath,[e.nativePath],0,{env:await(0,D.workerEnv)()})),...(0,s.batchClusterOptions)((0,p.maxCpus)(),"worker.BatchCluster"),streamFlushMillis:0,versionCommand:(0,y.stringify)(t),healthCheckCommand:(0,y.stringify)(t),taskTimeoutMillis:T.Settings.taskTimeoutMs.valueOrDefault,maxProcAgeMillis:4*T.Settings.taskTimeoutMs.valueOrDefault,minDelayBetweenSpawnMillis:(0,_.isPacked)()?g.secondMs:1,pass:o.ReadyStr,fail:d.FatalErrorRe,exitCommand:M.ServiceExitCommand});return i.on("taskData",(e=>{for(const t of(0,h.splitLines)((0,b.toS)(e))){const e=(0,v.parseJSON)(t);(0,f.isProgressEvt)(e)&&(0,m.emitProgressEvt)(e)}})),p.maxCpus.watchLater((e=>{const t=(0,w.clamp)(1,(0,E.cpuCount)(),e??(0,p.maxCpus)());return k().warn("maxConcurrentImports changed",{maxProcs:t,newValue:e}),i.setMaxProcs(t)})),new s.BatchClusterObserver("worker",i,l.EndableRanks.first)}})},41657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerEnv=void 0;const r=i(9727),s=i(28874),n=i(59107);t.workerEnv=async function(){const e={};return s.Settings.libraryDir.addToEnv(e),s.Settings.mountpoints.addToEnv(e,await(0,n.mountpoints)()),(0,r.childEnv)({overrides:e,forWorker:!0})}},83966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const s=r(i(1708)),n=i(41400),a=i(31586),o=i(7282),l=i(12089),u=i(45608),c=i(57159),d=i(89035);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),(0,o.isTest)()&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:s.default.pid,input:e?.input??"(no input)"}}})},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function w(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:w((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=w,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return w(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return w(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},75761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function w({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function v({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const v=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=v):p.src=v,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(w({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=w,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...v({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=v},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),s=i(31586),n=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),s=i(22573),n=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function w(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function v(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=w,t.fmtLocalToShort=function(e){return(0,a.map)(w(e),m)},t.nextMidnightTs=v,t.msUntilMidnight=function(){return v()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),s=i(73872);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const w=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,w),w}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s.hasPrior=()=>r,s}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),s=i(21605),n=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),s=i(68708),n=i(34666),a=i(32639);function o(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,n.isPrimitive)(e)||(0,n.isPrimitive)(t))return e===t;if(!(0,s.isObject)(e)||!(0,s.isObject)(t))return!1;for(const i of(0,s.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),s=i(42659),n=i(55835),a=i(31586),o=i(12168),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),s=i(50357),n=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class s extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=s},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,(t=>!e(i,t,s)));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),s=i(22573),n=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=w(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,s){return!(null==s||!o(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,s.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function w(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function v(e){return o(e)&&e>0}function b(e){return o(e)&&e>=0}function S(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function M(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function _(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=v,t.firstGt0=function(...e){for(const t of e){if(v(t))return t;const e=y(t);if(v(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return v(t)?String(t):void 0},t.mapNumeric=S,t.map2Numeric=function(e,t,i){return S(e,(e=>S(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,n.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return S(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=M,t.toPrecisionMaybe=function(e,t){return d(e,(e=>M(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=_,t.times=function(e,t){if(!v(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return _(0,100,v(t)?P(100*(v(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function w(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function v(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=w(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=w,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=v,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=v(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),s=i(30976),n=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),s=i(54993),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),s=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=w,t.ensureSuffix=v,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return v(w(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=w((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),s=i(68708),n=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let s=!0;const n=setTimeout((()=>{s&&(s=!1,i(a.Timeout))}),t);try{n.unref?.();const t=await e;s&&(s=!1,i(t))}catch(e){s&&(s=!1,r(e))}finally{clearTimeout(n)}}))}async function c(e,t,i=!0){const s=await u(e,t,i);if(s===a.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return s}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?a.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return c(e,s,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,n.tot)(i);const s=await u(e,t,r);return s===a.Timeout?(0,n.tot)(i):s}},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),s=i(30301),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(30301),s=i(54993);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},58939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(55835),s=i(31586);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},12236:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.noRecentAssetIdsProgress=t.isRebuildProgress=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0;const r=i(50989);t.SyncStatuses=(0,r.strEnum)("processing","paused","done"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI].includes(e?.uri)},t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),s=i(30301),n=i(31586),a=i(97238),o=i(29652);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return n(e)??[]},t.optToA=n},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),s=i(23541),n=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},98401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cancelFileAndProcCleanups=t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=t.maybeCleanup_=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(56519),o=i(76187),l=i(87290),u=i(79267),c=i(32144),d=i(13829),h=i(69734),f=i(95696),m=i(65238),p=i(70257),g=i(13940),y=i(12495),w=i(95402),v=i(28874),b=i(40958),S=i(42659),P=i(31586),M=i(64526),_=i(22526),T=i(69032),E=(0,r.lazy)((()=>(0,s.mkLogger)("library.Cleanup")));async function D(){const e=M.Library.instance();if(null==e)E().info("No library to vacuum.");else{E().info("Running tag and search maintenance...");try{await(0,T.runTagMaintenance)()}catch(e){E().warn("Failed to run tag maintenance",{error:e})}E().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,n.isDbJanitorService)()&&(E().info("Running database maintenance..."),await e.runDbBackup_())}E().info("Cleaning child processes..."),await(w.Pids.instance()?.killOldProcs()),E().info("Cleaning stale and temp files..."),await k(),await(0,a.mapAsync)({name:"fileCleanup",arr:j(),f:e=>e.cleanup()})}t.maybeCleanup_=(0,r.lazy)(D,5*S.minuteMs),t.cleanup_=D;const k=(0,r.lazy)((()=>(0,l.libraryDataDirPosixFile)()?.join("shared-state").rmrf())),x=(0,r.lazy)((()=>u.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:g.imageCacheDir_,staleMs:v.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ImageCacheName)}))),F=(0,r.lazy)((()=>u.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>f.PosixFile.for((0,m.readdirCacheDir)()),staleMs:v.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(m.ReadDirCacheName)}))),C=(0,r.lazy)((()=>u.FileCleanup.for({name:"previewWipCleanup",rootNativePath:l.libraryPreviewsDirPosixFile,staleMs:S.hourMs,isPrunable:e=>(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)}))),A=(0,r.lazy)((()=>u.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:d.defaultFsAdvisoryLockDir,staleMs:S.hourMs,isPrunable:h.isPsLockFileOrDir}))),I=(0,r.lazy)((()=>u.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,P.gt0)(v.Settings.syncReportRetentionCount.valueOrDefault)?(0,l.librarySyncReportsDir)():void 0,staleMs:S.hourMs,isPrunable:e=>(0,p.isWip)(e)||(0,c.isCsvExt)(e)})));function O(e){return(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)||(0,o.isSqliteFile)(e)}const L=(0,r.lazy)((()=>u.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,_.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:S.hourMs,isPrunable:O}))),R=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,_.libraryDbObjects_)().libraryDbBackupDir,staleMs:S.hourMs,minRetained:v.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:O})));async function N(){const e=await(M.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const B=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:N,staleMs:S.hourMs,minRetained:1,isPrunable:O})));function j(){return(0,b.compact)([x(),F(),C(),A(),(0,y.LogDirCleanup)(),I(),L(),R(),B()])}t.fileCleanups=j,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{w.Pids.instance()?.scheduleInterval();for(const e of j())e.scheduleInterval()})),t.cancelFileAndProcCleanups=function(){t.scheduleFileAndProcCleanups.unset(),w.Pids.instance()?.cancelInterval();for(const e of j())e.cancelInterval()}},64526:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(27395),u=i(25764),c=i(38836),d=i(99331),h=i(45608),f=i(15056),m=i(87290),p=i(38835),g=i(57159),y=i(61704),w=i(95696),v=i(18454),b=i(13940),S=i(48604),P=i(19851),M=i(23560),_=i(28874),T=i(2858),E=i(7014),D=i(63870),k=i(15674),x=i(22573),F=i(38639),C=i(42659),A=i(56409),I=i(68708),O=i(25470),L=i(22526),R=i(41844);class N extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired_(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new A.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted_(),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted_();const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,F.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,k.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted_(),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted_(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),v.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.previews=(0,P.lazy)((()=>(0,I.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new R.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.onEnd=(0,P.lazy)((async()=>{if(!(0,d.ending)())for(const{ea:e,t}of[{ea:this.dbModelJanitor.clear(),t:5*C.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=w.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise.then((()=>this))}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup_(){return(await this.dbModelJanitor())?.backup_()}}t.Library=N,r=N,n=new WeakMap,s={value:void 0}},19113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(62105),s=i(181),n=i(94448),a=i(39604);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},18449:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(7282),s=i(96706),n=i(29325),a=i(28874);t.sentryEnabled=function(){return(0,s.isEnvTrue)("ENABLE_SENTRY")||(0,r.isProd)()&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},95629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(16436)),l=a(i(48161)),u=a(i(1708)),c=i(19851),d=i(19043),h=i(50213),f=i(31578),m=i(7282),p=i(96175),g=i(23560),y=i(84968),w=i(81168),v=i(37805),b=i(25764),S=i(38836),P=i(99331),M=i(85100),_=i(98314),T=i(68301),E=i(70025),D=i(8769),k=i(34102),x=i(34592),F=i(42042),C=i(34474),A=i(20839),I=i(57902),O=i(45969),L=i(43334),R=i(40958),N=i(22573),B=i(42659),j=i(41400),z=i(98553),V=i(55835),W=i(12168),U=i(59455),q=i(54993),H=i(18449),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:v.release,environment:(0,m.nodeEnv)(),maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(T.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,w.ellipsize)(i,256));const r=await X(e);return await(T.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,k.ee)().on("fatal",$),(0,k.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Z(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Z(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,F.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=v.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,x.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*A.DefaultLogFlushMs);const e=await(0,C.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,w.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,w.isString)(e.meta)?(0,w.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Z,t.sentryExceptionToS=Y,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[I.LogLevels.fatal,"fatal"],[I.LogLevels.error,"error"],[I.LogLevels.warn,"warning"],[I.LogLevels.info,"info"],[I.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},37158:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const p=m(i(29907)),g=m(i(1708)),y=i(57206),w=i(19851),v=i(50213),b=i(59880),S=i(23560),P=i(19913),M=i(71567),_=i(37805),T=i(38836),E=i(99331),D=i(45608),k=i(56038),x=i(55534),F=i(42499),C=i(49776),A=i(96706),I=i(98314),O=i(38835),L=i(70025),R=i(8769),N=i(57159),B=i(34102),j=i(33456),z=i(87408),V=i(85021),W=i(17181),U=i(86941),q=i(28874),H=i(41692),G=i(2858),$=i(69385),J=i(22573),K=i(42659),Z=i(41400),Y=i(56409),X=i(55835),Q=i(41583),ee=i(54993),te=i(95629);t.setupEventHandlers=(0,w.lazy)((()=>{(0,B.ee)().on("resume",(()=>(0,$.resume)())),(0,B.ee)().on("pause",(()=>(0,$.pause)()))}));class ie extends T.EndableWrapper{constructor(e){super(e),r.add(this),s.set(this,void 0),n.set(this,new Y.Latch),a.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,k.time)("Service.setup",(()=>f(this,r,"m",o).call(this))))),u.set(this,(0,w.lazy)((()=>{const e=g.default.stdin.pipe(new j.LineReader);return e.on("data",(e=>f(this,r,"m",d).call(this,(0,ee.toS)(e)))),e}))),(0,S.isBillingService)()||(0,H.setSettingsDefaults)(),h(this,s,(0,v.mkLogger)("Service("+this.name+")"),"f"),f(this,r,"m",c).call(this),this.setup_()}get name(){return super.name}get ready(){return f(this,n,"f").promise}get isReady(){return f(this,n,"f").isResolved()}setInputHandler(e,t){f(this,a,"f").set(e.trim().toLowerCase(),t)}}t.Service=ie,s=new WeakMap,n=new WeakMap,a=new WeakMap,u=new WeakMap,r=new WeakSet,o=async function(){try{(0,J.mapNotBlank)((0,A.getEnv)("PS_FATAL_"+this.name),(e=>{throw new N.WrappedError(e,{fatal:!0})})),(0,J.mapNotBlank)((0,A.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new N.WrappedError(e)}),5*K.secondMs)})),(0,P.setServiceName)(this.name),(0,b.setProcessTitle)(),(0,S.isMainService)()&&await(0,U.mergeUserDataDirs_)(),await(0,G.readSettings)(),await f(this,r,"m",l).call(this),(0,W.setupLogger)(),(0,y.addDefaultJsonRevivers)(),(0,C.cacheDir)(),(0,t.setupEventHandlers)(),f(this,u,"f").call(this),await(0,F.setupLuxon)(),q.Settings.startPaused.valueOrDefault&&(0,$.pause)(),(0,E.ending)()?f(this,n,"f").reject():f(this,n,"f").resolve()}catch(e){console.error((0,I.errorToS)(e)),f(this,n,"f").reject((0,Q.toErr)(e)),(0,D.exit)({reason:(0,L.addErrorFlags)(this.name+" setup failed: "+(0,I.errorToS)(e),O.FatalErrorFlag),status:14})}},l=async function(){(0,S.isPermaService)()||(0,B.ee)().on("fatal",(e=>(0,D.exit)({error:e,status:12}))),g.default.on("unhandledRejection",(e=>(0,X.map)(e,(e=>(0,R.onError)("unhandledRejection",e))))),g.default.on("uncaughtException",(e=>(0,X.map)(e,(e=>(0,R.onError)("uncaughtException",e))))),g.default.on("SIGINT",(()=>(0,D.exit)({reason:"SIGINT",status:0}))),g.default.on("SIGHUP",(()=>(0,D.exit)({reason:"SIGHUP",status:0}))),g.default.on("SIGTERM",(()=>(0,D.exit)({reason:"SIGTERM",status:0}))),p.default.isWorker&&g.default.on("disconnect",(()=>(0,D.exit)({reason:"disconnect",status:0}))),await(0,te.installSentry)(this)},c=function(){this.setInputHandler("--version",(()=>(0,M.stdoutWrite)({version:_.version}))),this.setInputHandler(x.ServiceExitCommand,(()=>(0,Z.later)((()=>(0,D.exit)({reason:x.ServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,M.stdoutWrite)(k.PromiseTimer.instance().report()))),this.setInputHandler(V.HealthCheckCommand,(async()=>(0,M.stdoutWrite)(await(0,z.getStatusSummary)({refresh:!0}))))},d=async function(e){if(f(this,s,"f").debug("onLine()",{line:e,ending:this.ended||(0,E.ending)()}),await this.setup_(),e.startsWith("--")){const t=e.split(/\s+/,1)[0],i=f(this,a,"f").get(t);null==i?(f(this,s,"f").error("onLine(): unknown command",{line:e,knownCommands:[...f(this,a,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else f(this,s,"f").error("onLine(): failed to process",{line:e})}},56992:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calcVolumesTTL=t.setVolumesTTL=void 0;const r=i(19851),s=i(50213),n=i(76596),a=i(87290),o=i(28874),l=i(2858),u=i(63870),c=i(7014),d=i(42659),h=i(31586),f=i(12168),m=(0,r.lazy)((()=>(0,s.mkLogger)("SetVolumesTTL")));async function p(){if(!(0,l.libraryHasSettings)())return;const e=[],t=await(0,c.volumes)(),i=o.Settings.minDiskFreeGb.defaultValue*f.GB;for(const r of[(0,a.libraryOriginalsDirPosixFile)(),(0,a.libraryPreviewsDirPosixFile)()]){const s=await(0,c.bestVolumeForPath)(r,t);if(null==s)return void m().warn("Can't find volume for "+r+", using default TTL for volumes()");if(s.availablethis.maybeRunChunk(),intervalMs:7*N.secondMs,onEnd:()=>w(this,r,"m",a).call(this),rank:T.EndableRanks.first,endTimeoutMs:C.Settings.taskTimeoutMs.valueOrDefault}),r.add(this),this.recentlyProcessed=new P.TTLArray(N.minuteMs),s.set(this,[]),this.taskCount=(0,v.lazy)((()=>W.Task.count())),d.set(this,(0,v.lazy)((()=>{this.logger.debug("status",this.state())}),((0,b.isTest)()?1:30)*N.secondMs)),f.set(this,(()=>this.maybeRunChunk())),m.set(this,(0,v.lazy)((()=>this.logger.info("runChunk(): no-op",{isPaused:(0,O.isPaused)(),isFull:this.p.isFull(),isTooBusy:(0,A.isTooBusy)(),whyDoNotRun:(0,I.whyDoNotRun)(this),pendingWorkCount:this.pendingWorkCount(),queueItemCount:this.taskCount(),freeSlots:this.p.freeSlots()})),((0,b.isTest)()?1:30)*N.secondMs)),this.maybeRunChunk=(0,v.lazy)((()=>{setTimeout((()=>{this.ended||(0,E.ending)()||(w(this,r,"m",g).call(this),this.maybeRunChunk.unset())}),t.TaskListRunLaterMs)})),p.set(this,(0,v.lazy)((()=>{const e=C.Settings.minBusyPct.valueOrDefault,t=C.Settings.stuckCheckIntervalMs.valueOrDefault;if(e<=0||this.p.isIdle()||t<=0)return;const i=A.CpuUsage.instance().busyPct();if(this.logger.debug("maybeCheckForStuckTasks()",{cpuBusyPct:i,minBusyPct:e,stuckCheckIntervalMs:t}),!(0,V.gte)(i,e))for(const e of this.p.running)if(e.elapsedMs>t){const t=e.payload;this.logger.error("Stuck serial task. Aborting.",{task:t,elapsedMs:e.elapsedMs});const i="stuck after "+e.elapsedMs+"ms";t.abort(i),e.reject(new M.AbortError(i))}}),C.Settings.stuckCheckIntervalMs.valueOrDefault)),this.p=new k.Promises(e,L.maxConcurrentImports),this.p.ee.on("vacancy",this.maybeRunChunk),this.p.ee.on("drain",(()=>w(this,r,"m",l).call(this))),(0,x.ee)().on("resume",w(this,f,"f")),W.Task.ee.on("added",this.maybeRunChunk)}async awaitDrain(e=[],t=0){(0,R.isEmpty)(e)&&(e=W.TaskNames.values);const i=new z.Latch;return w(this,s,"f").push({l:i,taskNames:e,maxRemaining:t,who:(0,j.shortStack)()}),this.maybeRunChunk(),i}isRunnable(){return!this.p.isFull()}currentWorkCount(){return this.p.unsettledCount()}pendingWorkCount(){return this.taskCount()-this.currentWorkCount()}hasCapacity(e=C.Settings.taskListCap.valueOrDefault){return e<=0||this.taskCount()e.payload))}currentTasksByFn(e){return this.currentTasks().filter((t=>t.fn===e))}state(){return{...this.p.stats(),isDone:w(this,r,"m",l).call(this),freeSlots:this.p.freeSlots(),pendingWork:this.taskCount(),next10:w(this,r,"m",h).call(this,10).map((e=>e.toString())),recentlyProcessedLast10:this.recentlyProcessed.slice(-10).map((e=>e.toString())),isRunnable:this.isRunnable()}}doNotStartMoreWork(){return(0,E.ending)()||this.ended||(0,O.isPaused)()||this.p.isFull()||(0,A.isTooBusy)()||(0,I.doNotRun)(this)||0===this.pendingWorkCount()}}t.TaskList=U,s=new WeakMap,d=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,r=new WeakSet,n=function(){this.taskCount.unset()},a=async function(){(0,x.ee)().off("resume",w(this,f,"f"));const e=new M.AbortError((0,E.ending)()?"service ending":"TaskList ended");for(const t of w(this,s,"f"))t.l.reject(e);await this.p.awaitAll()},o=function(){(0,R.filterInPlace)(w(this,s,"f"),(e=>e.l.isPending())),W.Task.dbl.runf((e=>e.delete().where("retries","<",0))),w(this,r,"m",n).call(this)},l=function(){if(this.ended)return;if(w(this,r,"m",o).call(this),(0,R.isEmpty)(w(this,s,"f")))return;const e=W.Task.countTaskNames();for(const t of this.p.deferreds){const i=t.name;e[i]=(e[i]??0)+1}for(const t of w(this,s,"f"))(0,F.sum)(t.taskNames.map((t=>e[t]??0)))<=t.maxRemaining&&t.l.resolve()},u=function(){return(0,R.uniq)(this.currentTasks().filter((e=>e.isSerial)).map((e=>e.fn)))},c=function(){return this.currentTasks().map((e=>e.id))},h=function(e){return 0===e?[]:W.Task.ops().allf((t=>(t=W.Task.orderBy(t.distinct().whereNotIn("id",w(this,r,"m",c).call(this)).whereNotIn("fn",w(this,r,"m",u).call(this))),(0,V.gt0)(e)&&(t=t.limit(e)),t)))},g=function(){if(w(this,r,"m",n).call(this),w(this,p,"f").call(this),this.doNotStartMoreWork())w(this,m,"f").call(this);else{w(this,d,"f").call(this);const e=this.p.freeSlots(),t=w(this,r,"m",h).call(this,e);this.logger.debug("runChunk():",{freeSlots:e,next:t});for(const e of t)this.p.enqueue({name:this.name,payload:e,l:()=>w(this,r,"m",y).call(this,e),serialId:e.isSerial?e.fn:void 0})}w(this,r,"m",l).call(this)},y=async function(e){try{await(0,D.time)("task."+e.fn,e._run())}catch(t){this.logger.warn("Failed to run task",{task:e,error:t})}finally{this.maybeRunChunk()}},U.instance=(0,B.defer)((()=>(0,S.isTaskListManager)()?new U:void 0))},44834:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitWhenDone=void 0,t.ExitWhenDone="--exit-when-done"},21200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitWhenDoneArg=void 0;const r=i(28874),s=i(38639),n=i(44834);t.ExitWhenDoneArg={beforeParse:e=>e.option(n.ExitWhenDone,"Exit after jobs are completed. Defaults to false unless paths are specified on the command line."),afterParse:e=>{(0,s.isTrue)(e.exitWhenDone)&&(r.Settings.exitWhenDone.envValue=!0)}}},2775:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ForceArg=void 0;const r=i(28874),s=i(38639);t.ForceArg={beforeParse:e=>e.option("--force","Deletes prior cached directory metadata, and forces directory contents to be re-scanned."),afterParse:async e=>{(0,s.isTrue)(e.force)&&(r.Settings.forceSync.envValue=!0)}}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},12195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoFilterArg=void 0;const r=i(4175),s=i(38639);t.NoFilterArg={beforeParse:e=>e.option("--no-filter","Disables import filters. All paths will try to be imported, even if they are too small or are missing tags. See https://photostructure.com/faq/why-is-my-file-missing/ ."),afterParse:async e=>{(0,s.isFalse)(e.filter)&&(0,r.disableAllFilters)()}}},52288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RebuildArg=void 0;const r=i(28874),s=i(38639);t.RebuildArg={beforeParse:e=>e.option("--rebuild","Rebuild your library by re-importing all your photos and videos (slow!) https://photostructure.com/faq/sync-vs-rebuild/"),afterParse:async e=>{(0,s.isTrue)(e.rebuild)&&(r.Settings.forceRebuildLibrary.envValue=!0)}}},46628:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(47783),c=i(97573),d=i(42231),h=i(40958),f=i(22573),m=i(68708),p=i(75020),g=i(54993),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function w(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function v(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(w));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...v(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...v(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=v},88224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(28874),o=i(42231),l=i(40958),u=i(20214),c=i(43487),d=i(46628),h=i(63175),f=i(4407),m=i(58886),p=i(32646),g=i(48144),y=i(60047),w=i(6186),v=i(42003),b=i(43723),S=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function P({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];if(t=(0,l.uniqBy)([e,...t],(e=>e.nativePath)),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,y.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),a.Settings.tagGeo.valueOrDefault)for(const e of t){const t=await(0,p.geoTagFile)(e);if(null!=t){u.push(t);break}}await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,b.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,g.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,v.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{S().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const P=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(w.normalizeTagRoot),o.joinTagPath)),M=await(0,w.tagDeltas)(i,P);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:P,result:M}),M}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await P({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=P},63175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(47783),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},4407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(47783),h=i(40958),f=i(55835),m=i(31586),p=i(75020),g=i(54993),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),w=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function v(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:v(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(w()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),w.unset()})),t.yearToOrdinal=v,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=_,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(r.date)}},58886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(19851),s=i(50213),n=i(42231),a=i(21404),o=i(40958),l=i(89937),u=i(75020),c=i(54017),d=i(94448),h=i(69032),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},32646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTagFile=t.geoTag=void 0;const r=i(48884),s=i(56519),n=i(50213),a=i(28874),o=i(47783),l=i(14245),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)((()=>(0,n.mkLogger)("curators.GeoTagger")));function p(e){const t=a.Settings.tagGeoMaxDistanceKm.valueOrDefault;if(t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t))return void m().warn("geoTag(): GeolocationDistance too large, skipping geo tag",(0,f.pickDeep)(e,...l.GeolocationFields));const i=a.Settings.tagGeoSynonyms.synonymMap(),s=a.Settings.tagGeoTemplate.valueOrDefault.map((t=>(0,r.first)(i.get(t)??[t],(t=>(0,f.pluckDeep)(e,t)?.value)))),n=(0,c.compactBlanks)(s);return m().tap({msg:"geoTag",result:0===n.length?void 0:(0,c.compact)([u.TagRoots.Where,...n]),meta:{picked:s}})}t.geoTag=p,t.geoTagFile=function(e){return(0,s.thenMap)((0,o.readTags)(e),p)}},48144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(47783),h=i(97573),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),w=i(96249),v=i(55835),b=i(75020),S=i(54993),P=i(6186),M=i(43723),_=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),T=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return _().tap({msg:"extractDashDashTags()",result:(0,v.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,v.mapOr)(T(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function D(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>T.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=D;const k=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(k,(e=>(i.push(e),"")));s.push(...(0,v.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,w.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function F(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function C(e,t){const[i,s]=(0,r.partition)(x(e),M.isWhoTag),n=(0,w.flatten)(i.map(M.nameTag)),a=(0,m.uniq)((0,w.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=F([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=F,t.processKeywords=C,t.keywordTagFiles=async function(e,t){return C([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,w.flatten)(e.map(D)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,w.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},60047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(56519),s=i(28874),n=i(47783),a=i(75020),o=i(40958),l=i(22573),u=i(55835);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},6186:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhereRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(50213),s=i(28874),n=i(42231),a=i(75020),o=i(40958),l=i(22573),u=i(45599);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.WhereRoot={name:a.TagRoots.Where,ordinal:5},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,t.WhereRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Where,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase()))),g=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhereRoot,...e.slice(1)]:g.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},42003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[w(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function w(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}t.friendlySubtype=y,t.fixCase=w},43723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(19851),s=i(50213),n=i(28874),a=i(47783),o=i(28630),l=i(66039),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(v)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function w(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function v(e){if(!(0,d.blank)(e))return Array.isArray(e)?(w(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=w,t.nameTag=v},98348:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(48884),d=i(19851),h=i(23560),f=i(25764),m=i(38836),p=i(99331),g=i(5916),y=i(12959),w=i(55332),v=i(91872),b=i(80632),S=i(51040),P=i(44955),M=i(15056),_=i(70025),T=i(57159),E=i(18454),D=i(28874),k=i(5233),x=i(42659),F=i(31586),C=i(68708),A=i(30976),I=i(17036),O=i(27134),L=i(35052);class R extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=x.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),D.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*x.secondMs),this.migrate_=(0,g.lazyAsync)({desc:"db.migrate",later:async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{await(0,O.verifyDb_)((()=>this.db))}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||D.Settings.dbForceRecover.valueOrDefault)&&(E.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new I.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e}}}),this.tableInfo_=(0,d.lazy)((()=>(0,L.localTableInfo)(this.db)))}toJSON(){return(0,C.pick)(this,"schema","dbFile")}get isOpen(){return!0===l(this,n,"f")?.open}get inTransaction(){return this.isOpen&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(t||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,b.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new T.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===D.Settings.dbAutoVacuumMode.valueOrDefault&&(0,F.gt0)(D.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%D.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&(this.logger.info("running incremental_vacuum..."),l(this,n,"f")?.pragma("incremental_vacuum")),l(this,n,"f")}async verify_(){await(0,O.verifyDb_)((()=>this.db))}assertHeartbeat_(){const e=(0,A.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{this.logger.info("closing db",l(this,n,"f")),await(0,k.retryOnReject_)((()=>{!0===l(this,n,"f")?.open&&l(this,n,"f")?.close()}),{timeoutMs:D.Settings.dbBusyTimeoutMs.valueOrDefault,maxRetries:5,errorIsRetriable:_.isSqliteBusyError,retryDelay:x.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>this.db),(()=>(0,O.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db),(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db),(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,O.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,M.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,P.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,y.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,w.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=R,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,F.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},25470:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(66364),d=i(50213),h=i(23560),f=i(78406),m=i(25764),p=i(38836),g=i(99331),y=i(56038),w=i(12959),v=i(55332),b=i(76187),S=i(73209),P=i(28874),M=i(42659),_=i(75240),T=i(95700),E=i(22526),D=i(45648),k=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends f.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:m.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new p.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),m.EndableRanks.postdb,k),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,y.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,w.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:k,endableRank:m.EndableRanks.postdb,noopIfContested:!1});(0,h.isDbManager)()&&await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,b.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),await this.db.closeDb()},o=function(){return this.ended||(0,g.ending)()||(0,c.isSuspended)()}},22526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(19851),s=i(50213),n=i(92407),a=i(55332),o=i(44955),l=i(15056),u=i(87290),c=i(98314),d=i(38835),h=i(73209),f=i(95696),m=i(17217),p=i(18454),g=i(57902),y=i(28874),w=i(2858),v=i(40958),b=i(22573),S=i(42659),P=i(94448),M=i(98348),_=i(45648),T=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,w._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function k(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function F(e=k(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=k,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=F,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await F(u,t);o=new M.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,v.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},86859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(54557),s=i(50213),n=i(99331),a=i(56038),o=i(65753),l=i(66184),u=i(70417),c=i(28874),d=i(40958),h=i(22573),f=i(45599),m=i(96249),p=i(31586),g=i(51926),y=i(57038),w=i(21074),v=(0,f.defer)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,y.knex)()(this.tableName)}prep(e,t=!1){const i=(0,w.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return v().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&v().log((0,l.defaultLogLevel)(),i+"(): "+(0,w.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;v().throw(t,{method:i,...(0,w.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,a.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,g.replaceAll)((0,g.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,w.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,m.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}async batched(e){let t,i=0;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,o.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&(await e.onResults(t),i+=t.length)}while((0,d.isNotEmpty)(t)&&!(0,n.ending)()&&(null==e.maxResults||e.maxResults>i));return{resultCount:i,done:null==t||t.length<(0,o.maxBatchPluckSize)()}}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}async pluckBatched(e){let t=0;const i=(0,u.min)([e.limit??(0,o.maxBatchPluckSize)(),e.maxResults]);if(i<=0||(0,p.lte0)(e.maxResults))return{done:!1,resultCount:t};let r;for(;null==e.maxResults||e.maxResults<=0||t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},36908:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(42231),o=i(40958),l=i(76790),u=i(23838),c=i(31586),d=i(54993),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},57038:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(31832)),n=i(19851),a=i(56519),o=i(55835),l=i(68708);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},17036:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(77598),l=i(19851),u=i(50213),c=i(7282),d=i(37805),h=i(4867),f=i(51040),m=i(77740),p=i(38835),g=i(8769),y=i(57159),w=i(34102),v=i(73209),b=i(95696),S=i(43899),P=i(18454),M=i(28874),_=i(40958),T=i(42659),E=i(41400),D=i(98553),k=i(55835),x=i(34666),F=i(32639),C=i(45648),A=i(94715),I=i(27134);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,A.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,_.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,v.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:M.Settings.dbMaintenanceTimeoutMs.valueOrDefault},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=A.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,F.isFunction)(s);return o?await s.bind(A.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.info("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,w.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),(0,c.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{if((0,m.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,k.map)(e,(e=>e(r))),await(0,h.thenOrTimeoutError)({p:this.applyMigration_(r,i),timeoutMs:5*M.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch((e=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,C.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile(),r=(0,f.splitBatchSql)(i);if((0,_.isEmpty)(r))this.logger.info("No-op migration: "+e);else{t&&this.db.pragma("foreign_keys = OFF");for(const t of r)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,I.foreignKeyCheck_)(this.db)}}finally{t&&this.db.pragma("foreign_keys = ON")}}},94715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(97352),o=i(68852),l=i(81168),u=i(85810),c=i(42022),d=i(1971),h=i(79842),f=i(89724),m=i(17415),p=i(88600),g=i(20014),y=i(42231),w=i(87001),v=i(40958),b=i(55835),S=i(31586),P=i(97790),M=i(89937),_=i(54993),T=i(7656),E=i(36908),D=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),k=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function F(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function C(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)}function A(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>k.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=F,t.fix_root_tags=C,t.isoToPrecisionMs=A,t.Migrations={fix_root_tags:C,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},A),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},w.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,_.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},F),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,v.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:T.rebuildTagAssetCounts,create_tag_fts:e=>{e.exec("DROP TABLE IF EXISTS tag_fts"),e.exec("CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize=\"unicode61\");")},rebuild_null_island:e=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,y.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")}}},27134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(14121),s=i(19851),n=i(50213),a=i(84777),o=i(12959),l=i(5531),u=i(91872),c=i(99315),d=i(76187),h=i(51040),f=i(38835),m=i(57159),p=i(29882),g=i(95696),y=i(89966),w=i(38156),v=i(28874),b=i(63870),S=i(5233),P=i(42659),M=i(41400),_=i(50357),T=i(98553),E=i(56409),D=i(31586),k=i(20214),x=i(51926),F=i(12168),C=i(59455),A=i(54993),I=i(94448),O=i(9508),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){L().debug("pragmaOrThrow_()",{db:N(e),db_open:e?.open,pragma:t,okResult:i});const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(r,i)||L().throw(`${t} failed for ${N(e)}: ${(0,T.stringify)({result:r})}`)}function N(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}function B(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function j(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function z(e){const t=(0,C.toA)(e.pragma("foreign_key_check"));t.length>v.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:v.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function V(e){await(0,u.handleDbRetries_)("db.quickCheck",e,B),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",e,j),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",e,z)}function W(e){return(0,O.withDbSync)(e,V,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,C.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,I.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=B,t.integrityCheck_=j,t.foreignKeyCheck_=z,t.verifyDb_=V,t.verifyDbFile_=W,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=v.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,C.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,D.gt0)(n?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):n};const U=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*F.MiB,await(0,d.sqliteSizeBytes)(i)),n=new w.PushProgressObserver({path:(0,A.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,A.toS)(e);U.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),await W(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,k.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,k.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},21074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(48884),s=i(68852),n=i(81168),a=i(12943),o=i(96249),l=i(98553),u=i(31586),c=i(68708),d=i(32639),h=i(54993);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},35052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(22573),s=i(23838);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},9508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(80632),s=i(28874),n=i(30301),a=i(54993);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)((()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i})));try{return t((function(){const e=o();return e.open?e:o.refresh()}))}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const n=(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i});try{return await t(n)}finally{n.close()}}},43487:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(48884),c=i(19851),d=i(50213),h=i(88158),f=i(45393),m=i(56519),p=i(89724),g=i(38835),y=i(74128),w=i(79847),v=i(28874),b=i(47783),S=i(38010),P=i(40958),M=i(76790),_=i(75761),T=i(38639),E=i(11371),D=i(98553),k=i(55835),x=i(31586),F=i(20214),C=i(59455),A=i(64526),I=i(4407),O=i(54017),L=i(48722),R=i(37094),N=i(45295),B=i(39604),j=i(48723),z=i(41507),V=i(72761),W={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class U extends V.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,b.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,T.isTrue)(t.shown)})}const t=R.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(W):e.andWhere(W)}static findUnhiddenById(e){return(0,x.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return A.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{unlinkAssetFiles:i});const l=n.getAssetFiles({refresh:!0});if(t){(0,B.upsertToShaBlockslist)(...l.map((e=>e.sha)));for(const e of l)(0,y.syncReport)().onProgress({from:"Asset.remove",path:await e.getNativePath()??e.uri,state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}N.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),R.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&j.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,w.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(N.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,k.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,x.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,x.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,L.toAssetId)(this)}renderCaption(e){return(0,k.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:j.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,P.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return j.Tag.ops().all(j.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??N.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:j.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:j.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,P.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,x.gt0)(e)&&!t.includes(e)))),r=(0,P.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,x.gt0)(e)&&t.includes(e))));if((0,P.isEmpty)(i)&&(0,P.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&j.Tag.deltaAssetCountAndAncestors(t,-1),(0,P.isEmpty)(i)||N.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,P.isEmpty)(r)||N.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,P.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&j.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,z.coalesceStreams)((0,P.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,M.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,T.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,x.gt0)(this.id)&&(0,x.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,D.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,T.isTrue)(e.shown)))??this.getAssetFiles({refresh:!0})?.find((e=>(0,T.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,F.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,_.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,E.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,_.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,_.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,F.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,k.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,x.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,T.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=U,s=U,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("Asset.version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},U.$tableName="Asset",U.$uniqueColumnName="id",U.$booleanFields=["shown","hidden"]},54017:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(76760),o=i(19851),l=i(88158),u=i(45393),c=i(68852),d=i(81168),h=i(13991),f=i(54296),m=i(56519),p=i(76490),g=i(89724),y=i(98314),w=i(38835),v=i(8769),b=i(29882),S=i(95696),P=i(62105),M=i(74128),_=i(35721),T=i(69589),E=i(28874),D=i(28544),k=i(16170),x=i(45200),F=i(34238),C=i(87001),A=i(42233),I=i(21404),O=i(40958),L=i(17586),R=i(22573),N=i(38639),B=i(42659),j=i(33374),z=i(50357),V=i(75240),W=i(11371),U=i(55835),q=i(31586),H=i(68708),G=i(34666),$=i(89937),J=i(75020),K=i(64526),Z=i(41844),Y=i(43487),X=i(48723),Q=i(94710),ee=i(72761);class te extends ee.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>F.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=Y.Asset.shownUnhidden(e.q).join("AssetFile","AssetFile.assetId","Asset.id").where("AssetFile.version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("AssetFile.updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("AssetFile.mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("AssetFile.uri",i+"%");return t})).orderBy("AssetFile.id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,A.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,A.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("AssetFile.id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,q.gt0)(e)?te.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,R.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(te.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=te.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=te.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:te.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,H.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith($.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,H.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,U.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,q.closeTo)(i.mtime,this.mtime,2*B.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return E.Settings.forceSync.valueOrDefault?E.Settings.forceSync.key+"=true":this.version!==u.AssetFileVersion?"AssetFileVersion: "+this.version+" != "+u.AssetFileVersion:this.whyNotMatchesFile(e)}async inSyncWithFile(e){const t=await this.whyNotInSyncWithFile(e);return this.logger().tap({msg:"inSyncWithFile()",result:null==t,meta:{whyNotInSync:t}})}async fileFields_(e){const t=e??await this.posixFile_();return null==t?void 0:await(0,h.assetFileStatFields_)(t)}isInLibrary(){return this.uri.startsWith($.PS_LIBRARY_PROTOCOL)}async isNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){const t=await this.whyNotNoop(e);return this.logger().tap({msg:"isNoop()",result:null==t,meta:{whyNotNoop:t}})}async whyNotNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){if(!0===e.forceSync)return"forceSync is true";if(!(0,q.gt0)(this.id))return"missing .id";if(!(0,q.gt0)(this.assetId))return"missing .assetId";{const e=await this.whyNotInSyncWithFile();if(null!=e)return e}if(await(0,Z.mayCopyAssetsToLibrary)()){const e=K.Library.instanceRequired_().assetFileRepository(),t=e.whyNotCopyFile(await this.posixFile_());if((0,R.blank)(t)&&null==await e.existingLibraryAssetFile(this))return"need to copy into library"}this.syncState=M.AssetFileSyncStates.noop}isVersionUpToDate(){return(0,G.gte)(this.version,u.AssetFileVersion)}async siblingCount(){return te.dbl.pluckFirstf((e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=(0,T.forceContextOrSetting)()){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,q.gt0)(this.id)&&!t.forceSync)return void(null==this.syncState&&(this.upsert(),this.syncState??(this.syncState=M.AssetFileSyncStates.noop)));const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),!0!==t.skipAssetRepair&&Q.Task.addOne("repairAsset",{assetId:this.assetId}),this;if(!1===i){const i=await this.updateFromFile_(e,t);return this.syncState??(this.syncState=null==i?M.AssetFileSyncStates.noop:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,H.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e,t=(0,T.forceContextOrSetting)()){const i=Date.now(),r=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&!0!==t.forceSync&&await this.matchesFile(e))return void r.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void r.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,R.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,H.assignAllFields)(this,(0,H.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,r.elapsed("finished",Date.now()-i,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,H.assignFields)(this,(0,H.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...te.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,q.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,x.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,R.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,R.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,R.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+w.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),D.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,j.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,N.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===W.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,v.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=F.URI.parse(this.uri),t=(0,U.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=F.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,L.at)((0,L.at)(e,-1)?.tagPath,-1)}(0,z.eql)(e[0]?.tagPath,[J.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===$.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,L.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===J.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===$.PS_LOCAL_FILE_SCHEME){const t=F.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,H.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,N.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:ie(this.createdAt),updatedAtLocale:ie(this.updatedAt)})))}get isVideo(){return(0,k.isVideoMimeType)(this.mimetype)}}function ie(e){return(0,U.map)(e,(e=>(0,V.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=te,r=new WeakSet,s=function(){if((0,R.blank)(this.uri))return"blank uri";if((0,R.blank)(this.sha))return"blank sha";if(!(0,q.gt0)(this.width))return"missing width";if(!(0,q.gt0)(this.height))return"missing height";if(!(0,q.gt0)(this.capturedAtLocal))return"missing capturedAtLocal";if(!(0,q.gte0)(this.capturedAtPrecisionMs))return"missing capturedAtPrecisionMs";if(E.Settings.useImageHashes.valueOrDefault){const e=[];for(const t of["dctHash","diffHash","meanHash"])(0,R.blank)(this[t])&&e.push(t);if(1===e.length)return"missing image hash: "+e[0];if(e.length>1)return"missing image hashes: "+e.join(", ")}return this.isVersionUpToDate()?void 0:"outdated version"},te.$tableName="AssetFile",te.$uniqueColumnName="uri",te.$booleanFields=["shown"],te.$transientFields=["nativePath","syncState"]},48722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(76596),s=i(31586);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},37094:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},45295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},61204:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(19851),s=i(50213),n=i(97352),a=i(75020),o=i(4407),l=i(48723),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},95700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(19851),s=i(56038),n=i(28874),a=i(42659),o=i(41400),l=i(69032),u=i(61204),c=i(49796);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h());try{await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())}catch{}};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},55046:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(57975),n=i(50213),a=i(7282),o=i(65211),l=i(40958),u=i(38639),c=i(45599),d=i(31586),h=i(68708),f=i(34666),m=i(54993),p=i(57038),g=i(94448),y=i(33572),w=i(63872);class v{constructor(){this.$instanceId=(0,a.isTest)()?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new w.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if((0,a.isProd)())throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}update(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("update()",{self:this.toJSON()}),this.class().ops().updateOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=v,r=v,v.$schema="models",v.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),v.db=g.modelDb,v.$pkColumnNames=["id"]},94448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},33572:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(50213),s=i(40958),n=i(22573),a=i(38639),o=i(97790),l=i(51926),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},63872:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(48884),m=i(19851),p=i(50213),g=i(81168),y=i(48299),w=i(12943),v=i(38835),b=i(34102),S=i(28874),P=i(40958),M=i(76790),_=i(22573),T=i(50357),E=i(96249),D=i(98553),k=i(55835),x=i(31586),F=i(68708),C=i(59455),A=i(86859),I=i(33572);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,I.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new A.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,k.mapOr)(this.db(),(e=>e.isOpen),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,w.toDbValued)(t);return(0,F.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,F.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,C.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,C.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+v.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+v.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,k.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+v.NonRetriableErrorFlag+v.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);if(null==s)return;return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){const t=[],i=this.allf((i=>{for(const r of e){const e=this.model.hasId(r)?this.model.pickId(r):this.$pickModelUcn(r);null!=e?(t.push([r,e]),i=i.orWhere(e)):h(this,s,"f").warn("reload(): given insufficient partial model",{fragment:r})}return i})),n=[];for(const[e,a]of t){const t=i.find((e=>(0,T.eqlSubset)(a,e)));if(null==t)h(this,s,"f").warn("reload(): failed to find result in db",{prior:e,dbArr:i});else{const i=h(this,r,"m",u).call(this,e);h(this,r,"m",l).call(this,i,t),i!==e&&h(this,r,"m",l).call(this,i,t),n.push(t)}}return n}upsert(e){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const t=this.columnNames(),i=[];for(const s of(0,f.batches)((0,C.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=new Map,n=new Set,a=(0,P.compact)(s.map((e=>this.fromJSON(e))));for(const t of a){const i=(0,D.stringify)(this.$pickModelUcn(t));e.set(i,t),this.model.hasId(t)||n.add(i),t.$beforeUpsert()}h(this,r,"m",c).call(this,a.map((e=>e.$toDbJSON(t))));const o=this.reload(a),l=new Map(o.map((e=>[(0,D.stringify)(this.$pickModelUcn(e)),e])));for(const e of a){const t=(0,D.stringify)(this.$pickModelUcn(e)),r=l.get(t)??e;n.has(t)&&r.$afterInsert(),r.$afterUpsert(),i.push(r)}}return i}delete(e){const t=(0,C.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,F.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,F.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},20958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(19851),s=i(50213),n=i(88158),a=i(99331),o=i(70025),l=i(8769),u=i(22573),c=i(98553),d=i(50989),h=i(72761);t.OperationNames=(0,d.strEnum)("rebuildLibrary","forceRestartSync");const f=(0,r.lazy)((()=>(0,s.mkLogger)("model.Operation")));class m extends h.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(m.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return m.getFirstPendingOp(e)??m.ops().insertOne(e)}static getFirstPendingOp(e){return f().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,u.blank)(e?.name)?f().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return f().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce_(e,t,i=n.identity){const r=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=r)return void f().debug("applyOnce(): already done",{priorCompleted:r});const s=this.ops().insertOne(e);try{const e=await t(s);return(0,a.ending)()||s.markCompleted(),e}catch(t){if((0,o.isRedoableError)(t))return void f().info("applyOnce(): redoable error",{crit:e,error:t});throw(0,l.onError)("Operation.applyOnce(): "+(0,c.stringify)(e),t),t}}markCompleted(){null==this.completedAt&&(this.completedAt=Date.now(),this.upsert())}}t.Operation=m,m.$tableName="Operation",m.$uniqueColumnName="id",m.$useCache=!1},49796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.toPct=void 0;const r=i(48161),s=i(1708),n=i(48884),a=i(50213),o=i(28874),l=i(40958),u=i(42659),c=i(45599),d=i(98553),h=i(55835),f=i(31586),m=i(68708),p=i(67478),g=i(51926),y=i(59455),w=i(54993),v=i(76386),b=i(33572),S=i(55009),P=i(72761),M=(0,c.defer)((()=>(0,a.mkLogger)("model.Progress")));function _(e){return null==e||!(0,f.isNumber)(e)||e<0||e>100?void 0:(0,f.sigFigs)(e,3)}t.toPct=_;const T=(0,g.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function E(){const e=o.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*u.dayMs}t.defaultMinCreatedAt=E;class D extends P.TimestampedModel{static vacuum(e=o.Settings.progressRetentionDays.valueOrDefault*u.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t)));for(const e of(0,n.batches)(i,o.Settings.dbBatchSelectSize.valueOrDefault))S.ProgressMeta.dbl.runf((t=>t.whereIn("progressId",e).delete())),D.dbl.runf((t=>t.whereIn("id",e).delete()))}static countCompletedDirectorySyncs(){return this.dbl.pluckFirstf((e=>e.where({state:"done"}).whereNotNull("completedAt").where("uri","like","ps%")))}static times(){return M().tap({msg:"times()",result:this.dbl.all({sql:T})})}static insertNew(e){const t=(0,h.map)(e.dek,d.stringify);return this.ops().insertOne({...(0,m.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&this.assignFromPojo(e),super.upsert()}$beforeUpsert(){super.$beforeUpsert(),null==this.id&&(this.pid??(this.pid=s.pid),this.hostname??(this.hostname=(0,r.hostname)())),"done"===this.state&&(this.completedAt??(this.completedAt=Date.now())),this.completePct=_(this.completePct),this.incompletePct=_(this.incompletePct),this.scanningPct=_(this.scanningPct)}$afterUpsert(){super.$afterUpsert(),(0,v.tellWebProgressUpdated)()}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,l.compactBlanks)((0,p.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,d.stringify)((0,l.compactBlanks)((0,y.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,m.omit)(e,"volume","uri"))}getMeta(){return S.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncomplete(e=E()){return this.logger().tap({msg:"priorIncompleteProgress()",result:D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc")))})}getLastCompletedAt(e=E()){return D.dbl.pluckFirstf((t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e)))}getLastIncompleteStartAt(){return D.dbl.pluckFirstf((e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0)))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),S.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,l.diff)(t.map((e=>e.name)),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),S.ProgressMeta.ops().upsert((0,m.entries)(e).map((([e,t])=>({progressId:this.id,name:e,value:(0,w.toS)(t)})))),(0,l.isNotEmpty)(i)&&S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).whereIn("name",i).delete()))}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),S.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,m.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},55009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},39604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(19851),s=i(50213),n=i(95696),a=i(40958),o=i(22573),l=i(86859),u=i(94448),c=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),d=(0,r.lazy)((()=>new l.DbRequest(u.modelDb,"ShaBlocklist")));function h(e){return null!=(0,u.modelDb)()&&!(0,o.blank)(e)&&c().tap({msg:"isShaBlockslisted",result:null!=d().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}function f(...e){if(null==u.modelDb.prior())return;const t=(0,a.uniq)(e).map((e=>({sha:e})));return(0,a.isEmpty)(t)?void 0:d().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,u.modelDb)())return null;const t=h(await n.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=h,t.upsertFileToShaBlockslist=async function(e){if(null==(0,u.modelDb)())return;const t=await n.PosixFile.for(e).sha();return null==t?void 0:f(t)},t.upsertToShaBlockslist=f},48723:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(56038),o=i(34102),l=i(19851),u=i(50213),c=i(36372),d=i(97352),h=i(28874),f=i(81168),m=i(42231),p=i(75020),g=i(40958),y=i(22573),w=i(42659),v=i(41400),b=i(50357),S=i(55835),P=i(31586),M=i(34666),_=i(20214),T=i(51926),E=i(59455),D=i(12168),k=i(6186),x=i(57038),F=i(21074),C=i(7656),A=i(43487),I=i(48722),O=i(45295),L=i(98784),R=i(41507),N=i(72761),B=4*w.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,v.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:A.Asset.dbl.pluckFirst(A.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset(),this.ops().clearDbCache()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{r.clear();for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.update({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,F.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:C.RecursiveAssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),this.ops().upsertOne(i)}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return A.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();return(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)})),r.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(A.Asset.dbl.all(t).map(I.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return A.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:C.RecursiveAssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?A.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(A.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(I.toAssetId))));for(const t of r)t.assetIdA.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(this.id??0),"Asset.id",i)).limit(t))).map(I.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!0,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=A.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(k.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e}),B);const V=(0,l.lazy)((()=>A.Asset.dbl.pluckFirstf((e=>e.count()))),w.minuteMs)},98784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(38156),s=i(3127),n=i(40958),a=i(41400),o=i(94715),l=i(55046),u=i(48723);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=new r.PushProgressObserver({op:"Rebuilding tag search index"},u.Tag.dbl.pluckFirstf((e=>e.count("*")))),t=this.dbl.db();o.Migrations.create_tag_fts(t.db),await u.Tag.ops().batched({qb:e=>e,onResults:t=>(this.$logger().throwIfAborted_(),this.insertFts(t),e.incrProgress(t.length),(0,a.delay)(1))}),e.completed()}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},41507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},94710:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Task=t.StaleTaskError=t.InvalidTaskError=t.TaskNames=t.Tasks=t.testTask=void 0;const c=i(78474),d=i(22454),h=i(23560),f=i(12089),m=i(76740),p=i(22911),g=i(99331),y=i(31562),w=i(38835),v=i(70025),b=i(8769),S=i(74128),P=i(28874),M=i(37692),_=i(40958),T=i(22573),E=i(42659),D=i(45599),k=i(98553),x=i(49769),F=i(68708),C=i(50989),A=i(59455),I=i(58723),O=i(34274),L=i(90901),R=i(61989),N=i(93755),B=i(69032),j=i(55046);t.testTask=(0,f.shim1)({name:"testTask",impl:async e=>{}}),t.Tasks={applyDeleted:I.applyDeleted,applyExcluded:I.applyExcluded,runTagMaintenance:B.runTagMaintenance,updateAssetFile:N.updateAssetFile_,repairAsset:async function(e){e.forceSync=!0,e.skipPreviews=!0,e.skipAssetTagging=!0;const t=await(0,R.updateAsset_)(e);return(0,_.isNotEmpty)(t?.assetIdsToUpdate)&&q.add(t?.assetIdsToUpdate.map((t=>({fn:"repairAsset",args:{...e,assetId:t},priority:W.repairAsset+1})))),null!=t&&!0!==t.deleted&&(0,T.blank)((0,A.toA)(t.rejected).join(""))&&(0,T.blank)(t.error)&&q.addOne("assetPostUpsertTasks",(0,F.omit)(e,"skipPreviews","skipAssetTagging")),t},assetPostUpsertTasks:L.assetPostUpsertTasks,syncFile:O.importFileToResult_,testTask:t.testTask},t.TaskNames=(0,C.strEnum)(...(0,F.keys)(t.Tasks));class z extends Error{}t.InvalidTaskError=z;class V extends Error{}t.StaleTaskError=V;const W={applyDeleted:16,applyExcluded:16,runTagMaintenance:14,updateAssetFile:13,repairAsset:12,assetPostUpsertTasks:10,syncFile:0,testTask:-1},U=["repairAsset"];class q extends j.Model{constructor(){super(...arguments),r.add(this),o.set(this,(0,D.defer)((()=>new m.Abortable)))}static countTaskNames(){const e={};for(const t of s.dbl.allf((e=>e.select("fn").count().groupBy("fn"))))e[t.fn]=t["count(*)"];return e}static orderBy(e){return e.orderBy([{column:"priority",order:"desc"},{column:"retries",order:"desc"},{column:"id",order:"asc"}])}static count(){return s.dbl.pluckFirstf((e=>e.count("id")))}static freeSlots(){return P.Settings.taskListCap.valueOrDefault-s.count()}static countByFn(e){return s.dbl.pluckFirstf((t=>t.where({fn:e}).count("id")))}static nextByFn(e,t=(e=>e)){return s.ops().allf((i=>s.orderBy(t(i.where({fn:e})))))}set args(e){this.argsJSON=(0,k.stringify)(e)}get args(){const e=(0,k.parseJSON)(this.argsJSON);return(0,F.notEmptyObj)(e)&&(e.halt=u(this,o,"f").call(this)),e}get isSerial(){return U.includes(this.fn)}toString(){return`Task#${this.fn}(${this.argsJSON})`}static addOne(e,t){return s.add([{fn:e,args:t}])[0]}static add(e,t=!1){if((0,_.isEmpty)(e))return[];const i=s.ops().upsert(e.map((e=>({fn:e.fn,argsJSON:(0,k.stringify)(e.args)})),t));return s.ee.emit("added",i),(0,h.isTaskListManager)()||(0,M.addStateEvent)("checkTasks"),i}$beforeUpsert(){this.priority??(this.priority=W[this.fn]),this.retries??(this.retries=P.Settings.maxRetries.valueOrDefault)}donePromise(){return(0,h.isTaskListManager)()?(0,x.getOrSet)(u(s,s,"f",n),this.id,(()=>new p.Deferred(this.toString(),{payload:this}))):(0,y.untilTrue)((()=>null==s.ops().findById(this.id)),{intervalMs:E.secondMs})}abort(e){this.logger().warn("aborting task",{reason:e,task:this}),u(this,o,"f").call(this).abort(e),this.delete(),(0,T.blank)(this.args.path)||(0,S.syncReport)().onProgress({path:this.args.path,from:this.fn,state:S.SyncFileStates.failed,details:e})}async _run(){if(this.retries<0)throw this.logger().warn(".run(): too many retries"+w.InternalErrorFlag,{job:this}),this.delete(),new z;if(!u(this,r,"m",l).call(this))throw this.logger().warn(".run(): someone already started this task",{job:this}),new V;try{const e=Date.now(),i=await t.Tasks[this.fn](this.args);return this.logger().throwIfAborted_(u(this,o,"f").prior()),s.taskResolvedCounts.incr(this.fn),s.ee.emit("resolved",this,i,Date.now()-e),this.delete(),u(s,s,"f",n).get(this.id)?.resolve(i),i}catch(e){if((0,g.ending)())throw this.logger().info("task failed, but we're ending. We'll leave it for next time.",{task:this}),e;throw s.taskRejectedCounts.incr(this.fn),(0,v.isRedoableError)(e)?(this.retries++,this.priority--,this.upsert()):!0===(0,v.isRetriableError)(e)&&this.retries>=0?this.logger().warn("run failed, but we can retry it later",{task:this,error:e}):(s.ee.emit("rejected",this,e),this.delete(),u(s,s,"f",n).get(this.id)?.reject(e),(0,b.onError)(this.toString()+" failed",e)),e}finally{u(s,s,"m",a).call(s)}}}t.Task=q,s=q,o=new WeakMap,r=new WeakSet,a=function(){for(const[e,t]of u(this,s,"f",n).entries())t.isSettled&&u(this,s,"f",n).delete(e)},l=function(){const e=this.retries;if(1===s.dbl.runf((t=>t.where({id:this.id,retries:e}).update({retries:e-1}))).changes)return--this.retries,!0;{const e=this.toJSON(),t=this.reload();return this.logger().warn(".#decrRetries(): someone already started this task",{before:e,reloaded:t}),!1}},q.$tableName="Task",q.$uniqueColumnName="fn,argsJSON",q.$useCache=!1,q.taskResolvedCounts=new d.CountingSet,q.taskRejectedCounts=new d.CountingSet,q.ee=new c.EventEmitter,n={value:new Map}},72761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),this.createdAt??(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},58723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyExcluded=t.applyDeleted=void 0;const r=i(50213),s=i(43487),n=(0,r.mkLogger)("ops.ApplyRemovable");async function a(e,t,i){const r=e?"Deleting":"Excluding",a=e?"deletedAt":"excludedAt";await s.Asset.dbl.batched({qb:e=>e.select("id").where("shown",0).andWhere(a,"<=",t),onResults:async t=>{for(const a of t){n.throwIfAborted_(i);try{await s.Asset.remove({assetId:a,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){n.error(r+" failed",{assetId:a,error:e})}}}})}t.applyDeleted=function(e){return a(!0,e.createdAt,e.halt)},t.applyExcluded=function(e){return a(!1,e.createdAt,e.halt)}},76386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)((()=>(0,s.mkLogger)("progress.Progress")));t.ProgressRateMs=(0,r.lazy)((()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:1.5))),t.tellWebProgressUpdated=(0,r.lazy)((async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch((e=>h().warn(".tellWebProgressUpdated: failed",{error:e})))}),(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},22968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeRebuildLibrary=t.forceRebuildLibraryLater=t.rebuildLibraryOperationCrit=void 0;const r=i(45393),s=i(28874),n=i(98553),a=i(43487),o=i(54017),l=i(20958),u=i(33567);function c(){return{name:l.OperationNames.rebuildLibrary,value:(0,n.stringify)({AssetVersion:r.AssetVersion,AssetFileVersion:r.AssetFileVersion})}}t.rebuildLibraryOperationCrit=c,t.forceRebuildLibraryLater=function(){a.Asset.dbl.runf((e=>e.update({version:0}))),o.AssetFile.dbl.runf((e=>e.update({version:0}))),l.Operation.dbl.runf((e=>e.where(c()).delete()))},t.maybeRebuildLibrary=async function(){return s.Settings.skipLibraryRebuild.valueOrDefault?void 0:l.Operation.applyOnce_(c(),(()=>(new u.LibraryRebuild).doneLatch))}},33567:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LibraryRebuild=void 0;const c=i(19851),d=i(83412),h=i(25764),f=i(8769),m=i(76752),p=i(28874),g=i(15674),y=i(22573),w=i(42659),v=i(31586),b=i(12168),S=i(12236),P=i(35580),M=i(49796),_=i(94710),T=i(18209);class E extends d.DoneWrapper{constructor(){super("LibraryRebuild",(()=>u(this,r,"m",a).call(this)),h.EndableRanks.first),r.add(this),this.assetFileEta=new m.ETA,this.assetEta=new m.ETA,this.assetFilesUpdated=0,this.assetsUpdated=0,this.initialAssetTodoCount=(0,T.outdatedAssetCountSync)(),this.initialAssetFileTodoCount=(0,T.outdatedAssetCountSync)(),this.assetFileTodo=(0,c.lazy)((()=>(0,T.outdatedAssetFileCountSync)()),5*w.secondMs),s.set(this,(0,c.lazy)((()=>M.Progress.insertNew({uri:S.RebuildingURI,volume:"🔄",scanningPct:0})))),o.set(this,((e,t,i)=>{"updateAssetFile"===e.fn?(this.assetFilesUpdated++,this.assetFileEta.push(i),u(this,r,"m",n).call(this)):"repairAsset"===e.fn&&(this.assetsUpdated++,this.assetEta.push(i),u(this,r,"m",n).call(this))})),_.Task.ee.on("resolved",u(this,o,"f")),this.doneLatch.observe(u(this,r,"m",l).call(this))}assetTodo(){return(0,T.outdatedAssetCountSync)()}}t.LibraryRebuild=E,s=new WeakMap,o=new WeakMap,r=new WeakSet,n=async function({force:e=!1,done:t=!1}={}){const i=u(this,s,"f").call(this);if(e||!(0,v.gt)(i.updatedAt,Date.now()-w.secondMs))if((t??this.isDone())&&"done"!==i.state){const e=[];this.assetFilesUpdated>0&&e.push(`Updated file metadata for ${(0,b.fmt)(this.assetFilesUpdated)} files (roughly ${(0,b.fmt)(this.assetFileTodo())} remain).`),this.assetsUpdated>0&&e.push(`Refreshed ${(0,b.fmt)(this.assetsUpdated)} assets (roughly ${(0,b.fmt)(await this.assetTodo())} remain).`),i.dek=e,i.upsert({state:"done",hed:"Finished rebuilding your library 🎉",completePct:100,incompletePct:0,scanningPct:0})}else{let e="Rebuilding your library";const t=this.assetFileTodo(),r=await this.assetTodo(),s=(this.assetFileEta.etaMs(t/(0,g.maxConcurrentImports)())??0)+(this.assetEta.etaMs(r)??0),n=[];t>0&&n.push(`Updating file metadata (${(0,b.fmt)(this.assetFilesUpdated)} processed)`),r>0&&n.push(`Refreshing assets and previews (${(0,b.fmt)(this.assetsUpdated)} processed`);const a=t+r,o=this.assetFilesUpdated+this.assetsUpdated,l=(0,v.clamp)(0,100,Math.round(o/(a+o)*100)),u=(0,m.fmtEstimate)(s);(0,y.notBlank)(u)&&(e+=", "+u+"…"),i.dek=n,i.upsert({state:"processing",hed:e,completePct:l,incompletePct:100-l,scanningPct:0})}},a=function(){_.Task.ee.off("resolved",u(this,o,"f"))},l=async function(){this.logger.info("Starting library rebuild...");const e=p.Settings.forceFilters.getState();try{p.Settings.forceFilters.envValue=!0;const e=P.TaskList.instance(),t=await this.assetFileTodo(),i=await this.assetTodo();if(this.logger.info(".run()",{assetFileTodo:t,assetTodo:i}),0===t&&0===i)return;let s=!1;for(;!s;)s=(await(0,T.enqueueAssetFileUpdates)()).done,this.logger.info("run(): waiting for asset updates to complete..."),await e.awaitDrain(["updateAssetFile"],s?0:p.Settings.taskListCap.valueOrDefault/2);for(s=!1;!s;)s=(await(0,T.enqueueAssetUpdates)()).done,await e.awaitDrain(["repairAsset","assetPostUpsertTasks"],s?0:p.Settings.taskListCap.valueOrDefault/2);await u(this,r,"m",n).call(this,{done:!0,force:!0}),this.logger.info("rebuild complete!")}catch(e){(0,f.onError)("LibraryUpdater.run() failed",e)}finally{p.Settings.forceFilters.setState(e)}}},18209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.enqueueAssetUpdates=t.outdatedAssetCount=t.enqueueAssetFileUpdates=t.outdatedAssetFileCountSync=t.outdatedAssetCountSync=t.outdatedAssetFileCount=t.currentUriRoots=void 0;const r=i(50213),s=i(45393),n=i(70417),a=i(45200),o=i(5696),l=i(7014),u=i(40958),c=i(45599),d=i(41400),h=i(20214),f=i(54993),m=i(43487),p=i(54017),g=i(94710),y=(0,c.defer)((()=>(0,r.mkLogger)("sync.UpdateQueue")));async function w(){return[...await(0,h.thenCollect)((0,l.volumes)(),(async e=>(0,a.nativePath2uri)(e.mountpoint,e))),o.PSLIB_ROOT_URI].map(f.toS)}t.currentUriRoots=w,t.outdatedAssetFileCount=async function(){const e=await w();return p.AssetFile.dbl.pluckFirstf((t=>t.count("AssetFile.id").distinct().where("version","!=",s.AssetFileVersion).andWhere((t=>e.forEach((e=>t.orWhereLike("AssetFile.uri",e+"%")))))))},t.outdatedAssetCountSync=function(){return m.Asset.outdatedCount()},t.outdatedAssetFileCountSync=function(){return p.AssetFile.dbl.pluckFirstf((e=>e.count("id").where("version","!=",s.AssetFileVersion)))},t.enqueueAssetFileUpdates=async function(){const e=[];for(const t of await w())e.push(await p.AssetFile.dbl.batched({maxResults:g.Task.freeSlots(),onResults:async e=>{const t=[];for(const i of e)t.push({fn:"updateAssetFile",args:{assetFileId:i.id,path:await(0,a.uri2nativePath)(i.uri),skipAssetRepair:!0}});g.Task.add(t),y().info("Scheduled updateAssetFile",{tasks:t})},qb:(e,i)=>(e=e.select({id:"AssetFile.id",uri:"AssetFile.uri"}).distinct().orderBy("AssetFile.id","asc").where("AssetFile.version","!=",s.AssetFileVersion).andWhereLike("AssetFile.uri",t+"%"),(0,u.isNotEmpty)(i)&&(e=e.andWhere("AssetFile.id",">",(0,n.max)(i.map((e=>e.id))))),e)}));return y().tap({msg:"enqueueAssetFileUpdates",level:"info",result:{done:e.every((e=>e.done)),tasksAdded:(0,n.sumf)(e,(e=>e.resultCount))}})},t.outdatedAssetCount=async function(){const e=await w();return m.Asset.dbl.pluckFirstf((t=>t.count("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").where("Asset.version","!=",s.AssetVersion).andWhere((t=>e.forEach((e=>t.orWhereLike("AssetFile.uri",e+"%")))))))},t.enqueueAssetUpdates=async function(){const e=[];for(const t of await w())e.push(await m.Asset.dbl.pluckBatched({maxResults:g.Task.freeSlots(),onResults:e=>(g.Task.add(e.map((e=>({fn:"repairAsset",args:{assetId:e}})))),y().info("Scheduled repairAsset for ",{assetIds:e}),(0,d.delay)(1)),qb:(e,i)=>(e=e.select("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").orderBy("Asset.id","asc").where("Asset.version","!=",s.AssetVersion).andWhereLike("AssetFile.uri",t+"%"),(0,u.isNotEmpty)(i)&&(e=e.andWhere("Asset.id",">",(0,n.max)(i))),e)}));return y().tap({msg:"enqueueAssetUpdates",level:"info",result:{done:e.every((e=>e.done)),tasksAdded:(0,n.sumf)(e,(e=>e.resultCount))}})}},3996:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const a=i(19851),o=i(50213),l=i(79781),u=i(56519),c=i(56038),d=i(59189),h=i(38835),f=i(95696),m=i(48368),p=i(181),g=i(69589),y=i(28874),w=i(28544),v=i(47783),b=i(87001),S=i(40958),P=i(76790),M=i(22573),_=i(42659),T=i(55835),E=i(31586),D=i(43487),k=i(54017);t.isFileInSync=async function(e){return new F(f.PosixFile.for(e)).alreadySynced()};const x=new d.SerialLaterQueue;class F{constructor(e,t=(0,g.forceContextOrSetting)()){this.file=e,this.ctx=t,r.set(this,void 0),this.rejectedAssetIds=new Set,this.rejectedSiblingIds=new Set,this.alreadySynced=(0,c.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>n(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,c.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new k.AssetFile).updateFromFile_(this.file);return null==e?n(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,a.lazy)((async()=>{const e=await(0,v.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,a.lazy)((()=>y.Settings.useImageHashes.valueOrDefault?(0,m.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,a.lazy)((()=>(0,u.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,a.lazy)((async()=>{const e=await this.capturedAt_();return n(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,c.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,M.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return n(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await x.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return n(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new D.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,c.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,p.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtAndImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,c.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return n(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;n(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw n(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),s(this,r,(0,o.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f")}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),n(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}n(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(e=this.file){const t=await e.uri_();if(null!=t)return k.AssetFile.ops().firstf((e=>e.whereIn("uri",[...(0,b.uriEncodingVariants)(t),this.file.fileuri()])));n(this,r,"f").warn("byUri() uri is null",{file:e})}async assetByNormalizedPathUri(){const e=await this.file.normalize();return e.nativePath===this.file.nativePath?void 0:(await this.byUri(e))?.getAsset()}async assetBySha(){const e=await this.file.sha_();return D.Asset.findFirstByFile((t=>(t=t.where("AssetFile.sha",e),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds))),this.rejectedSiblingIds.size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),t)))}async assetByCapturedAtAndImageHash(){const e=await this.capturedAt_();if(null==e)return n(this,r,"f").throw("Cannot import, capturedAt is null"+h.InternalErrorFlag);if(y.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(k.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=y.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=k.AssetFile.query();return(0,E.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(_.secondMs,y.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,c.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)n(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(y.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void n(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const a=await this.dominantLabhashes();if((0,S.isNotEmpty)(a)){const t=e.localBoundaries({delta:4*s});if(null==t)n(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",a).orWhereIn("mode1",a).orWhereIn("mode2",a))));if(null!=e)return e}}const o=this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash));if(null!=o)return o;if(y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const r={};for(let e=0;e0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds)));const i=await this.firstSimilarAsset(k.AssetFile.ops().all(t));return null!=i&&n(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const s=(0,P.sortBy)(e.filter((e=>!this.rejectedSiblingIds.has(e.id)&&!this.rejectedAssetIds.has(e.assetId))),(e=>[(0,T.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of s)if(null!=e){await e.getNativePath();const i=k.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const s=(0,l.whyNotSameAsset)(t,e,i);if(null==s)return n(this,r,"f").info("Found sibling AssetFile",e),D.Asset.ops().findById(e.assetId);this.rejectedSiblingIds.add(e.id),n(this,r,"f").debug("Contemporary assetFile not similar: "+s,e?.uri)}}}t.AssetFileFinder=F,r=new WeakMap},34274:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult_=void 0;const u=i(19851),c=i(50213),d=i(73568),h=i(38835),f=i(95696),m=i(62105),p=i(74128),g=i(181),y=i(69589),w=i(28874),v=i(40958),b=i(22573),S=i(38639),P=i(59455),M=i(64526),_=i(19113),T=i(94710),E=i(3996),D=i(90901);t.importFileToResult_=async function(e){const t=M.Library.instanceRequired_();return(0,p.syncReport)().wrap_({path:e.path,from:"AssetFileImporter",fn_:()=>new k(f.PosixFile.for(e.path),t.assetFileRepository(),e).apply_()})};class k{constructor(e,t,i){r.add(this),this.file=e,this.repo=t,this.start=Date.now(),s.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else if(this.ctx.forceFilters||null==await this.prior()){const t=await(0,m.whyRejectFile)(this.file,(0,_.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,s,"f").throwIfAborted_();const i=await this.prior();if((0,v.isNotEmpty)(e)&&null!=i&&(l(this,s,"f").info("Deleting prior AssetFile",{rejected:e,prior:i}),i.delete(),this.ctx.skipAssetRepair?l(this,s,"f").info("Skipping asset repair",{assetId:i.assetId}):(l(this,s,"f").info("Scheduling asset repair",{assetId:i.assetId}),T.Task.addOne("repairAsset",{assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)}))),null!=i){const t=i.getAsset();null!=t?.deletedAt&&e.push("Asset is marked as deleted"),null!=t?.excludedAt&&e.push("Asset is marked as excluded")}if(l(this,s,"f").throwIfAborted_(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,b.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,s,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,s,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,s,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,r,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,s,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new E.AssetFileFinder(e,this.ctx),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=k,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(){l(this,s,"f").throwIfAborted_();const e=await l(this,s,"f").tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if((0,v.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,s,"f").throwIfAborted_();const t=await l(this,s,"f").tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,s,"f").throwIfAborted_();const i=await l(this,s,"f").tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return l(this,s,"f").throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return l(this,s,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,s,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,s,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;await l(this,s,"f").tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault}),l(this,s,"f").throwIfAborted_();try{o=await(0,D.assetPostUpsertTasks_)({asset:a,...this.ctx})}catch(e){e instanceof d.AbortError?l(this,s,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,s,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:r,assetFile:i,asset:a,uri:n,uris:[n,...(0,P.toA)(o?.newAssetFileUris)]}}},41844:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(50213),c=i(74128),d=i(81674),h=i(57902),f=i(4936),m=i(28874),p=i(47783),g=i(14245),y=i(67083),w=i(16170),v=i(54979),b=i(98604),S=i(40958),P=i(22573),M=i(98553),_=i(68708),T=i(89937),E=i(59455),D=i(54017),k=i(94710);t.mayCopyAssetsToLibrary=async function(){return m.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,u.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!0!==m.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,d.l)())return"no active subscription";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(m.Settings.libraryDir.valueOrDefault))return e+" already contained by "+m.Settings.libraryDir.valueOrDefault;const t=await(0,v.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,w.isMimeTypeIncluded)(t,m.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,E.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(D.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),k.Task.addOne("repairAsset",{assetId:t,forceSync:!0})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return a.addAssetFile(d),(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,p.readCapturedAt)(e),i=(0,f.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,p.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,p.readTags)(e);if(null!=i){if(m.Settings.writeGeolocationTagsToLibraryCopies.valueOrDefault){const e=(0,g.geolocationToXmp)(i);(0,_.isEmptyObj)(e)||await(0,p.writeTags_)(t,e)}return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred)}this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},90901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const r=i(50213),s=i(92434),n=i(73568),a=i(99331),o=i(39250),l=i(38835),u=i(57159),c=i(48604),d=i(66106),h=i(69589),f=i(40958),m=i(45599),p=i(23838),g=i(31586),y=i(64526),w=i(88224),v=i(43487),b=i(41844),S=i(68640),P=(0,m.defer)((()=>(0,r.mkLogger)("sync-file.AssetPostUpsertTasks"))),M=(0,m.defer)((()=>new o.LastOneInWins("Asset tasks")));async function _(e){const t=e,i=e,r=(0,g.toGt0)(t.asset?.id)??(0,g.toGt0)(i.assetId);if(null==r)throw new Error("assetPostUpsertTasks_(): unexpected null assetId"+l.InternalErrorFlag);const o=(0,h.forceContextOrSetting)(e),m=P().addContext(`.postUpsertAssetTasks_(Asset:${r})`);if(m.abortable=o.halt,o.skipPreviews&&o.skipAssetTagging)return void m.info("skipped (skipPreviews && skipAssetTagging)");const _=t.asset??v.Asset.ops().findById(r);if(null==_)return m.throw("unexpected null asset",{asset:_});try{return await M().enqueue({key:r,abortable:m.abortable,fn:()=>async function(e,t,i){const r=(0,h.forceContextOrSetting)(i),n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted_(),(0,f.isEmpty)(a)&&(await v.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,b.mayCopyAssetsToLibrary)())for(const[t,i]of(0,p.groupBy)(a,(e=>e.sha)).entries()){e.throwIfAborted_();try{for(const r of i)r.isInLibrary()&&await r.exists()&&e.debug("no-op for file SHA: already in library.",{sha:t,uri:r.uri});for(const e of i)if(await e.exists()){const t=await y.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,r);if(null!=t){o.newAssetFileUris.push(t.uri);continue}}}catch(r){e.warn("Failed to copy variation to library, but we'll try to continue",{sha:t,uris:i.map((e=>e.uri)),error:r})}}e.throwIfAborted_();const l=r.skipPreviews?void 0:await(0,S.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...r}),u=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?P().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,s.bestExistingAssetFile)(e.getAssetFiles())}(t,l);if(null==u)return e.throw("null primaryOrShownAssetFile_()",{asset:t});const m=await u.posixFile_();if(!0!==r.skipPreviews&&t.isVideo()){if(null==m)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});o.transcoded=null!=await(0,d.transcode_)(m,c.Previews.instance().ap(n).mp4(),{force:r.forceRebuildPreviews,halt:r.halt})}return e.throwIfAborted_(),t.markShownAndUpsert_(u),r.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,w.tagAndUpsertAsset_)(t),o}(m,_,{...e,...o})})}catch(e){if(e instanceof n.AbortError)return void m.warn("aborted, next caller will clean up my mess",{error:e});const t=[e];if(!(0,a.ending)()){m.error("failed, marking asset unshown",{error:e});try{_.markUnshownAndUpsert()}catch(e){m.error("failed to mark asset unshown",{upsertError:e}),t.push(e)}}throw new u.WrappedError("Failed to post-process assset "+_.id,{causes:t})}}t.assetPostUpsertTasks=function(e){try{return _(e)}catch(e){if(e instanceof n.AbortError)return void P().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=_},61989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset_=t.updateAsset=void 0;const r=i(48884),s=i(50213),n=i(45393),a=i(79184),o=i(79781),l=i(92434),u=i(56519),c=i(70417),d=i(69589),h=i(28874),f=i(40958),m=i(22573),p=i(38639),g=i(50357),y=i(43487),w=i(54017),v=i(3996),b=i(90901);async function S(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,r=(0,s.mkLogger)(`sync-file.UpdateAsset(${i})`);r.abortable=t.halt;const S=y.Asset.ops().findById(i);if(null==S)return r.throw("no such asset");const M=S.getAssetFiles({refresh:!0});if((0,f.isEmpty)(M))return r.warn("No asset files: deleting."),S.delete(),{asset:S,rejected:"Empty asset (no AssetFiles)"};const _=S.$clone(),T=S.getShown()?.$clone();for(const e of M)r.throwIfAborted_(),await e.upsertIfNeeded_(void 0,t);M.some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&S.clear(),await P(r,M);const E=(0,l.sortAssetFiles)(M),D=E?.[0];if((0,f.isEmpty)(E)||null==D)return r.warn("No existing files. Skipping for now."),S.markUnshownAndUpsert(),{asset:S,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!D.isVersionUpToDate())return r.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:D}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${D.id}, could not be updated. Un-showing Asset:${i}`};const k=await D.capturedAt();if(null==k)return r.warn("Best file failed to extract a captured-at",{bestAcceptedAF:D}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${D.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const x=new Set,[F,C]=await(0,u.partitionAsync)(E,(e=>(0,o.isSimilarAssetFile)(e,D)));if(r.throwIfAborted_(),(0,f.isNotEmpty)(C)){const e=await(0,a.aggregateAssetFiles)(C);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});x.add(e.id);for(const i of t)e.addAssetFile(i);w.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),r.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function A(e){return(0,f.uniq)(F.map((t=>t[e])))}const I=await Promise.all(F.map((e=>e.capturedAt()))),O=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,L=I.map((e=>e?.localBoundaries({delta:O}))),R=(0,c.min)(L.map((e=>e?.start)))??k.localBoundaries({delta:O})?.start,N=(0,c.max)(L.map((e=>e?.end)))??k.localBoundaries({delta:O})?.end,B=w.AssetFile.ops().all(w.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${D.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",A("sha")),null==R||null==N?r.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:R,endBoundary:N}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[R,N]),e.orWhereIn("AssetFile.meanHash",A("meanHash")).orWhereIn("AssetFile.diffHash",A("diffHash")).orWhereIn("AssetFile.dctHash",A("dctHash"))))));if(r.throwIfAborted_(),h.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const e=await D.posixFile();if(null==e)r.info("bestAcceptedAF has no posixFile, cannot expand query for fuzzy dates",{bestAcceptedAF:D});else{const i=new v.AssetFileFinder(e,t);for(const e of[...F,...B])i.rejectedAssetIds.add(e.assetId),i.rejectedAssetIds.add(e.id);let s=h.Settings.maxContemporaryAdoptionAssets.valueOrDefault;for(;--s>0;){r.throwIfAborted_();const e=await i.assetByCapturedAtAndImageHash();if(null==e){r.info("allowFuzzyDateImageHashMatches(): no additional assets found to adopt");break}if(r.info("allowFuzzyDateImageHashMatches(): found asset with similar image",{a:e}),null!=e){i.rejectedAssetIds.add(e.id);for(const t of e.getAssetFiles())r.info("found asset file by fuzzy date and image hash",{uri:t.uri,assetId:e.id}),B.push(t),i.rejectedAssetIds.add(t.id)}}}}r.info("asset file candidates for adoption: ",B.map((e=>e.posixPathFromGrandparent)));const j=[];for(const e of B){r.throwIfAborted_();try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,D)&&(r.info("adopting similar asset file",{af:e}),x.add(e.assetId),e.shown=!1,S.addAssetFile(e),e.upsert(),j.push(e))}catch(t){r.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}}r.info("fetched expansion",{retainAFs:F.map((e=>e.id)),rejectAFs:C.map((e=>e.id)),externalAssetFiles:B.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:j.map((e=>e.posixPathFromGrandparent))}),await P(r,[...F,...j]),t.skipPreviews&&t.skipAssetTagging?(r.info("skipping previews and tagging",t),S.upsert()):await(0,b.assetPostUpsertTasks_)({...t,asset:S});const z=!(0,g.eql)(_,S),V=!(0,g.eql)(T,S.getShown()),W=!(z||V||t.forceRebuildPreviews||t.forceSync);return r.tap({msg:"updateAsset() result",level:"info",result:{asset:S,assetIdsToUpdate:Array.from(x),assetFiles:S.assetFiles,skipped:W},meta:{ctx:t,assetChanged:z,primaryAssetFileChanged:V}})}async function P(e,t){const[i,s]=(0,r.partition)(t,(e=>e.isVersionUpToDate()));for(const t of s){e.throwIfAborted_();const r=i.find((e=>e.sha===t.sha));if(null!=r){e.info("backfilling",{sibling:r,dest:t});const i=await t.updateFromShaSibling_(r);null!=i&&i.upsert()}}}t.updateAsset=async function(e){try{const t=await S(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}},t.updateAsset_=S},93755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t.updateAssetFile_=t.updateAssetFile=void 0;const r=i(50213),s=i(92434),n=i(98314),a=i(74128),o=i(69589),l=i(87001),u=i(40958),c=i(22573),d=i(68708),h=i(43487),f=i(54017),m=i(94710);async function p(e){const t=Date.now(),i=e,s=e,n=s.af?.id??i.assetFileId,u=(0,r.mkLogger)(`updateAssetFile(${n})`),d=s.af??f.AssetFile.ops().findById(n);if(null==d)return u.throw("db record not found",{assetFileId:n});const h=await d.posixFile_(),p=(0,o.forceContextOrSetting)(e),w={id:n,assetFileId:n,path:h?.nativePath,uri:d?.uri};if(null==h){const e=["cannot resolve URI"];return(0,c.blank)(d.mountpoint)||e.push("is "+d.mountpoint+" mounted?"),(0,a.syncReport)().onProgress({path:d.uri,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:e.join(": "),state:a.SyncFileStates.skipped}),{...w,error:"file for URI not found"}}const v=await(h?.isDeletedUri(d.uri));if(null==v)return u.info("no-op: file URI points to an unmounted volume",w),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:((0,c.toNotBlank)(d.mountpoint)??"volume")+" is not currently mounted",state:a.SyncFileStates.skipped}),{...w,skipped:!0};const b=e.whyReject??await d.whyRejected();if(v||!(0,c.blank)(b)){const e={...w,rejected:b,deleted:v};return u.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:v?"file no longer exists":"rejected: "+b,state:a.SyncFileStates.deleted}),d.delete(),!0!==p.skipAssetRepair&&m.Task.addOne("repairAsset",{assetId:d.assetId}),e}const S=await h.uri_();if(!await(0,l.uriIsEquivalent)(S,d.uri)){const e=await g(d,S,p);if(null!=e)return{...w,...e}}return!p.forceSync&&await d.matchesFile()?(u.info("no-op: file already matches db record",w),d.touch(),{...w,skipped:!0}):{...w,...await y(d,p)}}async function g(e,t,i){const n=(0,r.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,u.uniq)([...(0,l.uriEncodingVariants)(e.uri),...(0,l.uriEncodingVariants)(t)]);n.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const o=f.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,u.isNotEmpty)(o)){n.warn("Found other AssetFiles with equivalent URIs.",{afIds:o.map((e=>e.id))});const t=[e,...o],r=(0,s.sortAssetFiles)(t);if((0,u.isEmpty)(r))return n.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,d.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const l=t.map((e=>e.id));for(const e of r)if(await e.exists()){f.AssetFile.dbl.runf((t=>t.whereIn("id",l.filter((t=>t!==e.id))).delete()));const r=y(e,i);return h.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,u.uniq)(t.map((e=>e.assetId)))))),r}}n.info("no-op, no duplicate URIs.")}async function y(e,t){const i=Date.now();return null!=await e.upsertIfNeeded_(void 0,t)&&h.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:await e.getNativePath(),elapsedMs:Date.now()-i,from:"updateAssetFileIfNeeded()",state:e.syncState??a.SyncFileStates.unknown}),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await p(e)}catch(t){return{id:e.assetFileId,...e,error:(0,n.errorToS)(t)}}},t.updateAssetFile_=p,t.handleAssetFileUriChange=g,t.updateAssetFileIfNeeded=y},68640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const r=i(99331),s=i(38835),n=i(48604),a=i(50213),o=i(69589),l=i(87001),u=i(40958),c=i(45599),d=i(50357),h=i(31586),f=i(68708),m=i(59455),p=i(43487),g=(0,c.defer)((()=>(0,a.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,m.toA)(e.assetFiles).find((e=>(0,h.gt0)(e.assetId)))?.assetId,i=(0,o.forceContextOrSetting)(e),a=g().addContext(".Asset:"+t);if(i.skipPreviews)return void a.warn("skipPreviews is true: no-op");if(!(0,h.gt0)(t))return a.throw("invalid assetId",{assetId:t});const c=e.asset??p.Asset.ops().findById(t);if(null==c)return a.throw("Asset:"+t+" not found");a.throwIfAborted_(i.halt);try{const e=await c.getExistingAssetFiles();if((0,u.isEmpty)(e))return void a.warn("no existing assetFiles",{asset:c});const r=n.Previews.instance().ap(t),o=await r.readInfo();a.throwIfAborted_(i.halt);const h=await(0,n.buildAssetPreviews_)({...i,assetId:t,assetFiles:e}),m=e.find((e=>e.id===h?.assetFileId))??e.find((e=>(0,l.uriIsEquivalent)(h?.uri,e.uri)));a.info("buildAssetPreviews_()",{result:h,primaryAssetFile:m});const p=await(m?.posixFile_());if(null==m||null==p||!0!==await(p?.exists()))return a.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:h,assetFiles:e.map((e=>(0,f.pick)(e,"id","uri"))),primaryAssetFile:m,primaryPosixFile:p});const g=(0,d.eql)(o,h),y=null==h||g;return{...h,noop:y}}catch(e){throw(0,r.ending)()||(a.warn("Failed to update previews. Un-showing asset "+t,{error:e}),c.markUnshownAndUpsert()),e}}},34742:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(93944).install()}catch{}const r=i(69554),s=i(38790),n=i(53978),a=i(43380),o=i(43334),l=i(28874),u=i(5670),c=i(21200),d=i(2775),h=i(31503),f=i(12195),m=i(52288),p=i(53767);!async function(){if(o.isElectron)new p.SyncService;else{const e=await new r.CLI(u.ServiceNames.sync,"[files-or-directories...]","If paths are provided on the command line, they should be fully-qualified.\n\n* Paths to directories will be scanned recursively.\n* Paths to files will be imported if they pass configured filters.\n\nNote that sync will spawn 1 or more `worker` processes to work in parallel.").add(m.RebuildArg,d.ForceArg,n.TimingArg,f.NoFilterArg,c.ExitWhenDoneArg,a.WriteSettingsArg,h.LogArgs,s.ColorArgs).parse();l.Settings.argvScanPaths.envValue=e.args,new p.SyncService}}()},94019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(87290),o=i(34102),l=i(16287),u=i(45969),c=i(43334),d=i(28874),h=i(45200),f=i(69375),m=i(7014),p=i(41400),g=i(31586),y=i(92244),w=i(46832);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const v=(0,r.lazy)((async()=>{const e=[];for(const t of await(0,m.volumes)()){if(!0===t.ignorable||!1===t.ok||(c.isMac||(0,u.isDocker)())&&"/"===t.mountpoint||(0,f.isExcludedMountpoint)(t.mountpoint)||!(0,g.gt0)(t.size))continue;const i=await(0,w.toUriPath)(t.mountpoint,(0,h.nativePath2uri)(t.mountpoint,t));null!=i&&e.push(i)}return e}));async function b(){const e=[],i=[],r=d.Settings.argvScanPaths.toNotEmpty()??d.Settings.scanPaths.values;for(const s of r)if(await(0,l.isReadableDirectory)(s)){const r=await(0,w.toUriPath)(s);null==r?(e.push(s),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",s)):i.push(r)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",s);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,p.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{v.unset()}))})),t.pathsToSync=async function(){const e=[];if(d.Settings.argvScanPaths.isNotEmpty()){for(const i of d.Settings.argvScanPaths.values){const r=await(0,w.toUriPath)(i);null!=r?e.push(r):(0,t.logger)().warn("pathsToSync(): Ignoring scanPath element: failed to create URI path",i)}return e}e.push(...(await b()).result),!0===d.Settings.scanAllDrives.value&&e.push(...await v());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),w.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:d.Settings.libraryDir.valueOrDefault,originalsDir:d.Settings.originalsDir.value})));d.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),d.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},76907:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.precheckFiles=void 0;const r=i(50213),s=i(98314),n=i(74128),a=i(69589),o=i(45200),l=i(98604),u=i(22573),c=i(45599),d=i(54017),h=(0,c.defer)((()=>(0,r.mkLogger)("sync.PrecheckFiles"))),f="AssetFilePrecheck";async function m(e,t){const i=(await(0,o.nativePath2uri)(e.nativePath)).toString(),r=d.AssetFile.ops().firstf((e=>e.where({uri:i})));if(null==r)return(0,n.syncReport)().onProgress({path:e.nativePath,from:f,state:n.SyncFileStates.enqueued,details:"Path is new to the library. Scheduling import."}),!0;const s=await r.whyNotNoop(t);return(0,u.blank)(s)?((0,n.syncReport)().onProgress({path:e.nativePath,from:f,state:n.SyncFileStates.noop,details:"in sync",url:(0,l.mkAssetUrl)(r.assetId)?.toString()}),r.touch(),!1):((0,n.syncReport)().onProgress({path:e.nativePath,from:f,state:n.SyncFileStates.enqueued,details:"update needed: "+s,url:(0,l.mkAssetUrl)(r.assetId)?.toString()}),!0)}t.precheckFiles=async function(e,t=(0,a.forceContextOrSetting)()){const i=[];for(const r of e)try{await m(r,t)&&(h().debug("precheckFiles(): stale path",{nativePath:r.nativePath}),i.push(r))}catch(e){h().info("precheckFiles(): failed to check path",{nativePath:r.nativePath,error:e}),(0,n.syncReport)().onProgress({path:r.nativePath,from:f,state:n.SyncFileStates.rejected,details:(0,s.errorToS)(e)})}return i}},63461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncCompleted=void 0,t.SyncCompleted={syncCompleted:!0}},98622:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runTimeIsStale=t.SyncCron=void 0;const r=i(1708),s=i(17415),n=i(28874),a=i(41400),o=i(30301),l=i(31586);t.SyncCron=(0,o.lazy)((()=>{const e=n.Settings.syncCronTZ.valueOrDefault??(0,s.toValidIanaZone)(r.env.TZ);return n.Settings.syncCron.cron(null==e?void 0:{timezone:e})})),(0,a.later)((()=>{n.Settings.syncCron.watchLater((()=>t.SyncCron.unset())),n.Settings.syncCronTZ.watchLater((()=>t.SyncCron.unset()))})),t.runTimeIsStale=function(e){return null==e||(0,l.lte)((0,t.SyncCron)().nextRun(new Date(e))?.getTime(),Date.now())}},56179:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncDirectory=t.DefaultFileHandler=void 0;const m=i(89788),p=i(19851),g=i(50213),y=i(7282),w=i(45255),v=i(81168),b=i(73568),S=i(83412),P=i(99331),M=i(98314),_=i(38835),T=i(60652),E=i(29882),D=i(74128),k=i(76752),x=i(70417),F=i(28874),C=i(14036),A=i(69385),I=i(15674),O=i(22573),L=i(38639),R=i(42659),N=i(45599),B=i(55835),j=i(31586),z=i(68708),V=i(12168),W=i(54993),U=i(35580),q=i(54017),H=i(20958),G=i(49796),$=i(55009),J=i(94710),K=i(76907);async function Z(e){const t=await(0,K.precheckFiles)(e);J.Task.add(t.map((e=>({fn:"syncFile",args:{path:e.nativePath}}))))}t.DefaultFileHandler=Z;class Y extends S.DoneWrapper{static async for({root:e,rootUri:t,fileHandler:i=Z}){const r=await e.directoryEntry();if(null!=r&&r.isDirectory())return new Y(e,r,t,i);(0,g.mkLogger)("sync.DirectorySync").error("Cannot sync "+e+": it's not a directory (or not readable)",{root:e,rootUri:t})}constructor(e,t,i,d){super("sync.DirectorySync("+e+")",(()=>h(this,r,"m",s).call(this))),r.add(this),this.root=e,this.rootDirent=t,this.rootUri=i,this.fileHandler=d,this.start=Date.now(),this.eta=new k.ETA,this.recentlyScannedDirs=new m.BoundedList(10),this.progress=(0,N.defer)((()=>this.logger.tap({msg:".progress()",level:"warn",result:G.Progress.insertNew({uri:this.rootUri,volume:this.root.nativePath})}))),this.forceDirectoryScan=(0,N.defer)((()=>{const e=F.Settings.forceSync.valueOrDefault,t=F.Settings.argvScanPaths.values.some((e=>this.root.eql(e)));return this.logger.tap({msg:"forceDirectoryScan",result:e||t,meta:{forceSync:e,isArgvPath:t}})})),this.initialMeta=(0,N.defer)((()=>this.forceDirectoryScan()?void 0:this.progress().getMetaAsRecord())),this.minPriorCreatedAt=(0,N.defer)((()=>(0,x.max)([H.Operation.getFirstPendingOp({name:"forceRestartSync"})?.createdAt,(0,G.defaultMinCreatedAt)()]))),this.priorMeta=(0,N.defer)((()=>this.progress().getPriorIncomplete(this.minPriorCreatedAt())?.getMetaAsRecord())),this.priorScannedDir=(0,N.defer)((()=>this.priorMeta()?.lastScannedDirectory)),this.priorScannedDirsCount=(0,N.defer)((()=>(0,j.toInt)(this.priorMeta()?.scannedDirectoryCount)??0)),this.priorProcessedImageCount=(0,N.defer)((()=>(0,j.toInt)(this.priorMeta()?.processedImageCount)??0)),this.priorProcessedVideoCount=(0,N.defer)((()=>(0,j.toInt)(this.priorMeta()?.processedVideoCount)??0)),this.scannedDirsCount=0,n.set(this,0),a.set(this,0),this.priorEnqueuedStaleFiles=(0,N.defer)((()=>(0,L.isTrue)(this.priorMeta()?.enqueuedStaleFiles)??!1)),this.enqueuedStaleFiles=!1,this.completed=!1,this.upsertProgressMeta=(0,p.lazy)((()=>{const e=this.progress().getMetaAsRecord(),t={lastScannedDirectory:this.recentlyScannedDirs.at(-1)??this.priorScannedDir()??"",scannedDirectoryCount:(0,W.toS)(this.scannedDirectoryCount()),completedDirectoryScan:(0,W.toS)((0,L.isTrue)(this.priorMeta()?.completedDirectoryScan)||(h(this,o,"f").call(this)?.isDone()??!0)),enqueuedStaleFiles:(0,W.toS)(this.priorEnqueuedStaleFiles()||this.enqueuedStaleFiles),processedImageCount:(0,W.toS)(this.processedImageCount()),processedVideoCount:(0,W.toS)(this.processedVideoCount()),completedDirectorySync:(0,W.toS)((0,L.isTrue)(e.completedDirectorySync)||this.completed)};this.progress().setMetaRecord(t)}),(0,y.isTest)()?100:R.secondMs),this.directoryListener=e=>{null==e||(0,O.blank)(e.nativePath)?this.logger.warn("directoryListener() called with blank dir"+_.InternalErrorFlag,{dir:e}):(this.scannedDirsCount++,this.recentlyScannedDirs.push(e.nativePath),this.logger.debug("directoryListener()",{scannedDirsCount:this.scannedDirsCount,dir:e.nativePath}),this.upsertProgress({force:!0}))},o.set(this,(0,N.defer)((()=>(0,L.isTrue)(this.priorMeta()?.completedDirectoryScan)?void 0:new T.DirectoryIterator(this.rootDirent,this.ctx())))),this.pendingCount=(0,p.lazy)((()=>J.Task.countByFn("syncFile")),R.secondMs),l.set(this,((e,t,i)=>{if("syncFile"===e.fn){const t=e;this.onFileResolved(t.args.path,i)}else this.logger.info("onTaskResolve() non-syncFile task",{task:e,result:t,elapsedMs:i})})),u.set(this,((e,t)=>{this.logger.error("onTaskRejected()",{task:e,error:t})})),this.doneLatch.observe(h(this,r,"m",c).call(this)).catch((t=>{this.logger.error("SyncDirectory failed for "+e,{error:t}),(0,D.syncReport)().onProgress({path:e.nativePath,from:"SyncDirectory",state:t instanceof b.AbortError?"canceled":"failed",details:(0,M.errorToS)(t)})}))}upsertProgress(e){const t=h(this,r,"m",d).call(this,e);if(this.logger.info("upsertProgress()",{update:t}),null!=t){const e=this.progress().upsert(t);return this.upsertProgressMeta(),e}}scannedDirectoryCount(){return this.priorScannedDirsCount()+this.scannedDirsCount}ctx(){return{startAtNativePath:(0,B.map)(this.initialMeta()?.lastScannedDirectory,E.splitNativePath),hasCapacity:()=>U.TaskList.instance().hasCapacity(),fileHandler:this.fileHandler,directoryListener:this.directoryListener,ended:()=>(0,P.ending)()||this.ended}}earliestStartTime(){return this.progress().getLastIncompleteStartAt()??this.start}async maybeEnqueueStaleAssetFiles_(){if(!F.Settings.forceSync.valueOrDefault&&(0,L.isTrue)(this.priorMeta()?.enqueuedStaleFiles))this.logger.info("maybeEnqueueStaleAssetFiles() no-op: prior enqueuedStaleFiles.");else{const e=this.progress(),t=this.earliestStartTime(),i=U.TaskList.instance();this.logger.info("maybeEnqueueStaleAssetFiles() starting",{earliestStartTime:t});const r=Math.min(Math.round(F.Settings.taskListCap.valueOrDefault/4),F.Settings.dbBatchSelectSize.valueOrDefault),s=F.Settings.taskListCap.valueOrDefault-r;let n=0;await q.AssetFile.ops().batched({batchSize:r,onResults:async e=>{this.logger.throwIfAborted_(),await Promise.all(e.map((e=>e.getNativePath()))),J.Task.add(e.map((e=>({fn:"updateAssetFile",args:{path:e.nativePath,assetFileId:e.id,whyReject:"missed by directory sync"}})))),n+=e.length,await i.awaitDrain([],s)},qb:e=>e.select("id").whereLike("uri",this.rootUri+"%").andWhere("updatedAt","<",t)}),this.logger.info("maybeEnqueueStaleAssetFiles() finished enqueue",{assetFileQueuePendingCount:n}),e.setMeta($.ProgressMetaNames.enqueuedStaleFiles,"true")}}processedCount(){return this.processedImageCount()+this.processedVideoCount()}processedVideoCount(){return this.priorProcessedVideoCount()+h(this,a,"f")}processedImageCount(){return this.priorProcessedImageCount()+h(this,n,"f")}onFileResolved(e,t){var i,r;(0,C.isVideoExt)(e)?f(this,a,(i=h(this,a,"f"),++i),"f"):f(this,n,(r=h(this,n,"f"),++r),"f"),this.eta.push(t),this.upsertProgress()}get isScanning(){const e=h(this,o,"f").call(this);return null!=e&&!e.isDone()}estimatedScannedPct(){if(!this.isScanning)return 100;const e=100/-(this.scannedDirsCount/500+1)+100;return(0,j.sigFigs)(e,3)}percents(){if(this.completed||this.isDone())return{completePct:100,incompletePct:0,scanningPct:0};const e=(0,j.round)(this.estimatedScannedPct()),t=100-e,i=this.processedCount(),r=this.pendingCount(),s=0===r&&0===i?0:(0,j.round)(e*(i/(r+i))),n=100-(s+t),a={completePct:s,incompletePct:n,scanningPct:t};return this.logger.debug("percents(): ",{scannedPct:e,processed:i,pending:r,p:a}),100!==(0,x.sum)([a.completePct,a.incompletePct,a.scanningPct])&&this.logger.warn("percents(): BUGGED",{p:a,processed:i,pending:r,scannedPct:e,scanningPct:t,incompletePct:n,completePct:s}),a}}t.SyncDirectory=Y,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,r=new WeakSet,s=function(){J.Task.ee.off("resolved",h(this,l,"f")),J.Task.ee.off("rejected",h(this,u,"f"))},c=async function(){J.Task.ee.on("resolved",h(this,l,"f")),J.Task.ee.on("rejected",h(this,u,"f"));const e=this.initialMeta();this.logger.info("setup()",{meta:e});const t=U.TaskList.instance(),i=h(this,o,"f").call(this);if(null==i)this.logger.info("#run(): already completedDirectoryScan");else{this.logger.info("#run(): starting directory scan...");const e=Math.round(F.Settings.taskListCap.valueOrDefault),r=Math.max(2*(0,I.maxConcurrentImports)(),Math.round(F.Settings.taskListCap.valueOrDefault/2));for(;!i.isDone();)await this.awaitOrAbort((0,A.resolveOnResume)()),await i.next(w.ShortCommandTimeoutMs+Date.now()),t.hasCapacity(.9*e)||await this.awaitOrAbort(t.awaitDrain(["syncFile"],r));(0,D.syncReport)().onProgress({from:"SyncDirectory",state:"note",details:"Directory scan complete",path:this.root.nativePath,elapsedMs:Date.now()-this.start}),this.upsertProgress({force:!0})}await this.awaitOrAbort(t.awaitDrain()),(0,D.syncReport)().onProgress({from:"SyncDirectory",state:"note",details:"File imports complete: "+this.processedImageCount()+" images and "+this.processedVideoCount()+" videos",path:this.root.nativePath,elapsedMs:Date.now()-this.start}),await this.awaitOrAbort(this.maybeEnqueueStaleAssetFiles_()),await this.awaitOrAbort(t.awaitDrain()),this.ended||this.aborted||(this.logger.info("DONE! Marking Progress as complete and updating meta."),this.completed=!0,this.upsertProgress({force:!0,done:!0}))},d=function(e={}){const t=e.prior??{},i={},r=this.isDone()||(e.done??!1)||this.completed;if(!0!==e.force&&(0,j.gt)(t.updatedAt,Date.now()-R.secondMs))return;const s=U.TaskList.instance(),n=(0,A.isPaused)()||(0,P.ending)();i.state=r?"done":n?"paused":"processing";const a=s.pendingWorkCount();{const e=[];if(e.push((0,v.capitalize)(i.state)),!r&&a>0){const t=Math.min((0,I.maxConcurrentImports)(),a),i=this.eta.fmtEstimate(a/t);null!=i&&e.push(i)}i.hed=e.join(", ")}const o=[];this.processedCount()>0&&o.push("Processed "+(0,V.plur)(this.processedImageCount(),"photo")+" and "+(0,V.plur)(this.processedVideoCount(),"video")),!r&&a>0&&o.push((this.isScanning?"At least ":"")+(0,V.fmt)(a)+" remain to be processed"),r||n||!this.isScanning||o.push("Scanning "+(this.recentlyScannedDirs.shiftOrFirst()??this.root.nativePath)),this.scannedDirectoryCount()>0&&o.push("Scanned "+(0,V.plur)(this.scannedDirectoryCount(),"directory"));const l=s.currentTasksByFn("syncFile"),u=J.Task.nextByFn("syncFile",(e=>e.whereNotIn("id",l.map((e=>e.id))).limit(2)));return l.length>0&&o.push("Processing: "+(0,E.ellipsizePaths)({arr:l.map((e=>e.args.path)),maxPathLength:48,sampleSize:2})),u.length>0&&o.push("Queued: "+(0,E.ellipsizePaths)({arr:u.map((e=>e.args.path)),maxPathLength:48,sampleSize:2})),i.dek=o,(0,z.assignFields)(i,this.percents()),r&&(i.completedAt??(i.completedAt=Date.now())),this.logger.tap({msg:"#mkProgressUpdate()",level:"info",result:i})}},88204:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncFile=void 0;const a=i(83412),o=i(98314),l=i(74128),u=i(69385),c=i(49796),d=i(94710),h=i(76907);class f extends a.DoneWrapper{constructor(e){super("SyncFile: "+e),r.add(this),this.src=e,this.doneLatch.observe(n(this,r,"m",s).call(this)).catch((()=>{}))}}t.SyncFile=f,r=new WeakSet,s=async function(){await(0,u.resolveOnResume)();const e=await this.src.uri();if(null==e)return void(0,l.syncReport)().onProgress({path:this.src.nativePath,from:"SyncFile",state:l.SyncFileStates.rejected,details:"failed to build URI"});const t=c.Progress.insertNew({uri:e,volume:this.src.nativePath,state:"processing"});try{const[t]=await(0,h.precheckFiles)([this.src]);if(null!=t){const e=d.Task.addOne("syncFile",{path:this.src.nativePath});await e.donePromise()}else this.logger.info("syncFile: no-op",{uri:e})}catch(e){(0,l.syncReport)().onProgress({path:this.src.nativePath,from:"SyncFile",state:l.SyncFileStates.failed,details:(0,o.errorToS)(e)})}finally{t.upsert({state:"done",completedAt:Date.now()})}}},2387:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncManager=void 0;const a=i(83412),o=i(99331),l=i(98314),u=i(95696),c=i(74128),d=i(28874),h=i(98553),f=i(54993),m=i(98401),p=i(20958),g=i(76386),y=i(69032),w=i(56179),v=i(88204),b=i(92244),S=i(46832);class P extends a.DoneWrapper{constructor(){super("SyncManager"),r.add(this),this.doneLatch.observe(n(this,r,"m",s).call(this))}}t.SyncManager=P,r=new WeakSet,s=async function(){const e=d.Settings.argvScanPaths.toNotEmpty()??(d.Settings.exitWhenDone.valueOrDefault?[]:await(0,b.stalePathsToSync)());this.logger.info("#run starting",{paths:e});for(const t of e){this.logger.throwIfAborted_();const e=await(0,S.toUriPath)(t);try{null==e&&this.logger.throw("Could not convert to URI: "+(0,h.stringify)(t));const i=e.nativePath,r=u.PosixFile.forMaybe(i);null==r||null==e?(0,c.syncReport)().onProgress({path:i,from:"SyncManager",state:c.SyncFileStates.failed,details:"Cannot import: path could not be built."}):await r.isFile_()?(this.sync=new v.SyncFile(r),await this.sync.donePromise()):await r.isDirectory_()&&(this.sync=await w.SyncDirectory.for({root:r,rootUri:e.uri}),await(this.sync?.donePromise()))}catch(i){this.logger.info("Failed to sync path",{ea:t,error:i}),(0,c.syncReport)().onProgress({path:e?.nativePath??(0,f.toS)(t),from:"SyncManager",state:c.SyncFileStates.failed,details:(0,l.errorToS)(i)})}await(0,m.maybeCleanup_)(),await(0,y.runTagMaintenance)(),await g.tellWebProgressUpdated.refresh()}this.logger.info("#run complete",{paths:e}),p.Operation.markOpCompleted({name:"forceRestartSync"}),(0,o.ending)()||await(0,c.syncReport)().flushClose()}},92244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.isStale=t.bestPathToSync=t.stalePathsToSync=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(23560),o=i(22277),l=i(87290),u=i(57902),c=i(28874),d=i(40958),h=i(76790),f=i(42659),m=i(75240),p=i(31586),g=i(20958),y=i(49796),w=i(94019),v=i(98622),b=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));t.nativePathBlocklist=new o.TTLSet(10*f.minuteMs);const S=10*f.minuteMs;async function P(){const e=await(0,w.pathsToSync)(),t=c.Settings.forceSync.valueOrDefault?[]:await y.Progress.times();return b().tap({msg:"pathsAndTimesToSync()",level:u.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}function M(e,t){return null==e.lastStartedAt||null==e.lastCompletedAt||(0,p.lte)(e.lastStartedAt,t)||(0,v.runTimeIsStale)(e.lastCompletedAt)}function _(){return g.Operation.getFirstPendingOp({name:g.OperationNames.forceRestartSync})}async function T(e){const t=_(),i=t?.createdAt,s=e.filter((e=>M(e,i)));if((0,d.isEmpty)(s))return(0,a.isSyncService)()&&t?.markCompleted(),b().tap({msg:"bestStable(): No stale paths to sync!",level:"info",result:void 0,meta:{arr:e,forceRestartOp:t}});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,p.gt)(e.lastUpdatedAt,Date.now()-10*f.minuteMs))return b().tap({msg:"bestStable(): returning most recently updated",level:"info",result:{...e,why:"recently updated"}})}const n=(0,r.leastBy)(s,(e=>[e.lastStartedAt??0,e.lastCompletedAt??0]));return b().tap({msg:"bestStable(): returning least-recently-started or least-recently-completed:",level:"info",result:null==n?void 0:{...n,why:"least recently started or completed"},meta:{stale:s}})}function E(e,t){return null==e.lastStartedAt?"new":null==e.lastCompletedAt?"todo":(0,p.gt)(e.lastUpdatedAt,Date.now()-f.minuteMs)?"syncing":M(e,t)?"stale":"synced"}function D(e){return null==e?void 0:new Date(e).toISOString()}function k(e){if(null==e)return;const t=Date.now()-e;return t<2*f.secondMs?"just now":(0,m.fmtDuration)(t)+" ago"}t.pathsAndTimesToSync=P,t.stalePathsToSync=async function(){const e=await P(),t=_(),i=t?.createdAt,r=e.filter((e=>M(e,i)));return(0,h.sortBy)(r,(e=>[null!=e.lastUpdatedAt&&Date.now()-Se.nativePath)),t=await T(e),i=(0,l.libraryOriginalsDirPosixFile)()?.nativePath,r=_()?.createdAt;return e.map((e=>({path:e.nativePath,library:i===e.nativePath,status:E(e,r),isNext:e.nativePath===t?.nativePath,lastStartedISO:D(e.lastStartedAt),lastStarted:k(e.lastStartedAt),lastCompletedISO:D(e.lastCompletedAt),lastCompleted:k(e.lastCompletedAt)})))}},53767:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncService=void 0;const l=i(50213),u=i(7282),c=i(71567),d=i(78406),h=i(25764),f=i(38836),m=i(99331),p=i(45608),g=i(5916),y=i(73614),w=i(76596),v=i(8769),b=i(57159),S=i(63664),P=i(18454),M=i(21525),_=i(21473),T=i(41944),E=i(28874),D=i(2858),k=i(37692),x=i(93493),F=i(42659),C=i(45599),A=i(98553),I=i(98401),O=i(64526),L=i(37158),R=i(56992),N=i(35580),B=i(22968),j=i(63461),z=i(98622),V=i(2387);t.SyncService=class{constructor(){this.logger=(0,l.mkLogger)("SyncService"),r.set(this,void 0),s.set(this,(0,C.defer)((async()=>{await this.service.setup_(),this.logger.info("setup()",{library:E.Settings.libraryDir.valueOrDefault,exitWhenDone:this.exitWhenDone,argvScanPaths:E.Settings.argvScanPaths.values,scanPaths:E.Settings.scanPaths.values,skipLibraryRebuild:E.Settings.skipLibraryRebuild.valueOrDefault,argv:process.argv});const e=O.Library.instanceRequired_();await e.ready;const t=await(0,S.getRemoteOrLocalHealthSummary)();(0,M.isHealthCheckLevelFatal)(t.level)&&await(0,p.exit)({reason:"Health check failed: "+t.msg.join(": "),status:1}),await(0,D.maybeUpgradeSystemSettings)(),await(0,D.maybeUpgradeLibrarySettings)(),await(0,_.testSharp_)(),await(0,x.setupShimDelegates)(),(0,I.scheduleFileAndProcCleanups)(),N.TaskList.instance(),E.Settings.forceRebuildLibrary.valueOrDefault&&(this.logger.info("setup(): "+E.Settings.forceRebuildLibrary.key+" is true: setting all assets to require updates..."),(0,B.forceRebuildLibraryLater)()),(0,u.isTest)()&&T.onProgressEvt.setShim((async e=>console.log((0,A.stringify)(e)))),k.stateEvents.on("checkTasks",(()=>N.TaskList.instance().maybeRunChunk())),new d.EndableInterval({name:"SyncService.setVolumesTTL()",callback:()=>(0,R.setVolumesTTL)(),intervalMs:F.dayMs/4,initialDelayMs:5*F.minuteMs,rank:h.EndableRanks.first}),new f.EndableWrapper("SyncService end status",(async()=>this.logger.info("end status",await this.status())),h.EndableRanks.first),this.run()}))),n.set(this,(0,g.lazyAsync)({desc:"SyncService.run",later:async()=>{if(this.logger.info(".run(): starting"),(0,I.scheduleFileAndProcCleanups)(),await(0,B.maybeRebuildLibrary)(),this.logger.info(".run(): finished library rebuild"),await(N.TaskList.instance()?.awaitDrain()),this.logger.info(".run(): finished task list drain"),o(this,r,new V.SyncManager,"f"),await a(this,r,"f").donePromise(),(0,u.isTest)()&&(0,c.stdoutWrite)(j.SyncCompleted),this.exitWhenDone)return(0,p.exit)({reason:"Finished",status:0});this.logger.info("SyncManager completed. Running cleanups..."),await(0,I.cleanup_)(),(0,I.cancelFileAndProcCleanups)();const e=(0,z.SyncCron)().nextRun();this.logger.info("nextRun",{nextRun:e});const t=e.getTime()-Date.now();this.logger.info("Scheduling next sync run for "+e.toISOString()+" ("+(0,w.durationHMS)(t)+" from now)",E.Settings.syncCron.addToEnv({})),(0,y.setUnrefTimeout)((()=>this.run()),t)}})),this.exitWhenDone=E.Settings.exitWhenDone.valueOrDefault||E.Settings.argvScanPaths.isNotEmpty(),this.service=new L.Service("sync"),a(this,s,"f").call(this).catch((e=>(0,v.onError)(new b.WrappedError("SyncService.setup() failed",{cause:e,fatal:!0}))))}async status(){const e=a(this,r,"f");return{libraryDir:E.Settings.libraryDir.value,ending:(0,m.ending)(),sync:e?.sync?.name,summary:P.HealthCheck.summary()}}run(){const e=a(this,n,"f").prior();return this.logger.info("run()",{prior_pending:e?.isPending}),null!=e&&e.isPending?(this.logger.warn(".run(): preventing overrun: prior run is still pending"),e):a(this,n,"f").refresh()}},r=new WeakMap,s=new WeakMap,n=new WeakMap},46832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.posixFileToUriPath=t.toUriPath=void 0;const r=i(53265),s=i(45200),n=i(22573),a=i(68708),o=i(54993);async function l(e,t){if((0,a.isObject)(e)&&!(0,n.blank)(e.nativePath)&&!(0,n.blank)(e.uri))return e;const i=(0,r.resolve)((0,o.toS)(e)),l=await t??await(0,s.nativePath2uri)(i);return null==l?void 0:{nativePath:i,uri:l.toString()}}t.toUriPath=l,t.posixFileToUriPath=function(e){return l(e.nativePath,e.uriObject_())}},7656:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.DirectAssetCountForTagQuery=t.RecursiveAssetCountForTagQuery=t.nonLeafTagIds=void 0;const r=i(50213),s=i(56038),n=i(95704),a=i(38156),o=i(42659),l=i(45599),u=i(41400),c=i(31586),d=i(51926),h=(0,l.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function f(e){return e.prepare((0,d.compressWhitespace)("SELECT"," t1.id,"," count(t2.id) AS cnt","FROM"," Tag t1"," JOIN Tag t2 ON t1.id = t2.parentId","GROUP BY"," 1","HAVING"," cnt > 0")).pluck().all()}async function m(e,i=[]){const r=e.prepare(t.RecursiveAssetCountForTagQuery).pluck(),o=e.prepare(t.DirectAssetCountForTagQuery).pluck(),l=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId"),c=new Set(f(e)),d=new a.PushProgressObserver({op:"Rebuilding tag asset counts"},e.prepare("SELECT count(*) FROM Tag").pluck().get());await(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e){const e=!c.has(t);(0,s.timeSync)("db.rebuildTagAssetCounts("+(e?"leaf":"cte")+")",(()=>{const s=(e?o:r).get({tagId:t});l.run({tagId:t,assetCount:s,updatedAt:Date.now()}),d.incrProgress(),h().debug("_rebuildTagAssetCounts()",{isLeaf:e,whereClauses:i,tagId:t,assetCount:s})})),t%10==0&&(h().throwIfAborted_(),await(0,u.delay)(1))}}}),d.completed()}t.nonLeafTagIds=f,t.RecursiveAssetCountForTagQuery=(0,d.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.DirectAssetCountForTagQuery=(0,d.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," AssetTag"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," AssetTag.tagId = :tagId"," AND Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL;"),t.rebuildTagAssetCounts=async function(e,t=o.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>m(e,["assetCount IS NULL"]))),(0,c.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rm(e)))}},69032:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(1728),c=i(56038),d=i(34102),h=i(49076),f=i(69589),m=i(28874),p=i(42231),g=i(85087),y=i(98770),w=i(59107),v=i(63870),b=i(7014),S=i(22573),P=i(42659),M=i(41400),_=i(75240),T=i(31586),E=i(34666),D=i(51926),k=i(75020),x=i(54017),F=i(48723),C=i(98784),A=i(7656),I=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>C.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return I().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=((0,o.isTest)()?5:30)*P.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=I().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),F.Tag.validate_(),s.throwIfAborted_(i?.halt),await L(),i.recountAllTags&&(s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)(),s.info("rebuilding tag asset counts..."),await(0,A.rebuildTagAssetCounts)(F.Tag.dbl.db().db,0))}catch(e){I().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,T.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),I().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const L=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{I().info("updating tag mountpoints...");const e=F.Tag.findByPath([k.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await N(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function R(){t.tagFtsRebuild.unset(),L.unset()}async function N(e){if(null==e||2!==e.depth||!e._path.startsWith(k.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===k.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),F.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,v.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),F.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",R),m.Settings.libraryDir.watchLater(R)})),t.fixFileRootTag=N,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,v.volumeMetadataTtlMs)()}),(0,M.later)((()=>{w.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},16436:e=>{"use strict";e.exports=require("@sentry/node")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},87550:e=>{"use strict";e.exports=require("better-sqlite3")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},66150:e=>{"use strict";e.exports=require("fast-xml-parser")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},31832:e=>{"use strict";e.exports=require("knex")},51168:e=>{"use strict";e.exports=require("luxon")},93973:e=>{"use strict";e.exports=require("ml-kmeans")},4927:e=>{"use strict";e.exports=require("papaparse")},83058:e=>{"use strict";e.exports=require("picomatch")},57272:e=>{"use strict";e.exports=require("plist")},85949:e=>{"use strict";e.exports=require("process")},90595:e=>{"use strict";e.exports=require("punycode")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},93944:e=>{"use strict";e.exports=require("source-map-support")},49378:e=>{"use strict";e.exports=require("trash")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},29907:e=>{"use strict";e.exports=require("cluster")},76982:e=>{"use strict";e.exports=require("crypto")},34589:e=>{"use strict";e.exports=require("node:assert")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=34742);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463:(e,t,i)=>{const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),w=m(y,f);return a(s,t,o,p,w)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),w=m(g,p);if(!l(s,w))throw new o("decryption failed");const v=await y(a,f,r.subarray(16));if(!v)throw new o("decryption failed");return v},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),w=u.subarray(32),v=await g(e,y,w),b=n(o,l,v,t,s),S=m(b,p);return a(o,t,l,v,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),w=p.subarray(0,32),v=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,w,v);if(!P)throw new o("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223:e=>{const t=36e5,i=24*t,r=7*i,s=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const n=s.exec(e);if(!n)throw new TypeError(`invalid time period format ("${e}")`);const a=parseFloat(n[1]);switch(n[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*a);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*a);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(a*t);case"day":case"days":case"d":return Math.round(a*i);case"week":case"weeks":case"w":return Math.round(a*r);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*a)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227:(e,t,i)=>{const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120:(e,t,i)=>{const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827:(e,t,i)=>{const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015:(e,t,i)=>{const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function w(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...w(e.slice(i+1))]}function v(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return M(e,(e=>e.valueOf()))}function P(e,t){return T(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return T(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function T(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function k(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return w(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=v,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=D,t.collectBatched=function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of D((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await k(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),w=i(25764),v=i(38836),b=i(99331),S=i(95937),P=i(98314),M=i(38835),_=i(70025),T=i(8769),E=i(43334),D=i(95402),k=i(28874),x=i(63870);class F extends v.EndableWrapper{constructor(e,t,i=w.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>n(this,r,"m",s).call(this)),i,"worker"===e?(0,x.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,D.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,S.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+M.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&D.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,b.ending)()||!0===(0,_.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,T.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=F,r=new WeakSet,s=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(E.isWin?3:1)*c.minuteMs,maxTasksPerProcess:k.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:k.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:k.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,x.commandTimeoutMs)(),taskTimeoutMillis:k.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,s.set(this,void 0),n.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,s,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]=t))}get length(){return u(this,n,"f")}set length(e){l(this,n,(0,d.clamp)(0,u(this,n,"f"),e),"f")}clear(){this.length=0}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,n,"f")),e<0||e>=u(this,n,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,s,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,n,"f"){u(this,s,"f")[e]=c}));return u(this,n,"f")}pop(){return u(this,r,"m",o).call(this,u(this,n,"f")-1,(e=>{var t;return l(this,n,(t=u(this,n,"f"),--t),"f"),u(this,s,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,n,"f"){u(this,s,"f")[e]=c,l(this,a,e,"f")}));return u(this,n,"f")}shift(){return u(this,r,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,n,(i=u(this,n,"f"),--i),"f"),u(this,s,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",o).call(this,u(this,n,"f")-1-e,(e=>{const i=u(this,s,"f")[e];u(this,s,"f")[e]=u(this,s,"f")[t],u(this,s,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=n(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),s=i(31586),n=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),s=i(65843),n=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),s=i(20014),n=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)((()=>!1))},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),s=i(98553);var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},57206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(77988),s=i(51168),n=i(45599),a=i(98553),o=i(68708),l=i(24689),u=i(21330),c=i(57159),d=i(28544),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},19851:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function w(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(w()??await(m.isWin?P():m.isMac?_():T()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(w);const v=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=v.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function T(){return S(w((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=T,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),s=i(32105),n=i(14593);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),s=i(55835),n=i(59455),a=i(48884);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),s=i(54557);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),s=i(42659),n=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,s]of(0,l.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,l.keys)(e))if(r[n]=t(n,e[n]),s++,(0,o.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,n.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),s=i(73024),n=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),w=i(30933),v=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return F();case"win32":return C();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function T(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){v().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=T;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},D={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function k(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function F(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return k(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return v().warn("osNameMac(): unknown release",e),b()}}function C(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":k(e,D);return null!=t?`Windows ${t} (${e})`:(v().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=F,t.osNameWin=C,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,w.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(C())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(T())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},45393:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=4},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(72993),s=i(50213),n=i(23560),a=i(43334);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(85949).title=t}catch(e){(0,s.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},92782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),s=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),s=i(56409),n=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,v(...e)}}async function w(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return s.promise}const v=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return w(...e)};return v.clear=()=>{h=void 0},v.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},v.force=async(...e)=>(h=void 0,f&&await v.donePromise(),w(...e)),v.isRateLimited=()=>g(),v.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),v.minCallDelayMs=()=>t,v.setMinCallDelayMs=e=>{t=e},v}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),s=i(54993);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),w=i(34102),v=i(43334),b=i(24399),S=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,w.ee)().on("clearCache",(()=>T.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>v.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const T=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||T().has(e))return;T().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;_=!1}try{return await(v.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(1708)),n=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),s=i(57150),n=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,n.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,s.logStartup)())}},28850:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),s.set(this,void 0),n(this,r,e,"f")}_call(){return(0,l.time)(a(this,r,"f")+(null==a(this,s,"f")?"(local)":"(remote)"),null==a(this,s,"f")?this.impl():a(this,s,"f").call(this))}setShim(e){n(this,s,e,"f")}hasShim(){return null!=a(this,s,"f")}clearShim(){n(this,s,void 0,"f")}}r=new WeakMap,s=new WeakMap},12089:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=a,s.set(this,void 0),n.set(this,void 0),l(this,s,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",a).call(this,e),(()=>u(this,r,"m",o).call(this,e)))}setShim(e){l(this,n,e,"f")}hasShim(){return null!=u(this,n,"f")}clearShim(){l(this,n,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",a).call(this,e))}}s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,s,"f")+(null==u(this,n,"f")?"(local)":"(remote)"),null==u(this,n,"f")?this.impl(e):u(this,n,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return s(this,r,"f")[Symbol.iterator]()}get length(){return s(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=s(this,r,"f").length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),a=this.valueOf(s(this,r,"f")[n]);if(e===a)return{found:!0,index:n};e>a?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&s(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...s(this,r,"f")];const a=t=>t<0||t>s(this,r,"f").length-1?null:(i??this.diff)(s(this,r,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return s(this,r,"f").shift()}at(e){return(0,a.at)(s(this,r,"f"),e)}toA(){return[...s(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===s(this,r,"f").length-1){const e=[...s(this,r,"f")];return s(this,r,"f").length=0,e}return s(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return s(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),s=i(82328),n=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),s=i(95705);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const w=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" …(+"+s+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const v=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return v.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const T=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=T.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['‘’].*['‘’]$/,D=/^["“”„«»〃].*["“”„«»〃]$/;function k(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>w.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=k,t.splitUp=x,t.sortNaturalBy=F,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>F(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const C=/#.*$/gm;t.stripComments=function(e){return e.replace(C,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function w(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=v(i),t=v(r);return 2*b(e,t).length/(e.length+t.length)}))}function v(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=w,t.bigrams=v,t.nonUniqIntersection=b,t.lnsDiff=M;const _=/[^\da-z]+/gi;function T(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=T,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:w(e,t),lns:M(e,t),radixDiff:T(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),s=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},88264:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TTLArray=void 0;const r=i(31586);class s{constructor(e,t){this.ttlMs=e,this.maxLength=t,this.times=[],this.a=[],this.expirationListeners=[]}[Symbol.iterator](){this.vacuum();const e=[...this.a];return function*(){for(const t of e)yield t}()}push(...e){(0,r.times)(e.length,(()=>this.times.push(Date.now()))),this.a.push(...e),null!=this.maxLength&&this.vacuum()}pushUniq(...e){e.forEach((e=>{this.includes(e)||this.push(e)}))}includes(e){return this.vacuum(),this.a.indexOf(e)>=0}find(e){return this.vacuum(),this.a.find(e)}some(e){return this.vacuum(),this.a.some(e)}shift(){return this.vacuum(),this.times.shift(),this.a.shift()}first(){return this.vacuum(),this.a[0]}last(){return this.vacuum(),this.a[this.a.length-1]}shiftOrFirst(){return this.length>1?this.shift():this.first()}pop(){return this.vacuum(),this.times.pop(),this.a.pop()}onExpire(e){this.expirationListeners.push(e)}slice(e,t){return this.vacuum(),this.a.slice(e,t)}get length(){return this.vacuum(),this.a.length}clear(){return this.times.length=0,this.a.length=0,this}get values(){return this.vacuum(),[...this.a]}map(e){return this.vacuum(),this.a.map(e)}oldestEntryAge(){return this.vacuum(),this.times[0]}vacuum(){if(0===this.a.length)return;const e=this.a.length;if(null!=this.maxLength){const e=this.a.length-this.maxLength;this.times.splice(0,e),this.a.splice(0,e)}const t=Date.now()-this.ttlMs,i=this.times.findIndex((e=>e>t));if(-1===i?this.clear():i>0&&(this.times.splice(0,i),this.a.splice(0,i)),e!==this.a.length)for(const e of this.expirationListeners)e()}}t.TTLArray=s},75387:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},65211:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(19851),s=i(76790),n=i(22573),a=i(54993),o=i(7282),l=i(55222);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!(0,o.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),u=0}},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),s=i(55835),n=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},79184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(59455),s=i(48884),n=i(22859),a=i(28874),o=i(79781),l=i(92434);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(50357),o=i(55835),l=i(31586),u=i(68708),c=i(12168),d=i(23467),h=i(73168),f=i(50213),m=i(86580),p=i(48368),g=i(80361),y=i(28874),w=i(28544),v=i(75767),b=i(16170),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} ≠ ${o}`}function M(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function _(e,t){return[M(e),M(t)]}function T(e,t,i){const r=(0,v.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.aKey}:${r.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=w.CapturedAt.fromAssetFile(e),f=w.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const M=a.isFuzzy||f.isFuzzy;if(M&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",_)??P(e,i,"model",_);if(null!=E)return E;const D=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),k={cameraId:T(e,i,"cameraId")??null,imageId:T(e,i,"imageId")??null,lensId:T(e,i,"lensId")??null,exposureSettings:(0,v.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(D,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(D)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:k});const x=(0,s.compact)((0,u.values)(k));if((0,s.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:M});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(k).filter((e=>null==k[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos ≠ images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=E(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},13991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(19851),s=i(55835),n=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function w(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function v(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([w(e),v(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=w,t.assetFileStatFields_=v,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),w=i(14036),v=i(45200),b=i(34238),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function T(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=T;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function D(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,F).reverse()}function k(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,w.isSupportedByCurrentBrowserExt)(n.ext),mtime:T(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function F(e){const t=k(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=D,t.assetFileSortCriteriaPojo=k,t.assetFileSortFields=x,t.assetFileSortCriteria=F,t.bestExistingAssetFile=async function(e){for(const t of D(e))if(await(0,v.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),s.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,n(this,s,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return n(this,s,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,n(this,s,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=n(this,r,"f")&&clearTimeout(n(this,r,"f")),a(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,s=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(87997)),n=i(31586);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const w=y(i(87997)),v=y(i(57975)),b=i(45599),S=i(26905),P=i(55835),M=i(31586),_=i(68708),T=i(20214),E=i(57153),D=i(85556),k=i(50213),x=i(70025),F=i(95937),C="TIMEOUT",A=(0,b.defer)((()=>(0,k.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,M.gt0)(t)?new s(C).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const s=i[r];if(s.isSettled){if(s.name===C)return void A().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield s.value}}if(i.every((e=>e.name===C)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,k.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[v.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,T.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(w.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,M.gt0)(e)&&(g(this,h,w.default.setTimeout((()=>{this.isPending&&(this.reject(new D.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,F.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,s=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),w.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},83412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DoneWrapper=void 0;const r=i(56409),s=i(38836);class n extends s.EndableWrapper{constructor(){super(...arguments),this.doneLatch=new r.Latch}isDone(){return this.doneLatch.isSettled()||this.ended}donePromise(){return this.doneLatch.promise}}t.DoneWrapper=n},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>v()),10*n.minuteMs);const y=5*n.secondMs;async function w(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function v(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>w(e))))},t.end=w,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),v();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>w(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,s.compact)(g.valuesFlat()).map((e=>w(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class w extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=w,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,s=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function w(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=w,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{w({reason:`${e}:${t}`,status:0,error:i})}))}))},39250:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(23838),a=i(54993),o=i(15674),l=i(73568),u=i(76740),c=i(99331),d=i(42638);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new d.Promises(e,t)}vacuum(){return s(this,r,"f").filterInPlace(((e,t)=>t.isPending&&!0!==t.payload?.aborted)),s(this,r,"f").valueCount()}enqueue({key:e,abortable:t,fn:i}){for(const t of s(this,r,"f").get(e)??[])t.payload?.abort("aborted by new work");if(this.vacuum(),(0,c.ending)())throw new l.AbortError("ending");const n=t??new u.Abortable,o=this.p.serial((0,a.toS)(e),(()=>i(n)),n);return s(this,r,"f").add(e,o),o}},r=new WeakMap},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),w=i(22911),v=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new b(e,t,i,r)};class b extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,n,0,"f"),d(this,s,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,r,"m",u).call(this,w.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,n,"f")}isStale(){return null==c(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,s,"f")?void 0:Date.now()-c(this,s,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(v().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,n,(i=c(this,n,"f"),++i),"f")}},u=function(e){d(this,s,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof w.Deferred?e:new w.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),s=i(80049);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},22781:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),s.set(this,!1),n.set(this,!1)}_call(){return a(this,s,"f")?(o(this,n,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,r,"f")):(o(this,s,!0,"f"),o(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,s,!1,"f"),!0===this.runLaterIfBusy&&a(this,n,"f")&&(o(this,n,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,s,"f")}prior(){return a(this,r,"f")}async force(){return await a(this,r,"f"),this._call()}}r=new WeakMap,s=new WeakMap,n=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),w=i(15674),v=i(42638);var b=i(20214);async function S(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,l.gt0)(s)?(0,c.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function _({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,w.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:n});const u=a??(o.length<=s?v.PermissivePromises:new v.Promises(i,(()=>s))),d=(0,l.gt0)(n)?e=>(0,c.thenOrTimeoutError)(t(e),n):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=S,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await S(s);r.push(...await S(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await _({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){s=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await _({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),w=i(25764),v=i(38836),b=i(73614);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new v.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),w.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),r=t();return _(e,Date.now()-i),r},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>M(e,t)),i)}},42638:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),w=i(54993),v=i(89788),b=i(82647),S=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,w.toS)(e)};class M{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new v.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},59189:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(1708)),n=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),w=i(50213),v=i(7282),b=i(88158),S=i(45969),P=i(43334),M=i(28874),_=i(3790);function T(e){return E().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const E=(0,n.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(M.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,b.sortedKeys)((0,l.filter)((0,d.env)(),(e=>T(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,M.allSettings)())t.watchLater(e)}));const D=["HOME","LANG","USER"],k=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?D:k),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,M.pathWithDefaults)(),e}));function F(e){const t={NODE_ENV:(0,v.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,S.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,M.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,o.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(s.default.env,(e=>T(e)||!(0,_.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=F,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:A({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let C=!1;function A({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,g.childProcLocale)():{},...F(r),...e??{}});for(const e of(0,M.transientSettings)())e.deleteFromEnv(s);if((0,y.isLogged)("debug")&&!C){C=!0;const e=(0,w.mkLogger)("child.ChildEnv"),t=(0,l.entries)(s).map((([e,t])=>[e,(0,_.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>T(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return s}t.childEnv=A},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),w=i(79089),v=i(45255),b=i(22911),S=i(4867),P=i(73614),M=i(70025),_=i(57159),T=i(36868),E=i(66184),D=i(45643),k=i(95402),x=i(9727),F=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function C(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function A(e,t=30*u.secondMs){if(null==e)return!1;F().debug("endProcess()",C(e));const i=e.pid;if(null==i||i<=0)return F().warn("endProcess(): asked to end invalid pid",C(e)),!1;if(i===n.default.pid)return F().warn("endProcess(): asked to end MY pid",C(e)),!1;if(i===n.default.ppid)return F().warn("endProcess(): asked to end my parent pid",C(e)),!1;(0,T.closeStreams)(e);{const t=e.kill();F().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,k.killPid)(i).catch((e=>{F().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,D.waitForPidExit)(i,t))return F().debug("endProcess(): exitted",C(e)),!0;{k.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");F().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,k.killPid)(i,!0).catch((e=>{F().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,D.waitForPidExit)(i,5e3)}function I(e,i,r,s=0){const a=new Date,o=[];return(0,w.niceable)(i,r)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,w.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&A(e)}),s-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,k.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,E.isLogged)("trace",F().context)?F().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):F().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new b.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,T.endStream)(a.stdin);const w=new d.Latch;null==a.stdout?w.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>w.resolve())));const P=new d.Latch;null==a.stderr||s?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),F().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,S.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),F().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:w.state(),stderr:P.state()}),await(0,S.thenOrTimeoutError)({p:w.promise,timeoutMs:v.ShortCommandTimeoutMs,halt:i.halt}),await(0,S.thenOrTimeoutError)({p:P.promise,timeoutMs:v.ShortCommandTimeoutMs,halt:i.halt});const E=p.join("");(0,l.notBlank)(E)&&g.push(new Error(E)),!r&&(0,o.isNotEmpty)(g)&&F().warn(f+" resulted in errors:",g);const D=i.isIgnorableError??M.isIgnorableError,k=g.filter((e=>!0!==D(e)));if(k.length>0)throw 1===k.length?k[0]:new _.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:k});if(!n&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:E}}catch(e){throw F().error("stdoutResult_() failed",e),await(0,k.killPid)(a.pid,!0),e}}t.endProcess=A,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return F().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return F().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},86335:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(77598),u=o(i(1708)),c=i(19851),d=i(40958),h=i(22573),f=i(50268),m=i(68708),p=i(5670),g=i(50989),y=i(12168),w=i(59455),v=i(41583),b=i(54993),S=i(80875),P=i(50213),M=i(81168),_=i(27395),T=i(25764),E=i(59958),D=i(70025),k=i(83278),x=i(85021),F=i(29325),C=i(43334),A=i(28874),I=i(84777),O=i(55534),L=i(85100),R=i(34330),N=(0,c.lazy)((()=>(0,P.mkLogger)("child.ChildService")));async function B(e){const t=(0,M.ensureSuffix)(e,".js"),i=k.BaseFile.projectRoot(),r=k.BaseFile.for(u.default.cwd()),s=(0,F.isPacked)()?[i.join("bin",t),C.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];(0,F.isPacked)()||(C.isElectron?(s.push(r.join("dist","app",t)),s.push(i.join("src","desktop","dist","library",t))):s.push(i.join("src","library","dist","library",t)));for(const e of s)if(null!=e&&!0===await e.isNonEmptyFile((0,F.isPacked)()?y.KB:128))return N().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:F.isPacked,paths:s.map(b.toS)}});return N().throw("Failed to find path to "+e,{paths:s,fatal:!0})}t.pathToService=B,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=(0,g.strEnum)(...p.ServiceNames.pick("web","sync"));class j{static async mk_(e,t={}){const i=t.pathToService??await B(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,w.toA)(t.nodeArgs),new j(e,i,t)}constructor(e,t,i){var o,l;r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,L.serviceExitTimeoutMs)(e),this.logger=(0,P.mkLogger)(this.name);const c=[...(0,w.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&c.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale","forWorker"),this.spawnOpts.forceCLocale=!1,(l=(o=this.spawnOpts).env??(o.env={}))[E.UV_THREADPOOL_SIZE]??(l[E.UV_THREADPOOL_SIZE]=(0,b.toS)(("web"===e?A.Settings.webUvThreads:A.Settings.syncUvThreads).valueOrDefault)),this.wc=new R.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&await(this.opts.onPreRestart?.()),this.restartCount++,(0,I.spawn)(u.default.execPath,c,-1,this.spawnOpts)),endableRank:T.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:a(this,r,"m",n).bind(this),onStderr:a(this,r,"m",s).bind(this),onError:this.opts.onError??(e=>!1===(0,D.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:O.ServiceExitCommand,...i}),(0,_.addEndable)(T.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(x.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(O.ServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,M.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,v.toErr)(i)),this.write(e,t-1)}}}t.ChildService=j,r=new WeakSet,s=function(e){const t=(0,S.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},n=function(e){if(!(0,h.blank)(e))try{const t=(0,S.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){const e="failed"===t.state||"error"===t.level;this.logger.log(e?"error":"info",".onStdout(): health check summary",t),e&&this.wc.onError(this.name+".onStdout()",t,e)}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),s=i(41400),n=i(19851),a=i(28874);(0,s.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,n.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},85100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(23560),s=i(28874),n=i(45255);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?s.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},34330:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),w=i(54993),v=i(27395),b=i(25764),S=i(99331),P=i(42638),M=i(38835),_=i(8769),T=i(57159),E=i(66003),D=i(50213),k=i(45643),x=i(28874),F=i(84777);t.mkBasicWatchedChild=function(e){return new C({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,F.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class C{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,D.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new T.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,_.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,v.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=C,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,k.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,F.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,w.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),s=i.sibling(r);if(s.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",s.posixPathFrom((0,l.examples)()));const n=(0,d.originalsDir)();if(s.isSelfOrDescendantOf(n))return a.join("$library",s.posixPathFrom(n));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",s.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(6858),a=i(1708),o=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return s(this,r,"f").push(...e),this}async parse(e=a.argv,t){let i=(0,m.addHelpFooter)(new n.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of s(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":o.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,a.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of s(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),s=i(38639),n=i(17181),a=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,s.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),a.Settings.logColor.envValue=e,(0,n.setupLogFormatter)()}))}}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(1708)),n=i(22573),a=i(38639);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},53978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},43380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(28874),s=i(2858),n=i(22573),a=i(38639),o=i(46292);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},54772:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),w=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function v(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void w().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void w().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(v)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=v,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(v(e))}function y(e){return(0,f.clampRGB)(T(_(e)))}function w(e){return(0,t.LabBitZip)().clampValue(e)}function v(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return w([116*i-16,500*(t-i),200*(i-r)])}function _(e){const[t,i,r]=w(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function T(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=T,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const D=new Map;function k(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function F(e){return C(x(e))}function C(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function A(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function I(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(D,e,(()=>k(e,t))):k(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return F((0,f.rgbhex2triplet)(e))},t.rgb2hsl=F,t.hsl2rgb=function(e){return I(A(e))},t.hsv2hsl=C,t.hsl2hsv=A,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},42079:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(31586),s=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),w=(0,s.sqrt)(g*g+h*h);let v=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);v+=2*(v<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=w-y;let M=y*w==0?0:b-v;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,s.sqrt)(y*w)*Math.sin(M/2),T=(i+c)/2,E=(y+w)/2;let D;y*w==0?D=v+b:(D=(v+b)/2,D-=(Math.abs(v-b)>Math.PI?1:0)*Math.PI,D+=2*(D<0?1:0)*Math.PI);const k=(T-50)**2,x=1-.17*Math.cos(D-Math.PI/6)+.24*Math.cos(2*D)+.32*Math.cos(3*D+Math.PI/30)-.2*Math.cos(4*D-63*Math.PI/180),F=1+.015*k/(0,s.sqrt)(20+k),C=1+.045*E,A=1+.015*E*x,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*D-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*I)*O;return(0,s.sqrt)(Math.pow(S/(n*F),2)+Math.pow(P/(a*C),2)+Math.pow(_/(o*A),2)+L*P/(a*C)*_/(o*A))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(40958),s=i(31586),n=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},32848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(48884),o=i(31843),l=i(70417),u=i(3048);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},40401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),w=i(85810),v=i(3048),b=i(76490),S=i(1971),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,w.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??v.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,w.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function k(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const F=f.length<=g?[]:(0,s.compact)(M.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...T,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&k(g-1);const n=s.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,w.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n),2);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:F.map((e=>(0,u.pick)(e,"description","score")))});const C=(0,c.leastBy)(F,(e=>e.score));if(null==C)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),D(a,t);const A=(0,o.stringify)({...C?.description,elapsedMs:Date.now()-i}),I=(0,n.sortBy)(C?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:A,score:C?.score,totalColors:a.size,totalPixels:f.length,iters:C?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:A,dominantColorScore:C?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,v.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,v.ciede2000_delta_e)(e.centroid,r))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:v.cie76_delta_e,cie94:v.cie94_delta_e,ciede2000:v.ciede2000_delta_e},T=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function D(e,t){const i=e.countSum,r=e.size;k(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function k(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,w.unlabhash)(r),a=i.find((e=>(0,v.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,v.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{T.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=D,t.mergeLabhashes=k,t.mergeNearCentroids=x},85409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(31586),s=i(68708),n=i(50989);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),w=i(21330),v=i(928),b=i(54261),S=i(73389),P=i(51275),M=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof w.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function T(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof w.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),k(e),((e,t)=>e+t))}function D(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof w.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function k(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,v.getMillisecond)(e)))return 0;if((0,c.gt0)((0,v.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,v.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,v.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,v.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,v.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=T(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function F(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function C(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??w.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=T,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):D(e)},t.datedToDateTime=D,t.datedToPrecisionMs=k,t.isoToPrecisionMs=function(e){return(0,u.map)(C(e),k)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=k(e)),r??(r=k(t)),F(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,w.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,w.setZone)(t,s)??t),F(e,t,i,r)},t.isoToDated=C,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),s=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),s=i(31586),n=i(54557),a=i(91655),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),s=i(40958),n=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function w(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),w=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(w)??i,rawValue:e,tzoffsetMinutes:w})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??w(e,b(),t)},t.parseExifDateTimeRe=w;const v=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,v,p.monthRE,v,p.dayRE,/[T\s]/,p.hourRE,v,p.minuteRE,v,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),w=i(79842),v=i(66649),b=i(98247),S=i(98725),P=i(928),M=i(54261),_=i(73389),T=i(89724),E=i(17415),D=i(88600),k=i(51275);function x(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class F{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,D.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(S.ISO_YMD_RE.exec(e)?.groups??S.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tx(e))).join("-")}toLocal(){return(0,T.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new F(t.year,t.month,t.day)}}function C(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,M.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,E.zoneToTzOffsetMinutes)((0,v.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(s=>(0,d.map)((0,P.getDay)(e),(n=>(0,d.map)((0,P.getHour)(e),(a=>(0,b.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=F,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,h.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${x(n)}:${x(a)}`},t.toExifDateTime=C,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,M.hasTime)(e)||(i??(0,w.datedToPrecisionMs)(e))>=c.dayMs?O(e):C(e,(0,k.getZoneName)(e))?.toISOString({includeOffset:t})};const A="yyyy:MM:dd HH:mm:ss.SSS",I=A+"ZZ";function O(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>x(e))).join(t)}function L(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new F(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(v.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,w.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,k.hasZone)(t)?I:A):void 0},t.datedToYMD=O,t.toFuzzyDate=L,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,v.datedToMillis)(e)||null==(0,v.datedToMillis)(t))return;const[s,n]=[e,t].map((e=>(0,v.datedToMillis)(e))).sort(),o=(n-s)/(r+1),l=(0,k.getZoneName)(e),u=l===(0,k.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,M.hasTime)(e)))?L(c):c},t.setZone=function(e,t,i){const r={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,k.hasZone)(e)},s=(0,E.normalizeZone)(t);return null!=e&&null!=s&&(0,M.hasTime)(e)?e instanceof y.DateInterval?e.setZone(s,r):C(e)?.setZone(s,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,w.datedToDateTime)(e);if(null==i)return;const r=(0,k.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),w=i(68852),v=i(4001),b=i(28874),S=i(24689),P=i(79842),M=i(66649),_=i(98247),T=i(21330),E=i(54261),D=i(73389),k=i(16400),x=i(88600),F=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return F().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,w.concatRegexp)([/^/,t.yearRE,w.RegExpOptional.from(/-/,t.monthRE,w.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,w.concatRegexp)([/^/,t.yearishRE,w.RegExpOptional.from(/-/,t.monthishRE,w.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,D.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const C=new Map;function A(e,t,i){try{const r=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(C,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void F().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void F().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(v.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>A(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const e of n){const t=a(e);if(null!=t&&(0,x.isValidDate)(t))return t}}t.parseDated=I;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;T.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new w.RegExpEscaped("(?"+(0,k.monthNames)().map(w.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,w.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return T.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,k.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),s=i(31586),n=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),s=i(31586),n=i(68708);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),s=i(19851),n=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,s.lazy)((()=>w(l.Settings.datesBeforeAreEstimated.valueOrDefault)??w(l.Settings.datesBeforeAreEstimated.defaultValue)));function w(e){return(0,a.map)((0,c.isoToDated)(e),v)}function v(e){return(0,o.isNumber)(e)?_(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return v(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},42499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(51168),s=i(19851),n=i(19043),a=i(28874);t.setupLuxon=(0,s.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,n.locale)()}))},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,T=/(?[-±+−])/,E=/[-−]/,D=/(?[01]\d)/,k=/(?[01]?\d)/,x=/(?::(?\d\d))/;function F(e){return b(e)?0:C((0,t.TimezoneOffsetRE)().exec(e))}function C(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return w(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),T,D,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=F,t.timezoneOffsetFromRegExpMatch=C;const A=/\b(?(?:Etc\/)?GMT)\b/,I=(0,n.lazy)((()=>(0,m.concatRegexp)([A,T,k,m.RegExpOptional.from(x)])));function O(e){return C(I().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??F(e);if(null!=i)return M(i);if(null!=t){const i=S(e);if(null!=i)return M(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),w=(0,s.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),v=(0,s.lazy)((()=>(0,n.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),b=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,p.datedToISO)(e)))))),S=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,y.datedToLocal)(e)))))),P=(0,s.lazy)((()=>(0,n.compact)(v().map((e=>(0,m.datedToMillis)(e))))));function M(e){if(null==e)return!1;const t=T(e);return w().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return M(e)?e:void 0},t.isValidDate=M;const _=String(new Date("bad"));function T(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===_)return _;const t=(0,n.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,E())&&s.push("year is in the future"),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):S().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):b().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(t)).join("; "))}catch(t){return w().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=T;const E=(0,s.lazy)((()=>r.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return M(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==T({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),s=i(31586),n=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},82261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},92407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(19851),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},55332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(19851),s=i(50213),n=i(76187),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},91872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i,r){const a=Date.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}))}},12943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(79842),s=i(66649),n=i(40958),a=i(68708);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},65753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(19851),s=i(7282),n=i(28874);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*((0,s.isTest)()?.25:5))))},80632:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(54993),u=i(50213),c=i(23560),d=i(65211),h=i(29882),f=i(53265),m=i(66430),p=i(66184),g=i(28874),y=i(15674),w=i(87550);function v(){const e=g.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,a.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=g.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=g.Settings.logSql.valueOrDefault}){e=(0,f.resolve)(e),(0,h.mkdirpSync_)((0,r.dirname)(e));const b=(0,h.posixPathFromGrandparent)(e),S=(0,m.nativePathSizeSync)(e),P=(0,u.mkLogger)("db.mkdb("+b+")");if(null!=S){const E=Math.round(S/o.MiB),D=Math.ceil(1.5*E);D>g.Settings.dbCacheSizeMb.valueOrDefault&&(P.info("Dynamically setting dbCacheSize to "+g.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:E}),g.Settings.dbCacheSizeMb.envValue=D);const k=Math.round(1.5*E);k>g.Settings.maxMemoryMb.valueOrDefault&&(P.warn("Large database: setting maxMemoryDb to "+k+"MB",{dbFileSizeMb:E,"Settings.maxMemoryMb":g.Settings.maxMemoryMb.valueOrDefault}),g.Settings.maxMemoryMb.envValue=k)}P.info("Opening "+e+"...");const M={fileMustExist:!1,readonly:!1};if((0,a.gt0)(t)&&(M.timeout=Math.ceil(t)),i){const x=(0,u.mkLogger)("SQLite("+b+")"),F=(0,p.defaultLogLevel)();function C(e,...t){var i;(0,n.blank)(e)||x.log(F,(i=e,(0,l.toS)(i).replace(/\s{2,}/g," ")),{args:t})}M.verbose=C}const _=new w(e,M);P.info("Open. Setting PRAGMAs...");for(const A of(0,s.compact)(['encoding = "UTF-8"',"threads = "+(0,y.maxCpus)(),"foreign_keys = ON","page_size = "+v(),"trusted_schema = 0","cache_size = -"+Math.round(g.Settings.dbCacheSizeMb.valueOrDefault*o.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL",(0,a.gt0)(g.Settings.dbBusyTimeoutMs.valueOrDefault)?"busy_timeout = "+g.Settings.dbBusyTimeoutMs.valueOrDefault:null,"temp_store = MEMORY","synchronous = "+g.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,c.isDbJanitorService)()?(0,l.toS)(g.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+g.Settings.dbAutoVacuumMode.valueOrDefault]))P.tapThunk({msg:"PRAGMA "+A,result:()=>_.pragma(A)});const T=_;return T.__uid=(0,d.uid)(),T},t.pageSizeBytes=v},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},95704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(40958),s=i(31586),n=i(59455),a=i(65753),o=i(51040);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},76187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(17217),s=i(87391),n=i(7311);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},51040:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+$/gm,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(19851),s=i(50357),n=i(30976),a=i(50213),o=i(95696),l=i(80632),u=i(76187),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},87391:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),w=i(70698),v=i(64680),b=i(29882),S=i(45969),P=i(43334),M=i(28874),_=i(41692),T=i(32774),E=i(80612),D=i(32551),k=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function x(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+k(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+k()),preexistingDir:i});return e}}function F(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:T.DefaultDockerLibraryDir+"/.photostructure/cache"+k(),preexistingDir:T.DefaultDockerLibraryDir},...x()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,D.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,D.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,D.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...x()),i}t.tmpCacheDirs=x,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:x(),desc:"tmp"})},t.cacheDirs=F,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:F(),desc:"cache"})));const C=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),M.Settings.cacheDir.watchLater(A)}));function A(){M.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{C();const e=M.Settings.cacheDir.valueOrDefault;try{return(0,b.mkdirpSync_)(e),(0,w.writeCachedirTag_)(e).then((()=>(0,v.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=A},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),s=i(45969),n=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),s=i(45969),n=i(32774);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),s=i(96706),n=i(29882);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),s=i(49776),n=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),s=i(54993),n=i(29882),a=i(28874);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),s=i(55835),n=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function w(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function v(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(v(e),!1)}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function T(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await w(t);return(0,r.uniq)([t,i,await b(t),await P(t),await _(t),await T(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=w,t.libraryOriginalsDirPosixFile=v,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=T},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),w=i(80612),v=i(32551);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,v.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,v.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,w.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,v.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),s=i(7282),n=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),s=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),w=i(59958),v=i(6012),b=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(w.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,n.join)((0,m.homeDir)(),".psenv"));const t=(0,b.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,d.debom)(s.default.readFileSync((0,g.resolve)(r))),n=(0,v.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(n))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),s=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(1708)),n=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),s=i(19851),n=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),w=i(70025),v=i(57159);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,w.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,w.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function M(e,t){return e instanceof v.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),s=i(26905),n=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},68301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(19851),s=i(42659),n=i(75240),a=i(55835),o=i(31586),l=i(68708),u=i(59455),c=i(54993),d=i(50213),h=i(45255),f=i(37628),m=i(99331),p=i(46292),g=i(38835),y=i(32144),w=i(29882),v=i(95696),b=i(55222),S=i(28874),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function M(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class _{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*s.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=s.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,w.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),s=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=s,meta:{event:M(e),recentEventCount:r,maxErrorsPerDay:s,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:M(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:M(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=_,_.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new _(v.PosixFile.for(e).join("events"))))))},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),s=i(38639),n=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function w(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function v(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function b(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function S(e){return!!((0,s.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||b(e))||void 0}t.isSqliteBusyError=w,t.isSqliteDisconnectedError=v,t.isSqliteConstraintError=b,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===S(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||w(e)||v(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=S;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),s=i(31586),n=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),s.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(n(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),s=i(19851),n=i(15197);t.ee=(0,s.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new n.CapturingEventEmitter(e)}))},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(73024)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(76760)),n=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),s=i(76760);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),w=f(i(1708)),v=i(46466),b=f(i(57975)),S=f(i(38522)),P=i(19851),M=i(40958),_=i(5233),T=i(22573),E=i(42659),D=i(50357),k=i(96249),x=i(98553),F=i(55835),C=i(31586),A=i(68708),I=i(97790),O=i(39926),L=i(51926),R=i(59455),N=i(54993),B=i(48884),j=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),q=i(76850),H=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Z=i(43334),Y=i(81168),X=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),se=i(89968),ne=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),we=i(27794),ve=i(73428),be=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const Se=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,T.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const s=(0,fe.resolve)(i),n=new Pe(s,t);return Se().set(i,n),Se().set(s,n),n}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Y.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,F.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,C.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,D.eql)(["."],e)||e.every(T.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,F.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,k.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,F.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,q.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,be.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,ve.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,ve.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,ve.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,ve.writeFileSync_)(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,A.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,we.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,we.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,Y.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,C.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),Me)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,F.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,C.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,n=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Y.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,F.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,v.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*E.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let Me=!0;t.useFsWatch=function(e){Me=e},t.execDir=function(){return Pe.for(w.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),s=i(88840),n=i(14036),a=i(29882);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,n.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),w=i(14427),v=i(17217),b=i(16287),S=i(68284);class P{constructor(e,t){this.base=e,(0,w.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,v.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},60652:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b,S,P,M,_,T=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},E=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryIterator=t.Undone=t.Done=void 0;const D=i(76760),k=i(19851),x=i(40958),F=i(22573),C=i(41400),A=i(57924),I=i(31586),O=i(68708),L=i(34666),R=i(13538),N=i(83104),B=i(12168),j=i(59455),z=i(48884),V=i(45255),W=i(81168),U=i(38836),q=i(98314),H=i(32144),G=i(28874),$=i(79915),J=i(59107),K=i(98604),Z=i(69385),Y=i(92423),X=i(29882),Q=i(62105),ee=i(74128);t.Done={done:!0},t.Undone={done:!1};class te extends U.EndableWrapper{constructor(e,i,s){super("dir.DirectoryIterator("+e+")",(()=>this.cancel({details:"DirectoryIterator was ended"}))),r.add(this),this.dir=e,this.ctx=i,this.parent=s,this.start=Date.now(),n.set(this,[]),a.set(this,[]),o.set(this,[]),l.set(this,[]),u.set(this,void 0),c.set(this,!1),d.set(this,0),h.set(this,0),f.set(this,0),m.set(this,0),p.set(this,0),this.rootDir=(0,k.lazy)((()=>this.parent?.rootDir()??this.dir)),this.pathFromRoot=(0,k.lazy)((()=>(0,X.posixPathFrom)({nativePath:this.rootDir().dir},this.dir))),this.nextTimeout=(0,k.lazy)((()=>G.Settings.statTimeoutMs.valueOrDefault+(0,I.clamp)(0,512,10*(512-this.depth())))),y.set(this,(0,k.lazy)((async()=>{const e=await(0,Y.whyExcludedDirectory)(this.dir)??(!this.isRoot&&await(0,J.isPosixMountpoint)(this.dir)?"nested mountpoint":void 0);if(null!=e)return this.logger.info("skipping ignorable dir, "+this.dir,{details:e}),await(this.ctx.onExcludedDirectory?.(this.dir,e)),this.cancel({state:ee.SyncDirStates.skipped,details:e}),t.Done}))),b.set(this,(0,k.lazy)((async()=>{const[e,t]=(0,z.partition)((0,j.toA)(await this.dir.children()),(e=>T(this,r,"m",v).call(this,e)));for(const t of e)(0,ee.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.skipped,details:"this was scanned in a prior incomplete sync"});T(this,l,"f").push(...t.filter((e=>e.isDirectory()))),E(this,m,T(this,l,"f").length,"f");const i=t.filter((e=>e.isFile())),[s,a]=(0,z.partition)(i,H.isSidecarExt);T(this,n,"f").push(...a),T(this,o,"f").push(...s),E(this,h,T(this,n,"f").length,"f")}))),(0,ee.syncReport)().onProgress({path:e.nativePath+D.sep,from:"DirectoryIterator",state:ee.SyncDirStates.scanning})}get isRoot(){return null==this.parent}isDone(){return this.ended||T(this,c,"f")}status(){return{root:this.rootDir().nativePath,path:this.pathFromRoot(),isDone:this.isDone()}}cancel(e){return T(this,c,"f")||(E(this,c,!0,"f"),(0,ee.syncReport)().onProgress({path:this.dir.nativePath+D.sep,from:"DirectoryIterator",state:ee.SyncDirStates.canceled,...e,elapsedMs:Date.now()-this.start})),t.Done}depth(){return(0,W.countChars)(this.dir.nativePath,D.sep)}async run(e=V.ShortCommandTimeoutMs){for(;!this.isDone();)await this.next(Date.now()+e),await(0,C.delay)(1)}async next(e){var i;const s=e-Date.now();try{this.logger.trace("next() starting",{runMs:s});const n=await(0,R.thenOrTimeout)(T(this,r,"m",g).call(this,e),this.nextTimeout());return this.logger.trace("next() finished",{result:n}),n===N.Timeout?(E(this,p,(i=T(this,p,"f"),++i),"f"),this.logger.warn(".next() timed out",{runMs:s,timeoutCount:T(this,p,"f")}),T(this,p,"f")>3?(this.logger.warn(".next(): too many timeouts, giving up on this directory."),this.cancel({state:ee.SyncDirStates.timeout,details:"Failed to scan, even after 3 retries"})):t.Undone):(E(this,p,0,"f"),n)}catch(e){return this.logger.warn("next() failed",{error:e}),this.cancel({state:ee.SyncDirStates.failed,details:"Error thrown during scan: "+(0,q.errorToS)(e)})}}}t.DirectoryIterator=te,s=te,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,y=new WeakMap,b=new WeakMap,r=new WeakSet,g=async function(e){return(T(this,c,"f")?t.Done:void 0)??await T(this,y,"f").call(this)??await T(this,b,"f").call(this)??await T(this,r,"m",S).call(this,e)??await T(this,r,"m",P).call(this,e)??await T(this,r,"m",M).call(this,e)??await T(this,r,"m",_).call(this)},w=function(e){return this.ended||!0===this.ctx.ended?.()?this.cancel({details:"DirectoryIterator was ended"}):T(this,c,"f")?t.Done:(0,Z.isPaused)()||Date.now()>e?t.Undone:void 0},v=function(e){return this.logger.tap({msg:"shouldSkipChild()",result:(0,x.isNotEmpty)(this.ctx.startAtNativePath)&&(0,L.cmpArr)((0,X.splitNativePath)(e.nativePath),this.ctx.startAtNativePath,!1)<=0,meta:{child:e.base}})},S=async function(e){var t;const i=[];let s;for(;null==s&&(0,x.isNotEmpty)(T(this,n,"f"))&&this.ctx.hasCapacity();){const a=T(this,n,"f").shift();E(this,d,(t=T(this,d,"f"),++t),"f");const o=await(0,Q.whyRejectFileSimple)(a);null!=o?(this.logger.debug("maybePopChildFile()",{child:a,whyReject:o}),await(this.ctx.onExcludedFile?.(a,o)),(0,ee.syncReport)().onProgress({path:a.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.rejected,details:o})):i.push(a),s??(s=T(this,r,"m",w).call(this,e)),null!=s&&this.logger.trace("maybePopChildFile() timeout",{timeout:s})}return(0,x.isNotEmpty)(i)&&(this.logger.trace("maybePopChildFile()",{toAdd:i}),await this.ctx.fileHandler(i),T(this,a,"f").push(...i)),s},P=async function(e){for(;(0,x.isNotEmpty)(T(this,o,"f"));){const t=T(this,o,"f").shift();if(G.Settings.tagAlbumFilenames.values.includes(t.base))(0,ee.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.note,details:"sidecar will be checked for for album metadata"});else{const e=T(this,a,"f").filter((e=>(0,$.isSidecarOf)(e,t)));(0,x.isNotEmpty)(e)?(0,ee.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.note,details:"sidecar will be processed with "+(0,A.andList)(e.map((e=>e.base.normalize())))}):(0,ee.syncReport)().onProgress({path:t.nativePath,from:"DirectoryIterator",state:ee.SyncFileStates.rejected,details:"sidecar will be ignored (no importable file was found to be relevant to this sidecar's name)"})}const i=T(this,r,"m",w).call(this,e);if(null!=i)return this.logger.trace("handleSidecars() timeout",{timeout:i}),i}},M=async function(e){var t;let i;for(;null==i&&(null!=T(this,u,"f")||(0,x.isNotEmpty)(T(this,l,"f")))&&this.ctx.hasCapacity();){if(null==T(this,u,"f")){const e=T(this,l,"f").shift();null==e||(this.logger.trace("delegating to child dir, "+e),E(this,f,(t=T(this,f,"f"),++t),"f"),E(this,u,new s(e,this.ctx,this),"f"))}if(null!=T(this,u,"f")){const t=await T(this,u,"f").next(e);(t?.done??!0===T(this,u,"f")?.isDone())&&E(this,u,void 0,"f")}i=T(this,r,"m",w).call(this,e)}return i},_=async function(){if((0,x.isNotEmpty)(T(this,n,"f"))||(0,x.isNotEmpty)(T(this,l,"f"))||null!=T(this,u,"f"))return this.logger.error("maybeCompleteResult: not done (?!)",(0,O.pick)(this,"result","pendingChildren","childDelegate","pendingChildDirs")),t.Undone;if(!T(this,c,"f")){E(this,c,!0,"f");const e=await(0,K.mkFolderUrl)(this.dir.nativePath),t=e?.with({query:null}),i=t?.toString(),r=0===T(this,h,"f")?"":`${T(this,d,"f")}/${(0,B.plur)(T(this,h,"f"),"file")}`,s=0===T(this,m,"f")?"":`${T(this,f,"f")}/${(0,B.plur)(T(this,m,"f"),"directory","directories")}`,n=(0,F.mapNotBlank)((0,A.andList)([r,s]),(e=>"Accepted "+e))??"No files or directories found";(0,ee.syncReport)().onProgress({path:this.dir.nativePath+D.sep,state:ee.SyncDirStates.scanned,from:"DirectoryIterator",details:n,url:i,elapsedMs:Date.now()-this.start}),await this.ctx.directoryListener(this.dir)}return t.Done}},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),w=i(54557),v=i(50213),b=i(88158),S=i(56519),P=i(46292),M=i(32551),_=i(35280),T=i(87290),E=i(96706),D=i(57902),k=i(43334),x=i(78984),F=i(33995),C=i(28874),A=i(21144),I=i(83278),O=i(48313),L=i(85772),R=i(78133),N=i(46356),B=i(17217),j=(0,u.lazy)((()=>(0,v.mkLogger)("fs.ExcludeGlobs"))),z=new w.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:C.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?D.LogLevels.debug:D.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((k.isWin?"*":"")+"/"+t.s+"/",t.desc));if(k.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}k.isLinux&&e.push(new U(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Z=(0,u.lazy)((()=>{C.Settings.excludeGlobsOmitDefaults.watchLater(J),C.Settings.excludeGlobsAdd.watchLater(J),C.Settings.excludeGlobsOmit.watchLater(J),C.Settings.globsCaseInsensitive.watchLater(J),C.Settings.libraryDir.watchLater(K),C.Settings.originalsDir.watchLater(K),C.Settings.scanPaths.watchLater(K),C.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ne,whyNoMedia:L.whyNoMedia,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ne}])),t.excludeGlobs=(0,u.lazy)((()=>{Z();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!C.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of C.Settings.excludeGlobsOmit.values)i(e);for(const e of C.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const Y=[{disableAllFilters:()=>!0}],X=[{notBlank:()=>!1}];function Q(e){return C.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?X:(0,t.excludeBundles)().file}function ee(e){return F.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return C.Settings.disableAllFilters.valueOrDefault?Y:(0,h.blank)(e)?X:(0,t.excludeBundles)().dir}async function ie(e){return C.Settings.disableAllFilters.valueOrDefault?void 0:x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ne(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,T.libraryDirPosixFile)(),(0,T.libraryOriginalsDirPosixFile)(),...C.Settings.argvScanPaths.values,...C.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,A.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ne},88561:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class w extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=w,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},79267:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const c=i(19851),d=i(40958),h=i(42659),f=i(31586),m=i(71371),p=i(50213),g=i(7282),y=i(409),w=i(78406),v=i(25764),b=i(99331),S=i(91655),P=i(34102),M=i(89968),_=i(85772);class T{static for(e){return new T(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,a,d=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=a,this.minRetained=d,s.set(this,void 0),this.intervalMs=(0,c.lazy)((()=>(0,f.clamp)((0,g.isTest)()?0:5*h.minuteMs,h.dayMs,this.staleMs/2))),n.set(this,void 0),this.cleanup=(0,y.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>u(this,r,"m",o).call(this)}),l(this,s,(0,p.mkLogger)("fs.FileCleanup("+e+")"),"f")}scheduleInterval(){return(null==u(this,n,"f")||u(this,n,"f").ended)&&l(this,n,new w.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:v.EndableRanks.first}),"f"),u(this,n,"f")}cancelInterval(){u(this,n,"f")?.end(),l(this,n,void 0,"f")}}t.FileCleanup=T,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(e){if(!(0,f.gt0)(this.minRetained))return new Set;const t=new m.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},o=async function(){try{if((0,b.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await M.DirectoryEntry.for(e);if(null==t)return[];u(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,S.fmtFullDuration)(this.staleMs," ")});const i=await u(this,r,"m",a).call(this,t),n=Date.now()-this.staleMs,o=new Set,l=[],c=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,_.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,f.gte)(e.mtimeMs(),n)))if(e.isDirectory())try{await e.rmdir_(),c.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(u(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,P.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&u(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),l.push(e.nativePath),o.add(e.dir)}catch(t){u(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const h=[...l,...c];return(0,d.isNotEmpty)(h)&&t.clear(),u(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:l.length,pruned_dir_count:c.length}),h}catch(e){return void u(this,s,"f").error("cleanup() failed",{error:e})}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,n.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),s=i(17217),n=i(16287),a=i(68284);async function o(e){return(0,r.pick)(await(0,n.stat_)((0,s.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,s.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),s=i(19851),n=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,s.set(this,[]),n.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,n,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,s,"f").push(e)}close(){u(this,n,"f").close()}}t.FileWatcher=m,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,s,"f"))t(e,this.nativePath)}}},13829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(55835),s=i(13538),n=i(81168),a=i(37628),o=i(46292),l=i(73209),u=i(95696);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},73209:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const M=i(58587),_=P(i(44652)),T=i(87997),E=i(40958),D=i(17586),k=i(42659),x=i(50357),F=i(75240),C=i(55835),A=i(31586),I=i(30976),O=i(13538),L=i(54993),R=i(7282),N=i(68852),B=i(23560),j=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),q=i(55222),H=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,s,Math.max(Date.now(),b(this,s,"f",n)+1),"f",n),(0,E.compactBlanks)([q.TokenRadix.encode(b(this,s,"f",n)),B.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,A.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return b(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>b(this,r,"m",v).call(this)),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=s,s,(i=b(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(b(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await b(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+b(this,l,"f")),this.staleMs=(0,A.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),b(s,s,"f",o).push(this)}get acquired(){return b(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await b(this,r,"m",f).call(this,e)??b(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,D.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,x.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==b(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:k.secondMs);S(this,c,setInterval((()=>b(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=b(this,c,"f")&&(clearInterval(b(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(b(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),S(this,u,!1,"f"),(0,C.map)(b(this,d,"f"),(e=>(0,T.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?b(this,r,"m",w).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>b(this,r,"m",w).call(this)),(0,A.toGt0)(this.staleMs)??k.secondMs),"f"),b(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(b(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,A.gt0)(this.staleMs)&&Date.now()>b(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await b(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await b(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,A.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+k.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,A.gt0)(t)&&!(0,M.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),b(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await b(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},w=async function(){await b(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},v=function(){(0,E.filterInPlace)(b(s,s,"f",o),(e=>b(e,l,"f")!==b(this,l,"f")))},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),s=i(51926),n=i(54993),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(73024)),n=i(57075),a=i(46466),o=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44652)),n=r(i(73024)),a=i(46466),o=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),w=i(16287),v=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return v().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;v().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(n.default.createReadStream(i)),stats:(0,u.pick)(await(0,w.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),s=i(42659),n=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),s=i(54993),n=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,n.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,n.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,n.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,n.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(51926),n=i(54993);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(76760)),n=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},61704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(21144),s=i(17217);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=n(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),w=i(83278),v=i(70698),b=i(88561),S=i(65238),P=i(16287),M=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),_="NoMedia",T=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+_+"$","im"),E=Object.freeze(["."+_,_]),D=Object.freeze((0,u.flatten)(E.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function k(e){return null!=T.exec(e)}t.isNoMediaName=k;const x=(0,o.lazy)((()=>new b.FileCache({name:"fs.noMediaDirsCache"})));async function F(e,t){if(null==e)return null;const i=w.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return k(i.base)||await(0,v.isCachedirTagFile)(i)?x().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):F(i.parent());{const e=await x().getOrSetAsync(i.nativePath,(()=>C(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:F(i.parent())}}async function C(e){if(k(e.base))return x().set(e.parent().nativePath,e.nativePath),M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,S.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([A(e.nativePath,i),(0,S.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,v.isCachedirTagDirectory)(e)?M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(v.CACHEDIR_TAG).nativePath)}):null}async function A(e,t){for(const i of g.isCaseSensitiveFs?D:E){if(!0===t?.aborted)return null;const r=a.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return M().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(k(r.basename))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,r.basename))});if(r.basename===v.CACHEDIR_TAG){const t=(0,a.join)(e,r.basename);if(await(0,v.isCachedirTagFile)(t))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await F(e,t)},t.whyNoMedia=F,t.whyNoMediaDir=C,t._dirHasNoMediaChild=A},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),w=i(78133),v=i(53265),b=i(17217),S=i(16287),P=i(66430),M=i(5545);function _(e){return((0,b.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return F(e).some(_)},t.isNotHiddenPosixPath=function(e){return F(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,b.isSimpleFile)(e)?e.nativePath:(0,v.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,v.resolve)(...e)},t.parsePosixPath=function(e){return E((0,w.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return n.default.dirname((0,b.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const T=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=T.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function D(e){const t=n.default.parse((0,b.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,n.default.sep)}function k(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,b.toNativePath_)(e.ancestor),i=(0,b.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function x(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(y.isLinux?r===s:(0,p.equalsIgnoreCase)(r,s))}function F(e){return(0,b.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function C(e){return(0,u.notBlank)(e)&&F(e).length===(y.isWin?1:0)}function A({p:e,maxLength:t}){const i=(0,b.toNativePath_)(e);if(i.length<=t)return i;const r=F(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),O([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),O([...s,...n])}function I(e){return e.startsWith("\\\\")}function O(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),y.isWin?"":n.default.sep)}t.parseNativePath=E,t.parentBasename=D,t.grandParentBasename=function(e){return D(n.default.parse((0,b.toNativePath_)(e)).dir)},t.containedByNativePath=k,t.eqlBasename=function(e,t){return x(b.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return x(b.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return x(b.toNativePath_,e,t)},t.toPathnames=F,t.pathIsRoot=C,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:F(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,b.toNativePath_)(e),r=(0,b.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,w.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,w.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=A,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(A({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return F(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return F(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(M.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;if(C(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await s.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,b.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>k({ancestor:t,descendant:e,acceptSelf:!0})?[(0,b.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),w=i(64660),v=i(21144),b=i(16287),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,w.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function T(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...T(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await M(i))return y.isLinux?i:(0,v.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,w.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),w=i(76790),v=i(5233),b=i(22573),S=i(42659),P=i(26905),M=i(75240),_=i(55835),T=i(31586),E=i(68708),D=i(13538),k=i(89937),x=i(12168),F=i(54993),C=i(48884),A=i(50213),I=i(45255),O=i(81168),L=i(56519),R=i(56038),N=i(31562),B=i(84777),j=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),q=i(43334),H=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Z=i(34238),Y=i(87001),X=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),se=i(73209),ne=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,C.contextFilter)(function(e){return(0,w.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,A.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,X.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),r=new fe(i,t);return(0,O.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,X.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,F.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===k.PS_LIBRARY_SCHEME?1:t.scheme===k.PS_LOCAL_FILE_SCHEME?2:t.scheme===k.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,C.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,v.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,T.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,D.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,T.clamp)(I.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,Y.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,T.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),w=i(83278),v=i(19748),b=i(92423),S=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):null}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function T(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function D(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function k(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function F(e){return(0,w.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function C(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function A(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function I(e){return[{isSupportedFileExtension:v.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:F},{notFileTooSmall:C,notFileTooBig:A}]}function O(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:T},{notRejectedRating:D},{notExcludedKeyword:k}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=F,t.notFileTooSmall=C,t.notFileTooBig=A,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(76760)),n=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(s.default.join((0,p.execDir)(),"resources"),s.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=s.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),s=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),s=i(84542);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(51455)),n=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),w=i(28874),v=i(63870),b=i(88561),S=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(w.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function M(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=M;const _=(0,a.lazy)((()=>new b.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,v.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function T(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function E(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=D(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(w.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(s===f.Timeout&&(0,g.onTimeout)({soft:!1}),s!==f.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=T,(0,c.later)((()=>{w.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),M()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?M():T(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){T(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(w.Settings.readdirCacheMs.valueOrDefault)?E(e):D(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=D},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const s=i(73024),n=r(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=n.default.resolve(t,...e);if((0,s.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??n.default.resolve(...e))},t.execDir=(0,l.defer)((()=>n.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(22454),s=i(28874),n=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),s=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const s=r(i(73024)),n=r(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function w(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,g.statTimeoutMs)(),!0)}function v(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:w(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function S(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(S(r),S(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}t.stat_=w,t.statMaybe=v,t.statToType=b,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await v(e,t)},t.isEmptyFile=async function(e,t){const i=await v(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await v(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await v(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await v(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await v(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await v(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await v(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),s=i(56409);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(57075)),n=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),w=i(19851),v=i(40958),b=i(22573),S=i(42659),P=i(98553),M=i(31586),_=i(68708),T=i(50989),E=i(51926),D=i(85556),k=i(54993),x=i(89788),F=i(23467),C=i(7282),A=i(23560),I=i(77377),O=i(71567),L=i(73568),R=i(25764),N=i(38836),B=i(99331),j=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),q=i(5012),H=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Z=i(84542),Y=i(73428);t.AssetFileSyncStates=(0,T.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,T.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,T.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,T.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const X={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,_.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,T.strEnum)(...(0,_.keys)(new class{constructor(e,t,i,r,s,n,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,w.lazy)((()=>(0,Y.writeTextfile_)(re().nativePath,(0,E.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(X)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=S.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,H.isCsvExt)(e)&&(0,M.gte)(e.mtimeMs(),t)))},t.syncReport=(0,w.lazy)((()=>new se));class se extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new x.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,s,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,b.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,q.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,k.toS)(e.path),state:e.state,details:(0,k.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:t,at:new Date(t).toISOString(),...i,...(0,_.pick)(e,"from","elapsedMs","url")};(0,_.isEmptyObj)(e.meta)||(s.meta=(0,P.stringify)(e.meta)),(0,C.isTest)()&&process.stdout.write((0,P.stringify)(e)+Z.Newline),f(this,r,"m",u).call(this,s)}}maybeSystemData(e){(0,A.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:n}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,B.ending)()||r instanceof L.AbortError?t.SyncFileStates.canceled:r instanceof D.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return f(this,n,"f")??f(this,r,"m",h).call(this)}async flushClose(){return f(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,n,"f");return m(this,n,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,s,"f")}}t.SyncReport=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,F.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,r,"m",c).call(this,i):(f(this,r,"m",c).call(this,{...i,details:(0,v.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Z.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,s,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,j.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,s,"f").nativePath),this.logger.info("Opening new report: "+f(this,s,"f")),(0,C.isTest)()&&(0,O.stdoutWrite)({syncReport:f(this,s,"f").nativePath},!1),m(this,n,(0,g.createWriteStream)(f(this,s,"f").nativePath),"f"),f(this,n,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Z.Newline),f(this,n,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(48161)),n=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44652)),n=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},79847:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkFileUri=t.trashOrUnlinkFileUris_=void 0;const o=n(i(51455)),l=a(i(49378)),u=i(40958),c=i(22573),d=i(13538),h=i(83104),f=i(45255),m=i(31562),p=i(98314),g=i(34102),y=i(28874),w=i(45200),v=i(63870),b=i(16287),S=i(74128),P=i(84258),M="fs.Trash";async function _(e){const t=Date.now(),i=(0,v.commandTimeoutMs)(),r=(0,c.toNotBlank)(e.nativePath)??await(0,d.thenOrTimeout)((0,w.uri2nativePath)(e.uri,e.mountpoint),i);if((0,c.blank)(r)||r===h.Timeout)return(0,S.syncReport)().onProgress({from:M,state:"failed",details:"Could not convert URI to native path",path:e.uri,elapsedMs:Date.now()-t}),{uri:e.uri,unlinked:!1};const s=await(0,b.statMaybe)(r);if(null==s)return(0,S.syncReport)().onProgress({from:M,state:"noop",details:"Failed to delete: no such file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(!s.isFile())return(0,S.syncReport)().onProgress({from:M,state:"noop",details:"Failed to delete: not a file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(y.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,d.thenOrTimeoutError)((0,l.default)(r,{glob:!1}),i),await function(e){return(0,m.untilTrue)((async()=>null==await(0,b.statMaybe)(e)),{timeoutMs:f.ShortCommandTimeoutMs})}(r))return(0,S.syncReport)().onProgress({from:M,state:"deleted",details:"Moved file to trash",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0};(0,P.logger)().warn("soft-delete("+r+") didn't seem to work: the file is still there?")}catch(e){(0,S.syncReport)().onProgress({from:M,state:"note",details:"Failed to soft-delete file to trash: "+(0,p.errorToS)(e),path:r,elapsedMs:Date.now()-t}),(0,P.logger)().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}try{return await(0,d.thenOrTimeoutError)(o.unlink(r),i),(0,g.ee)().emit("fileChanged",r),(0,P.logger)().info("unlink("+r+") successful"),(0,S.syncReport)().onProgress({from:M,state:"deleted",details:"Permanently deleted file",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0}}catch(i){return(0,S.syncReport)().onProgress({from:M,state:"failed",details:"Could not move file to trash or delete: "+(0,p.errorToS)(i),path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!1}}}t.trashOrUnlinkFileUris_=async function(e){const t=[];for(const{uri:i,mountpoint:r}of(0,u.uniqBy)(e,(e=>e.uri)))try{t.push(await _({uri:i,mountpoint:r}))}catch(e){t.push({uri:i,unlinked:!1,error:e})}return t},t.trashOrUnlinkFileUri=_},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),s=i(41400),n=i(55835),a=i(92782),o=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),h=i(87128),f=i(95696);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=n(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await a.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(76760)),n=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),w=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function v(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=v,t.zcat=async function(e,t){try{return v(e,t)}catch(t){return void w().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void w().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){w().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},63664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const r=i(22573),s=i(45599),n=i(41400),a=i(50268),o=i(98553),l=i(50213),u=i(23560),c=i(45255),d=i(5916),h=i(28874),f=i(34238),m=i(51140),p=i(4988),g=i(18454),y=(0,s.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({desc:"health.getRemoteHealthSummary",later:async()=>{try{if((0,u.isWebService)())return;const e=await(0,p.get_)(f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}),{timeoutMs:c.ShortCommandTimeoutMs}),t=(0,o.parseJSON_)(e.data);if(m.HttpStatusIs.ok(e.statusCode)&&(0,a.isHealthCheckSummary)(t))return"ready"===t.state&&(0,r.toNotBlank)(t.libraryDir)!==(0,r.toNotBlank)(h.Settings.libraryDir.valueOrDefault)&&(y().error("getHealthSummary(): libraryDir mismatch! Switching to that library directory...",{local:h.Settings.libraryDir.valueOrDefault,remote:t.libraryDir}),h.Settings.libraryDir.value=t.libraryDir),y().debug("getHealthSummary()",{response:e}),t;y().warn("getHealthSummary(): invalid response",{response:e})}catch(e){y().warn("Failed to get health check summary from web service",{error:e})}}}),t.getLocalHealthSummary=(0,d.lazyAsync)({desc:"health.getLocalHealthSummary",later:()=>g.HealthCheck.awaitSettled()}),(0,n.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},87408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(63870),s=i(18454),n=i(89035),a=i(82638);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...s.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:s.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},18454:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,w,v,b,S,P,M=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},_=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const T=i(19851),E=i(40958),D=i(76790),k=i(22573),x=i(41400),F=i(50357),C=i(26905),A=i(50268),I=i(55835),O=i(68708),L=i(30976),R=i(51926),N=i(13538),B=i(42279),j=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),q=i(50213),H=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Z=i(77740),Y=i(98314),X=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),se=i(21525),ne=i(82638),ae=(0,T.lazy)((()=>(0,q.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{M(this,s,"f",l).push(e+": failed: "+(0,Y.errorToS)(t)),this.onResultChange()})),M(this,s,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return M(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){M(this,s,"f",l).push((0,R.isString)(e)?e:(0,Y.errorToS)(e)),this.onResultChange()}static lastErrors(){return M(this,s,"f",l).toA()}static addLoadingMsg(e){M(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,E.compact)((0,j.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:M(this,s,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[M(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=M(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>M(this,s,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return M(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,A.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=M(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=s.summary();if(e.pendingCount>0){const t=await Promise.all(s.testResultsCritical());e=s.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){s.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,C.shortStack)());else{this.onResultChange(),M(this,s,"f",l).clear(),M(this,s,"f",d).clear(),M(this,s,"f",h).clear(),M(this,s,"f",c).clear(),this.summary.clear(),_(this,s,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new s(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return M(this,s,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,n,o,l,u,c,d,h,f,m,S,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=n,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=S,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),v.set(this,(0,T.lazy)((async()=>{await M(this,p,"f").prior(),(0,F.eql)(M(this,g,"f"),M(this,r,"m",w).call(this))||(this.onReset?.(),await this.refresh(),M(this,v,"f").unset())}))),this.refresh=(0,T.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await M(this,p,"f").prior();const e=M(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,q.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[A.HealthCheckSections.ordinal(this.section),l??999,this.id],_(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>M(s,s,"f",a).enqueue({name:this.id,l:()=>M(this,r,"m",b).call(this,o)}),ttlMs:S}),"f"),this.isCritical&&M(this,p,"f").watchLater({onChange:s.onCriticalResult,onError:s.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>M(this,v,"f").call(this)))}isStale(){return M(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return M(this,p,"f").settledCount()}reset(){return M(this,p,"f").unset(),this.onReset?.(),_(this,g,{starting:!0},"f"),this}setTTL(e){M(this,p,"f").setTTL(e)}result(){return M(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return M(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return M(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??M(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,E.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,E.isNotEmpty)(i)&&(r.links=(0,E.uniqBy)(i)),(0,E.isNotEmpty)(t)&&(r.buttons=(0,E.uniqBy)(t)),r}t.HealthCheck=oe,s=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,v=new WeakMap,r=new WeakSet,o=function(){return(0,E.filterInPlace)(M(this,s,"f",n),(e=>!e.isPending)),M(this,s,"f",n)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,ne.summarizeHealthChecksSync)({errors:M(this,s,"f",l),skipPending:M(this,s,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&_(this,s,!0,"f",u),i.state!==M(this,s,"f",c).last?.state&&M(this,s,"f",c).push({state:i.state,ts:Date.now()}),i},w=function(){return(0,O.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},b=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,C.shortStack)()}),_(this,g,M(this,r,"m",w).call(this),"f");try{if((0,Z.getDevEnvFlag)("PS_SLOMO")&&await(0,x.delay)((0,L.randomInt)(.3*i,.7*i)),this.isSkipped())return M(this,r,"m",S).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const s=await(0,N.thenOrTimeoutError)(e(),i);return M(this,r,"m",S).call(this,{test:s,elapsedMs:Date.now()-t})}catch(e){return M(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},S=function({test:e,src:t="#toResult",elapsedMs:i}){var r,n;const a=s.normalizeMsg(e.msg),o=e.level??((0,z.toS)(a).toLowerCase().includes("error")?"error":(0,z.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,E.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(_(this,y,(n=M(this,y,"f"),r=n++,n),"f"),r),(0,$.ending)()?u:this.logger.tap({level:se.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const s=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,k.toNotBlank)((0,Y.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,X.isFatalError)(e)&&s.toLowerCase().includes("warn")?"warn":"error"),M(this,r,"m",S).call(this,{test:{msg:s,level:t},src:"#toErrorResult",elapsedMs:i})},n={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new U.CountingSet},f={value:[]},oe.all=(0,T.lazy)((()=>Object.freeze((0,D.sortBy)(M(s,s,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,H.debounce)((()=>{ae().info("onCriticalResult()",s.summary.refresh())}),250),oe.summary=(0,T.lazy)((()=>M(s,s,"m",m).call(s))),oe.resetDebounced=(0,H.debounce)((()=>s.reset()),50)},85021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function w({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await w(e)})};const v=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...v(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...v(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...v(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>v.unset()))})),t.summarizeHealthChecksSync=b},95242:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),w=i(57159),v=i(83278),b=i(95696),S=i(62105),P=i(84258),M=i(38156),_=i(69589),T=i(28874),E=i(47783),D=i(29990),k=i(16047),x=i(42725),F=i(4192),C=i(32876),A=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class O{constructor(e,t,i){r.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,_.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(r=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,S.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await n(this,r,"m",s).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:n,height:a,sha:l,mimetype:u}=t;if(null==s||null==n||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,D.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:n,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(x.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,D.equivalentFitSizes)(r,s)){const n=(0,D.fitSizes)(e,e.mimetype),a=(0,o.diff)(r,s);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=n.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:n});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=O,s=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new M.PushProgressObserver({path:e.nativePath,op:"Building previews"},x.ImageSize.sq().length+x.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,A.sharpReadable_)({src:e,minDim:x.ImageSize.largestFit().max});if(null==a)throw new w.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,A.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,k.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,v.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,D.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=x.ImageSize.largestSq(),b=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,h.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of l){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&r.reducer===C.Fit&&T.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of x.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=T.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(r)+" -> "+(0,u.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,F.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new w.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),w=i(70417),v=i(35721);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,v.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,v.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,w.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,v.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},33106:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(9288)),n=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(e);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(40958),s=i(33374),n=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),w=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function v(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){w().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void w().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=v(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void w().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=v,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void w().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),s=i(54993),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),s=i(19851),n=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),w=i(55222),v=i(63870),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+w.TokenRadix.randomChars(2),w.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,v.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(9288)),n=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),w=i(88561),v=i(95696),b=i(17217),S=i(50213),P=i(23624),M=i(28874),_=i(12089),T=i(16170),E=i(1078),D=i(33106),k=i(86580),x=i(78011),F=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const C=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void C().warn("imageHash() failed for "+e,t)}};const A=(0,n.lazy)((()=>new w.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=v.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,k.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),n=await(0,F.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,k.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,F.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,F.toSharp)(t).removeAlpha();(0,T.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),w=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),v=await(p?D.dctHash:D.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(w.meanHash),diffHash:(0,P.b64encodeBits)(w.diffHash),dctHash:(0,P.b64encodeBits)(v),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,T.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:A,impl:I}),t._imageHash_=I,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},80361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(33374),l=i(57924),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(21605),m=i(48884),p=i(50213),g=i(97352),y=i(85810),w=i(3048),v=i(32848),b=i(82647),S=i(38812),P=i(70417),M=i(23624),_=i(28874),T=i(86580),E=i(48368),D=i(2090),k=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,w.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,w.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function F(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function C(e,t,i=E.HashDim){const r=(0,M.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function A({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=C(e,i,r),l=C(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));k().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function I(e,t,i="debug",r={}){return k().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??F(r.meanHash))||(s.isGreyscale??F(s.meanHash))),f=A({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,T.validRotations)(r,s)}),m=A({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=A({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,v.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void k().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,w=(0,T.aspectRatio)(r),S=(0,T.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=w&&null!=S&&!(0,o.isCloseAspectRatio)(w,S);let M=0,x=0;n&&(x+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault,M+=_.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,M+=_.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(M+=_.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=_.Settings.imageHashGreyscaleDelta.valueOrDefault);const C=R((M+(i.minImageCorr??_.Settings.minImageCoeffPct.valueOrDefault))/100),I=R((x+(i.minColorCorr??_.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,D.fmtAspectRatio)(w)} vs ${(0,D.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,C)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,C)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=I,z=j&&N.avg>=C;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:C,imageCoeffDelta:M,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:I,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:w,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return k().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=F,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=C(e,t,i);return f.Rotations.map((e=>(0,M.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=A,t.isSimilarImage=I,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return I(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},42725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},4192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},78011:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(9288)),n=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},52121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const r=i(19851),s=i(78923),n=i(95696),a=i(50213),o=i(28874),l=i(12089),u=i(16170),c=i(13940),d=i(4192),h=i(5733),f=i(50961),m=(0,r.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=n.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,s.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},48604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),s=i(31586),n=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(9288)),n=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,n.lazy)((()=>{s.default.simd(l.Settings.enableSIMD.valueOrDefault),s.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),s.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(77988),n=r(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),w=i(56519),v=i(56038),b=i(57159),S=i(95696),P=i(17217),M=i(28874),_=i(47783),T=i(16170),E=i(95141),D=i(54979),k=i(1078),x=i(63870),F=i(86580),C=i(277),A=i(16047),I=i(13940),O=i(5733),L=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await z(e,t))?.nativePath}async function j(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=j,t.toSharp=function(e){const t=e;if((0,O.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,v.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=N().addParameterContext(e.nativePath);(0,O.setupSharp)();const n=await(0,D.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,k.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,T.isVideoMimeType)(n),S=(0,T.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const I=(0,F.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),z=(0,T.isSharpMimeType)(n)&&null==t,V=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||z||V)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:z,isMirrorOrientation:V});else{const i=!1,n=await(0,_.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>j(e,n,t,x,I)))}}}(0,T.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,A.isHeifMimeType)(n)&&await(0,C.isHeifSupported)()&&f("heif",(()=>(0,w.thenMap)((0,C.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,w.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,L.isVideoSupported)())try{return await(0,w.thenMap)((0,L.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,v.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=z},21473:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=void 0;const s=r(i(34589)),n=i(76760),a=r(i(9288)),o=i(50357),l=i(98553),u=i(68708),c=i(23560),d=i(43899),h=i(28874),f=i(5733);t.testSharp_=async function e(t){try{(0,f.setupSharp)();const e=t??(0,n.join)(d.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(e,{failOn:"error"}),r=await i.resize(24,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,o.eql)((0,u.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:24,height:32,channels:3}),"Unexpected sharp output: "+(0,l.stringify)(r.info))}catch(i){if(!(0,c.isWorkerService)()&&h.Settings.enableSIMD.valueOrDefault)return h.Settings.enableSIMD.envValue=!1,e(t);throw i}}},181:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(9288)),n=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),w=i(54979),v=i(63870),b=i(5733),S=i(50961),P=i(66106),M=i(51210),_=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&_().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const T=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,v.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return T().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:T,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,w.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),w=i(56038),v=i(31562),b=i(98314),S=i(34102),P=i(88561),M=i(95696),_=i(17217),T=i(74128),E=i(31843),D=i(70417),k=i(33847),x=i(28874),F=i(94678),C=i(43207),A=i(47783),I=i(16170),O=i(95141),L=i(1078),R=i(63870),N=i(89782),B=i(13940),j=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,j.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,E.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function q(e){return await(0,t.isVideoSupported)()?M.PosixFile.for(await(0,t._extractVideoFrame_)((0,_.toNativePath_)(e))):void 0}async function H(e,t){const i=V("extractVideoFrame",e),r=M.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,j.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,B.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,A.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,N.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,C.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,j.ffmpegFrame_)(t),!1===await(0,v.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,A.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,j.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,A.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,C.extractDurationSec)(i);if(!(0,c.gt)(n,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=q,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await G())return;const n=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,A.readTags)(e),h=(0,L.extractSizeInfoFromTags)(d),m=(0,C.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,A.readRawTags)(t),r=await(0,A.readRawTags)(e),s=(0,C.extractDurationSec)(r),n=(0,C.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),s=x.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,F.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,w.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new k.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:r.halt,...g},m=x.Settings.transcodeMaxDim.valueOrDefault,p=(0,D.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,j.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-n})}catch(t){throw(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:Date.now()-n}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await q(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,j.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),w=i(84258),v=i(28874),b=i(76280),S=i(63870),P=i(19769),M=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function _(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:v.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=_;const T=/ffmpeg version n?(?\S+)/i,E=(0,u.lazy)((async()=>{const e=await _();if(null==e)return void M().info("failed to find ffmpeg in $PATH",{ffmpegPath:v.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=T.exec(t.result)?.[1];return M().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function D(){E.unset(),t.ffmpegVersionDescription.unset()}function k(e){const t=e?.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function x(e){const t=[...v.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(v.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function F(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function C(e){const t=v.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(E(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",D),(0,g.ee)().on("clearToolCache",D)})),t.ffmpegVersion_=async function(){return await E.prior()??E.refresh()},t.isFFmpegSupported=async function(){return null!=await E()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=x,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...x(t),...C(t),...k(t),"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...F(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){M().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,w.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return M().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return M().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await _(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(19851),s=i(42659),n=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),w=i(89782),v=i(13940),b=i(42725),S=i(19769),P=(0,r.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,v.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>D(e,t)})};const M=["-T"],_=["-Z","-"],T=["-o","1"],E=["-t","0","-j"];async function D(e,t){const i=await(0,w.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=b.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[...M,..._,...T,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],v={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:v});const D=(0,c.execFile)(g,y,void 0,v),k=[];function x(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});k.push(r)}}if(D.on("error",x),D.stderr.on("data",x),await t.writeStream_(D.stdout),(0,s.isNotEmpty)(k))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:k,path:e.nativePath});(0,c.endProcess)(D)}t.dcraw_emu_=D},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},42042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(22573),s=i(28874),n=i(81674);t.getEmail=async function(){const e=s.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),w=i(50213),v=i(56519),b=i(76596),S=i(46292),P=i(87290),M=i(77740),_=i(34102),T=i(83278),E=i(28874),D=i(37692),k=i(71706),x=i(83950),F=i(72042),C=i(33603),A=i(48132);t.k=(0,y.rolazy)((()=>(0,k.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,w.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,F.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function L(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:x.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,C.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,v.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await L((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,A.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function B(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=L,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await L(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof x.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,M.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,C.sids)({timeoutMs:A.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),(e=>T.BaseFile.for(e))),s=(n=(0,l.flatten)((await(0,v.someOrTimeout)([()=>function(e){return L(E.Settings[(0,t.k)().L].value,"Settings",A.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:A.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,f.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l))),(e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,o.later)((()=>{(0,_.ee)().on("clearCache",(()=>t.m.unset())),(0,_.ee)().on((0,t.k)().c,(()=>t.m.unset())),D.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=B,t.l=async function(){try{return await B()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await B()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},84194:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(40958),a=i(76790),o=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),h=i(19851),f=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function w(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=w,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(w(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const v=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||v.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=w(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==w(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(45599),o=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),h=i(50213),f=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),w=i(45879),v=i(70854),b=i(57902),S=i(72308),P=i(43334),M=i(24399),_=i(7014),T=i(30933),E=i(71706),D=i(84194);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const k=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const F=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,D.toUID)(D.S.lc,e.join(",")))))),C=/o\.e\.m\./i;async function A(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,w.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(C)))}async function I(){return P.isLinux?(await A("lm")).map((e=>(0,D.toUID)(D.S.lm,e))):void 0}async function O(){return P.isLinux?(await A("lp")).map((e=>(0,D.toUID)(D.S.lp,e))):void 0}async function L(){return P.isLinux?(await A("lb")).map((e=>(0,D.toUID)(D.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,D.toUID)(e,t)))}catch(e){return void k().warn((0,t.k)().i+" failed",e)}}async function N(){return(await M.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,D.toUID)(D.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,D.toUID)(D.S.cm,(0,T.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,D.toUID)(D.S.bm,(0,r.compactBlanks)(await A("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,D.toUID)(D.S.li,await((0,v.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,D.toUID)(D.S.si,await((0,v.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,D.toUID)(D.S.nm,e)))}async function q(){return(0,c.toA)(await(0,_.volumes)()).map((e=>(0,D.toUID)(D.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,F,R,V,W,z,I,O,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return k().tap({msg:"sids()",result:(0,D.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,f.isTest)())for(const t of e)H.add(t)},t.clearSids=function(){(0,f.isTest)()&&H.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},34474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(40958),s=i(42659),n=i(41400),a=i(96249),o=i(68708),l=i(34666),u=i(20214),c=i(71371),d=i(50213),h=i(42638),f=i(31562),m=i(98314),p=i(89968),g=i(28874),y=i(4904),w=i(57902),v=i(89241),b=i(83954);function S(e=10*s.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(w.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-s.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new v.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*s.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-s.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),s=i(23560),n=i(66184),a=i(72210);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),s=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function w(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...w(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),w=i(31256),v=i(28538),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new w.GelfLogFormatter,this.logFilter=new v.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),s=i(42659),n=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},12495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(19851),s=i(42659),n=i(23560),a=i(79267),o=i(32144),l=i(28874);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isLogExt)(e.ext)})))},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),s=i(31586),n=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),s=i(57902);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,s.set(this,[]),n.set(this,(0,l.lazy)((()=>{o(this,s,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,s,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,n,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,r,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,r,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){if(null==e||0===o(this,s,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,s,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),s=i(50989),n=i(28874);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=n.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},89241:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),h=i(38522),f=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),w=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),s.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,s,!0,"f")})),this.stream.on("end",(()=>{u(this,s,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,s,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,s,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,s,!0,"f");else{const t=(0,w.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),s=i(76760),n=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),w=i(22277),v=i(25764),b=i(38836),S=i(99331),P=i(42638),M=i(76596),_=i(98314),T=i(89968),E=i(29882),D=i(28874),k=i(28981),x=i(20839),F=i(21727),C=i(66184),A=i(57902),I=i(72210),O=i(98192);function L(e){const t=(0,k.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),v.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new w.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,D.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await T.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,C.ifLog)(A.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,_.errorToS)(t))))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,F.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,_.errorToS)(e))))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await T.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,C.ifLog)(A.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),s=i(82328),n=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),w=i(31586),v=i(409),b=i(23560),S=i(81168),P=i(78406),M=i(25764),_=i(20197),T=i(14977),E=i(36868),D=i(28874),k=i(32105),x=i(20839),F=i(21727),C=i(66184),A=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:M.EndableRanks.logger,unref:!0,onEnd:()=>c(this,s,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:k.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:C.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,v.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,A.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,w.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,F.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),D.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,T.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),s=i(84542),n=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),s=i(76790),n=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),s=i(41400),n=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),w=i(66184),v=i(28538),b=i(24068),S=i(43705),P=i(51879);function M(){(0,w.logFilter)()instanceof v.LogFilterImpl||w.logFilter.set(new v.LogFilterImpl),_();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new S.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,n.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&b.LogTail.instance()}function _(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=M,t.setupLogFormatter=_,(0,s.later)((()=>{h.Settings.logStdout.watchLater(M),h.Settings.logDir.watchLater(M),h.Settings.tailLogs.watchLater(M),h.Settings.logColor.watchLater(_),h.Settings.logLevel.watchLater((()=>w.defaultLogLevel.unset()))}))},83954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(89179);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},82647:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p69(){return n(this,r,"m",s).call(this,.5)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,s=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},76752:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtEstimate=t.ETA=void 0;const r=i(42659),s=i(75240),n=i(31586),a=i(97352),o=i(82647);function l(e){return(0,n.gt0)(e)?e<=r.minuteMs?"less than a minute remains":"about "+(0,s.fmtDuration)(e,1,{plural:"remains",singular:"remain"}):void 0}t.ETA=class{constructor(){this.taskMillis=new o.Average(10)}push(e){(0,a.mapGt0)(e,(e=>this.taskMillis.push(e)))}clear(){this.taskMillis.clear()}avg(){return this.taskMillis.p69}etaMs(e){const t=this.avg();if(null==t)return;const i=t*e;return i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(76790),s=i(93973);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},36372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(76790),s=i(42659),n=i(31586),a=i(97238),o=i(50597),l=i(9103),u=i(55222);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},38812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(21605);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}×${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),s=i(65713);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function w(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=w;class v{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new v;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=w(t,((t,r)=>(t-i)*(r-e))),s=w(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(38522),s=i(22573),n=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(48161)),n=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),w=i(34102),v=i(26293),b=new RegExp("^"+v.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==b.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=S.exec(e)}function M(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=M,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=M(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const _=(0,s.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,w.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=M(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),s=i(19851),n=i(54993);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(22573),s=i(51926),n=i(83556);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),s=i(59455),n=i(31562);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),w=i(97790),v=i(59455),b=i(54993),S=i(54557),P=i(19851),M=i(50213),_=i(88158),T=i(409),E=i(78406),D=i(25764),k=i(99331),x=i(56519),F=i(46292),C=i(8769),A=i(83278),I=i(32144),O=i(29882),L=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,M.mkLogger)("proc.Pids"))),j=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,O.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,v.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,T.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??L.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,f.isEmpty)(s))return B().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,N.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){B().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!z(r,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:r}),a.push(W(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,C.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,s,"f").delete(l),o(this,s,"f").getOrSet(l,(async()=>{const i=o(this,r,"m",n).call(this,e.pid),s=(0,w.opt)((0,_.Try)((()=>(0,O.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:s,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,s,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,v.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,r,"m",n).call(this,e);return(0,x.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new E.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:D.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=U,s=new WeakMap,a=new WeakMap,r=new WeakSet,n=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,F.configDir)(),(e=>new U(A.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const s=i(31421),n=i(48161),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),w=i(84968),v=i(48963),b=i(56519),S=i(84777),P=i(8103),M=i(45879),_=i(43334),T=i(24399),E=i(45643),D=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function k(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){if(_.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,M.readFileMaybe)("/proc/"+i+"/stat")));return D().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,E.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:N)).filter((e=>k(e)&&t.includes(e.pid)));return D().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=k,t.pidInfo=async function(e){return(0,b.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,b.thenMap)((0,E.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const F="Get-Process",C="| Select-Object -Property Id,ProcessName,StartTime";function A(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(T.PowerShell.instance().ended)return R(e);const t=[F,"-Id",A(e),"-ErrorAction SilentlyContinue",C].join(" ");return(0,b.thenMap)(T.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,v.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,v.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===a.default.pid))||r.push({pid:a.default.pid,start:new Date(w.StartTs),cmd:"node "+a.default.title}),r}async function N(e){return t=(await(0,S.stdoutResult_)("ps",["-p",A(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(_.isLinux)return(0,c.toGt0)((0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){D().warn("clk_tck failed",{error:e})}return 100})),j=(0,g.lazy)((()=>Date.now()-(0,n.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,s=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(s)?{pid:i,cmd:r,start:new Date(j()+s/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),s=i(42659),n=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),w=i(99331),v=i(56519),b=i(31562),S=i(84777),P=i(34102),M=i(43334),_=i(28874),T=i(63870),E="{ready}",D=" | ConvertTo-Json -Compress";function k(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=k,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,T.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,v.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,D),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,w.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,D),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,v.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+k(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,w.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,T.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),s=i(91655),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874),l=(0,n.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,s.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,s.pick)(e??{},"retries","halt","path"),...(0,s.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},86941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(19851),s=i(59455),n=i(72993),a=i(46292),o=i(95696),l=i(50213),u=i(83179),c=i(28874),d=i(2858),h=i(84438),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),n=await t.resolve_();if(null==r||null==n||n.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=n.join("licenses");for(const r of(0,s.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=n.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),s=i(22573),n=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function w(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function v(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){M(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&w(),y("strictDeduping",e)&&v(),(y("optOut",e)||y("noNetwork",e))&&_()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(m.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=w,t.setStrictDeduping=v;const b=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],S={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function M(e){for(const t of b)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:S;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function _(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=M,t.disableExternalNetworkRequests=_},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),s=i(53265),n=i(87652);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},4936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(55835),l=i(51926),u=i(50213),c=i(81168),d=i(79842),h=i(21330),f=i(51275),m=i(29882),p=i(28874),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+e.replace(/'/g,"′")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),s=i(83556);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),w=i(40583),v=i(81168),b=i(44198),S=i(96706),P=i(34102),M=i(28283),_=i(81075),T=i(98778),E=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?n(this,r,"m",s).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?n(this,r,"m",s).call(this,e??t)+": "+i:null==this.fromEnv(e)?n(this,r,"m",s).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,v.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,S.caseInsensitiveEnv)():new w.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,b.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,M.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(M.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return _.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,b.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&S.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,b.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&S.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new w.CaseInsensitiveValued(e)))??(0,S.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,v.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],E.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,v.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],E.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,v.wrap)(["",e+": "+r],E.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,T.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,T.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,T.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,s=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),s=i(51168),n=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),w=i(40583),v=i(79840),b=i(7282),S=i(12801),P=i(4328),M=i(70488),_=i(84248),T=i(5531),E=i(99315),D=i(34365),k=i(34580),x=i(96706),F=i(50274),C=i(33866),A=i(52086),I=i(48584),O=i(45969),L=i(43334),R=i(24540),N=i(70379),B=i(71300),j=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),q=i(30577),H=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Z=i(71988),Y=i(38483),X=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),se=i(57039),ne=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(b.isProd);const we=()=>!(0,t.isProd)();function ve(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function be(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>we()?"1":"25"}),imageCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>we()?32:1024}),quiet:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:be}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Y.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Y.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:be}),useFsWatch:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new se.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>H.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:H.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>H.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Y.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Y.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Y.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Y.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new Y.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),minDelayBetweenSpawnMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,M.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>we()?"5s":"5m"}),streamFlushMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>v.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ne.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>we()?50:500,min:1,max:5e3}),enableArchive:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ve()}),enableRemove:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!ve()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Y.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:T.CheckpointTypes,defaultValue:T.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:D.SynchronousModes,defaultValue:D.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>we()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:we()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>we()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Y.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Y.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Y.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!we()||!(0,O.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:C.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Y.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Y.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Y.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Y.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:q.UpdateChannels}),autoUpdateCheck:new Y.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Y.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Y.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,k.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Y.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Y.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Y.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Y.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Y.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":s.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Y.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Y.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!we()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Y.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:F.SidecarExts,defaultValue:F.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Y.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Y.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new ne.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Y.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Y.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!we()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:A.CropStrategies.attention,strEnum:A.CropStrategies}),videoFrameAtSec:new ne.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Y.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Y.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Z.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Y.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>j.DefaultIncludedPreviewTags}),disableAllFilters:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Y.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Y.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new se.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Y.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ne.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!we()}),tagKeywordsFromPath:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Y.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new ne.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!we()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Y.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Y.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Y.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function Se(e){const i=((0,u.blank)(e)?"":e).split(n.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(n.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=Se,t.pathWithDefaults=(0,a.lazy)((()=>Se((0,x.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const Me=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Me().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new w.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(31586),n=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),w=i(15674),v=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{v.Settings.configDir.opts.defaultValue=o.configDir,v.Settings.logDir.opts.defaultValue=c.defaultLogDir_,v.Settings.logServerLevel.opts.defaultValue=()=>v.Settings.logLevel.valueOrDefault,v.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,v.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,v.Settings.libraryDir.opts.exampleValue=()=>(0,n.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,n.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),v.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,v.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,v.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],v.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,w.maxCpus)()/4)),v.Settings.useFsWatch.watch(f.useFsWatch),v.Settings.updateChannel.opts.defaultValue=g.channel,v.Settings.minBusyPct.opts.defaultValue=()=>(0,s.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),w=i(54993),v=i(50213),b=i(81168),S=i(83556),P=i(87290),M=i(98314),_=i(34102),T=i(83278),E=i(95696),D=i(60865),k=i(4175),x=i(83179),F=i(81075),C=i(28874),A=i(41692),I=i(84438),O=i(32707),L=i(6707),R=i(98778),N=i(55018),B=i(10357),j=(0,r.lazy)((()=>(0,v.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,O.systemSettingsFile)()){if(null!=e)return X(T.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,L.readTomlFile_)((0,O.systemSettingsFile)()))?.[C.Settings.libraryDir.name])}catch{return}}function U(e){return(0,L.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function q(){return U((0,O.systemSettingsFile)())}function H(e){return U(z(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:C.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,x.settingsToObj)(i),wip:r}),r){const t=await(0,L.readTomlFile_)(s),i=await(0,L.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function K(e=(0,O.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,C.persistedSystemSettings)()),t}function Z(e){return X(z(e))}async function Y(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,C.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,C.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function X(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,M.errorToS)(e)),[]}}async function Q(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,L.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,C.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,C.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}})));return t.info("loaded",{settings:(0,x.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,k.handleDeprecatedSettings)(),(0,k.handleMetaSettings)(a),{settings:a,warnings:n}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return C.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=q,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await q()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await H()&&await Y()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",G),(0,_.ee)().on("settingsChanged",G),C.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,D.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(E.PosixFile.for(e),(0,C.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=Y,t._readSettings=X,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([C.Settings.noNetwork,C.Settings.httpPort,C.Settings.license,C.Settings.logStdout,C.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(C.Settings))ee().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),C.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(E.PosixFile.forMaybe((0,O.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,_.ee)().emit("clearCache"),A.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${D.versionMajorMinor}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...F.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...F.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,w.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>{return i=t,s=e.strEnum,(0,r.compact)((0,a.splitStringArray)(i)?.map((e=>s.getCI(e))));var i,s},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),s=i(55835),n=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),s=i(44652),n=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),s=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),s=i(81168);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),w=i(81168),v=i(76596),b=i(79842),S=i(66649),P=i(21330),M=i(98725),_=i(928),T=i(54261),E=i(89724),D=i(17415),k=i(88600),x=i(51275),F=i(29882),C=i(17217),A=i(68284),I=i(57902),O=i(28874),L=i(65162),R=i(71300),N=i(14036),B=i(61424),j=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,b.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,C.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,b.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,A.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,M.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,D.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,D.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,v.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,x.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,T.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,_.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,k.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,x.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,D.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,b.datedToStartDateTime)(this.date)??(0,b.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,b.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function q(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],s=r;if((0,k.isValidDate)(t)){if((0,D.isValidZone)(e.tz)&&(!(0,x.hasZone)(t)||R.OverrideUTCZoneTags.includes(s))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,w.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,b.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,b.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,b.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,x.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function H(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,M.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,b.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,M.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,k.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,w.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,F.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",q(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??s("tags",q(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("stat+bname",await(0,B.extractStatBname)(e)))??(n?void 0:s("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",H(e,t)))??(n?void 0:s("path",G(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await $(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return q(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),s=i(97352),n=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(77988),n=r(i(76760)),a=r(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),w=i(12168),v=i(56038),b=i(4867),S=i(36557),P=i(98247),M=i(21330),_=i(98725),T=i(23467),E=i(88561),D=i(95696),k=i(17217),x=i(16287),F=i(50213),C=i(17921),A=i(7282),I=i(88158),O=i(23560),L=i(28874),R=i(12089),N=i(81168),B=i(63870),j=i(15674),z=i(28544),V=i(43207),W=i(72180),U=i(75767),q=i(12788),H=i(80495),G=i(14036),$=i(67083),J=i(3432),K=i(28630),Z=i(15912),Y=i(30748),X=i(16170),Q=i(95141),ee=i(7330),te=i(54979),ie=i(1078),re=i(61424),se=i(8791),ne=(0,o.lazy)((()=>(0,F.mkLogger)("exiftool.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,S.batchClusterOptions)((0,A.isTest)()?8:(0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeoutError)({p:le().version(),timeoutMs:L.Settings.statTimeoutMs.valueOrDefault})},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,B.commandTimeoutMs)()})))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,k.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*w.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,N.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),s=await e.sidecar(),n=(0,X.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,X.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=D.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void ne().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ne().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,X.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,v.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,X.normalizeMimetype);if((0,u.blank)(r))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values])if(!(0,W.isUtcTagName)(t)){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l)}const c=o?(0,Y.extractMakeAndModel)(n):await(0,re.inferMakeAndModel)(e,n);c.Make!==(0,Y.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,Y.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(n),h=await(0,z.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,V.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};(0,A.isTest)()&&(y.__parsedBy__=a.default.pid);const w={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(w,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(w)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,T.eqlAsync)(e.sha(),t.sha())||await(0,T.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=D.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,k.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,k.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,v.time)("exiftool.overwriteTags:"+e,(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,v.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,v.time)("exiftool.writeTags:"+e,(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await me(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=D.PosixFile.for(t),s=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:s}),await le().write(r.nativePath,s,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...L.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,G.isVideoExt)(n.default.extname(e))?[]:["-fast"]],r=await(0,v.time)("exiftool.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,X.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),ae&&(r.__instance=(0,C.safeUUID)()),r}}),t.parseTags=ge},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),w=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const v=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function T({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of v){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of v)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of v){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>T({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>T({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>T({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>T({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,w.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),s=i(40958),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function w(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=w,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return w(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return w(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return w(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return w(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return w(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return w(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return w(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return w(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),s=i(45599),n=i(68708),a=i(50213),o=(0,s.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,n.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:s}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[s])&&(t[i]=t[s]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,n.pick)(e,"Directory","FileName"));for(const t of(0,n.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),w=i(50213),v=i(81168),b=i(66649),S=i(17415),P=i(29882),M=i(95696),_=i(17217),T=i(28874),E=i(47783);function D(e,t){return(0,d.entries)(t??{}).map((([t,i])=>k({action:e,key:t,value:i})))}function k({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=D,t.mkHistoryRecord=k,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,w.mkLogger)("tags.History")));function F(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function C(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function A(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,v.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,_.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!F(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=M.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=F,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,v.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=C(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=C,t.inferredToTags=A,t.ensureInferredHistoryRecords=async function(e,i,r){const s=D(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?A(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),I(i,s,n)},t.ensureHistoryRecords=I},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(53705)),n=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),w=i(72180),v=i(14245),b=i(61424),S=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,v.omitInvalidGeolocationTags)(t);{const e=M(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,w.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=_(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function M(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return S().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function _(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,u.toDated)(t[r]);if(null==s||(0,f.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return S().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return S().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=M,t.inferTzOffsetMinutesFromFilename=_},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),w=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function v(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):v(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>w.unset()))})),t.keywordToPath=function(e){const t=w();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=v,t.splitKeywords=b;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function T(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,T);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,T).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=T,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(_(i)?t.push(...T(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const w=/([\d. -]+)\s?mm\b/i,v=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=w.exec(e)?.[1].replace(/\s/g,""),i=v.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function w(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=w(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=w;const v={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(v))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},38010:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(50213),g=i(84885),y=i(66649),w=i(98725),v=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function M(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return v().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return v().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return v().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,w.parseDated)({input:e.When}));return null==r?v().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?v().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):v().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-M(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),s=i(54993),n=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},66039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(75020),u=i(59455),c=i(50213),d=i(68852),h=i(81168),f=i(70417),m=i(28874),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,w=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,v=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,w),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function M(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,v),null!=e&&(M(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(M(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const _=(0,s.compactBlanks)(t.split(/\s+/)),T=l.length,E=b.length;if(_.length>0)if(0===T&&E>0)l.push(..._);else if(0===E&&T>0&&1===_.length)b.push(..._);else if(1===_.length)l.push(..._);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?_.pop():_.shift()),l.push(..._)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function M(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function _(e,t,i){return M("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=M([t.modifier,t.lifespan]),r=M(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?M([r,e]):_(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),s=i(54993),n=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),s=i(40958),n=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,s.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),w=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),v=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return w().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return w().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return v().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},3127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(54993),s=i(42231);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),w=i(79842),v=i(21330),b=i(98725),S=i(51275),P=i(35280),M=i(19748),_=i(88561),T=i(95696),E=i(65238),D=i(17217),k=i(57902),x=i(28874),F=i(80496),C=i(65162),A=i(28544),I=i(47783),O=i(88840),L=i(30748),R=i(16170),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===F.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===F.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:k.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,v.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,v.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,v.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,M.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7,i=!0){if(!await j(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(r,(e=>(0,C.bname)(e))),n=(0,D.findFileIndex)(e,s);if(n<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),H(e,t,!1)):void 0;const l=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[s.slice(n-2*t,n),s.slice(n+1,n+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,C.bname)(e,!0),(0,C.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,w.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,w.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function w(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function v(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=w,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(w(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=v,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>v(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),s=i(22573),n=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),w=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function v(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await v(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void w().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?w().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=v,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),s=i(57975),n=i(57160),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",w=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class v{static isUri(e){return e instanceof v||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return T(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=w.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?v.file(r.win32.join(T(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=v;const b=h.isWinPortable?1:void 0;class S extends v{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=T(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?_:M;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:M(o,!1)),r}function D(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+D(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=T;const k=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(k)?e.replace(k,(e=>D(e))):e}t.percentDecode=x,t.toURI=function(e){return v.isUri(e)?e:v.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),s=i(40958),n=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),s=i(22573),n=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(9103),a=i(37628);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),s=i(30577);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),s=i(22573),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),s=i(9595),n=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},42233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(45200),s=i(98770),n=i(7014);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),s=i(22573),n=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),w=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function v(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=v,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await w());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(v)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),w=i(24399),v=i(28874),b=i(24541),S=i(60224),P=i(63870),M=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function T(e){return e?.match(_)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(T(e),(e=>e+":\\"))}function D(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(T(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function k(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(T(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=D,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return w.PowerShell.instance().executeJsonToA(x())};const F=/\{([-a-z\d]{7,})\}/i;function C(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function A(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([C(e.HealthStatus,"healthy"),C(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(F.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function I(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>w.PowerShell.instance().executeJsonToA(D(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:v.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(k)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>w.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:v.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(A)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=A,t.volumeInfoWin=I},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),w=i(83278),v=i(8103),b=i(16287),S=i(45969),P=i(43334),M=i(69108),_=i(98770),T=i(44224),E=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,v.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const D=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?D().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,T.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>w.BaseFile.for(e).clear().childDirectories())))))}):D().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(D().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void D().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await k(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,E.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const k=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void D().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),s=i(5233),n=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),w=i(98770),v=i(63870),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,w.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,v.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,w.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,v.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),s=i(19851),n=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),w=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(v)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?w().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){w().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const v=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),w=i(84777),v=i(34330),b=i(8769),S=i(34102),P=i(17217),M=i(16287),_=i(43334),T=i(28874),E=i(8540),D=i(68884),k=i(44224),x=i(24541),F=i(69375),C=i(63870),A=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function O(e=(0,C.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function L(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{T.Settings.libraryDir.watchLater(I),T.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&T.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),O((0,C.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux){const i=(0,k.maybeWatchProcMounts)();await(0,D.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),O((0,C.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),O((0,C.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=T.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?x.mountpointsWin:k.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return A().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,C.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,F.isExcludedMountpoint)(e)||T.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(A().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,S.ee)().on("clearCache",(()=>{D.gioVolumes.unset(),I()})),T.Settings.mountpointsTtlMs.watch(O)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>L(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:D.GioCommand,args:D.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(D.gioVolumes.unset(),L()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,w.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,C.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,v.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>L(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),w=i(28874),v=i(69108),b=i(68884),S=i(59107),P=i(69375),M=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await D()??await(0,c.thenMap)((0,v.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,b.isGioSupported)())try{await(0,c.thenMap)((0,b.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){M().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function T(e){return!w.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,P.isExcludedMountpoint)(e)&&(!w.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function D(e=_,t=T,i=E){if(y.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return M().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return M().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void M().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=T,t.readProcMounts=D,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(_)?new h.FileWatcher(_,{recursive:!1,persistent:!1},(()=>{M().info("detected change in "+_),(0,d.setUnrefTimeout)((()=>S.mountpoints.refresh()),n.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),s=i(42659),n=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),w=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await T()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const v=["LocalName","RemoteName","Status"],b=["NETUSE","get",v.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,u.parseFixed)(v,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const T=(0,w.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),s=i(12168),n=i(28874);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),w=i(95696),v=i(45969),b=i(28874),S=i(59107),P=i(63870),M=i(68995),_=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),T=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function E(e){return(0,a.isTrue)(e.ignorable)||(0,v.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function D(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function k(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=D(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(b.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of b.Settings.volumeUuidFilePaths.values){const i=w.PosixFile.for(e.mountpoint).join(t),r=await k(i).catch((e=>_().info("Failed to read "+i,{error:e})));if(null!=r)return _().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,M.volumeUuidSubpath)());if("/"===e.mountpoint)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(b.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(b.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,M.writeVolumeUuid)(e);if(!(0,n.blank)(t))return _().tap({msg:"readVolumeUUID(): wrote new "+(0,M.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return _().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>T.clear())),S.mountpoints.watchLater((()=>T.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(E(e))return;if((0,a.isFalse)(e.ok))return;const t=await T().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>_().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=E,t.toVolumeUUID=D,t.readUuidFile_=k,t.readVolumeUUID=x},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),w=i(59455),v=i(48884),b=i(50213),S=i(7282),P=i(23560),M=i(28850),_=i(45255),T=i(81168),E=i(56519),D=i(4867),k=i(49776),x=i(9595),F=i(77740),C=i(44198),A=i(96706),I=i(8769),O=i(57159),L=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),j=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),q=i(43334),H=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Z=i(27461),Y=i(66840),X=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=s.default.platform(),ne=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,ne),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,k.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,x.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ne.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,T.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:se}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))n.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,w.toA)(await(0,X.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function me(e,i){const r=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(r))return;const s=await(0,L.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function pe(e,t,i){const r=i.filter((e=>(0,T.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,T.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,W.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,T.equalsIgnoreCase)(n,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,S.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,w.toA)(await(0,X.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,D.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,D.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,O.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if((0,S.isTest)()){const e=(0,p.toInt)((0,C.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,F.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,D.thenOrTimeoutError)({p:q.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,D.thenOrTimeoutError)({p:q.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,Y.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,A.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,T.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,v.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,w.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),h=i(34238),f=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const a=n(i(37067)),o=n(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),h=i(50213),f=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),w=(0,u.defer)((()=>(0,h.mkLogger)("net.get")));async function v(e,t){return b({...t,url:e})}async function b(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?a.request:"https"===t.scheme?o.request:w().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??f.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",h=e?.agent??!1,b=r(t.toString(),{method:c,headers:u,timeout:n,agent:h},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const a={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&y.HttpStatusIs.redirect(a.statusCode)&&!(0,l.blank)(e.headers.location)?(w().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(v(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(w().debug("complete",{...a,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(a))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||b.write(e.body),b.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=v,t.httpRequest_=b},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},14854:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(48161)),h=i(42659),f=i(45599),m=i(55835),p=i(31586),g=i(68708),y=i(19851),w=i(50213),v=i(7282),b=i(78406),S=i(25764),P=i(38835),M=i(74128),_=i(82647),T=i(43334),E=i(28874),D=i(30933),k=i(15674),x=(0,y.lazy)((()=>(0,w.mkLogger)("work.CpuUsage"))),F=(0,y.lazy)((()=>{const e=C.instance().busyPct();(0,M.syncReport)().maybeSystemData({from:"cpuUsage",state:"note",details:"Current system load is too high to schedule more work",meta:(0,g.compactValues)({loadCpuPct:I(),cpuBusyPct:e})}),x().warn("Current system load is too high to schedule more work",{cpuBusyPct:e,max:E.Settings.cpuBusyPercent.valueOrDefault})}),((0,v.isTest)()?15:60)*h.secondMs);t.isTooBusy=function(){if(E.Settings.cpuBusyPercent.valueOrDefault<=0)return!1;const e=C.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(4*E.Settings.cpuBusyPercent.valueOrDefault/3));return(0,p.gte)(e,t)?(F(),!0):(F.unset(),!1)};class C extends b.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,k.singleThreadedMode)()?60:T.isWin?20:10)*h.secondMs,rank:S.EndableRanks.first}),r.add(this),s.set(this,new _.Average(5)),n.set(this,new A),(0,p.mapFinite)(I(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??I()}}t.CpuUsage=C,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,I());const e=new A;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},C.instance=(0,f.defer)((()=>new C));class A{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?(0,p.sigFigs)(t/r*100,3):void x().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+P.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function I(){return T.isWin?void 0:(0,p.sigFigs)(d.default.loadavg()[0]/(0,D.cpuInfo)().length*100,3)}},73328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyDoNotRun=t.doNotRun=void 0;const r=i(68708),s=i(99331),n=i(74128),a=i(63664),o=i(14854);t.doNotRun=function(e){return null!=u(e)};const l=["error","no-library","stop-sync"];function u(e){if(!0===e?.ended)return"endable ended";if((0,s.ending)())return"service is ending";if((0,o.isTooBusy)())return"system is too busy";const t=(0,a.getRemoteOrLocalHealthSummarySync)();if(null==t||!l.includes(t.level))return;const i=t.level+": "+t.msg.join("\n");return(0,n.syncReport)().maybeSystemData({from:"whyDoNotRun",state:"note",details:t.level,meta:(0,r.omit)(t,"links","buttons")}),i}t.whyDoNotRun=u},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),s=i(37692);let n=!1;function a(){return n}function o(e=!0){l(e),(0,s.writeStateFile)({paused:e})}function l(e){e!==n&&(n=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=a,t.pause=o,t.resume=function(){return o(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return a()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const w=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),s.minuteMs);function v(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=v,t.targetCpuLoadPct=b,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(b()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(b()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=v();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,w());return t=(0,a.clamp)(1,s,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:w()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const s=r(i(78474)),n=i(40958),a=i(76790),o=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),h=i(87290),f=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),w=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let v;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new s.default;let b=0;function S(){const e=(0,h.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-b>o.minuteMs;i&&(b=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(v?.nativePath)||(v?.close(),v=void 0),r&&null!=e&&(v??(v=new f.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=S()?.readJsonSync();for(const i of e?.events??[])M.get(i.e)!==i.ts&&(w().info("emitting event "+i.e),t.stateEvents.emit(i.e),M.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const M=new Map;function _(e){const i=S();if(null==i)w().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),s=function(e){const t=Date.now()-10*o.minuteMs;return(0,n.uniqByLast)((0,a.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:s};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=_,t.addStateEvent=function(e){const t=Date.now();M.set(e,t),_({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),s=i(87997),n=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},83600:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.RequestTask=void 0;const a=i(58587),o=i(80875),l=i(19851),u=i(50213),c=i(34102),d=i(84542),h=i(87445),f=i(40958),m=i(26905),p=i(98553),g=i(31586),y=(0,l.lazy)((()=>(0,u.mkLogger)("worker.RequestTask")));class w extends a.Task{constructor(e){super((0,p.stringify)(e),(e=>n(this,r,"m",s).call(this,e))),r.add(this),this.request=e}}t.RequestTask=w,r=new WeakSet,s=function(e){for(const t of(0,f.compactBlanks)((0,d.splitLines)(e))){const e=(0,o.parseJSON)(t);if(null==e)y().warn("ignoring non-json line from worker",{line:t});else{if(null!=e.error)throw y().warn("worker threw error",{response:e}),(0,m.errorFromJson)(e.error);if((0,g.isNumber)(e.id))return e.id!==this.request.id?y().throw(`bad request: #parse given mismatching requests (${e.id} != ${this.request.id})`,{response:e,request:this.request}):e.response;(0,h.isProgressEvt)(e)?(0,c.ee)().emit("progress",e):y().warn("ignoring json line from worker",{response:e})}}return y().throw("bad request: #parse missing valid response")}},93493:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearShims=t.setupShimDelegates=void 0;const r=i(19851),s=i(5233),n=i(68708),a=i(13538),o=i(57206),l=i(50213),u=i(23560),c=i(70025),d=i(28874),h=i(15674),f=i(22751),m=i(83600),p=i(58800),g=i(24817),y=(0,r.lazy)((()=>(0,l.mkLogger)("worker.ShimDelegation")));let w=0;async function v(e,t){const i=d.Settings.taskTimeoutMs.valueOrDefault;return(0,s.retryOnReject_)((async()=>{y().throwIfAborted_();const r={id:w++,fn:e,args:t},s=new m.RequestTask(r),n=await(0,p.workerCluster)(),o=n?.t,l=null==n||null==o?g.WorkerFunctions[e](...t):n.awaitOrAbort(o.enqueueTask(s));return(0,a.thenOrOnTimeout)(l,i/3,(()=>{y().warn("soft timeout servicing work request",{request:r,timeoutMs:i}),(0,f.onTimeout)()})),(0,a.thenOrTimeoutError)(l,i)}),{maxRetries:d.Settings.maxRetries.valueOrDefault,timeoutMs:i,retryDelay:d.Settings.minDelayBetweenRetriesMs.valueOrDefault,errorIsRetriable:e=>!1!==(0,c.isRetriableError)(e)})}function b(){for(const e of(0,n.values)(g.WorkerFunctions))(0,n.maybeCall)(e,"clearShim")}t.setupShimDelegates=async function(){if((0,o.addDefaultJsonRevivers)(),(0,u.isWorkerService)())b(),y().warn("setupShimDelegates(): in worker service, skipping");else if((0,h.singleThreadedMode)())y().warn("setupShimDelegates(): single-threaded mode, clearing shims"),b(),await(0,p.endWorkerCluster)();else for(const[e,t]of(0,n.entries)(g.WorkerFunctions))t.setShim((t=>v(e,t)))},t.clearShims=b},24817:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequest_=t.isWorkRequest=t.mkWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=t.AllWorkerFunctionCandidates=void 0;const r=i(98553),s=i(31586),n=i(68708),a=i(50989),o=i(32639),l=i(13991),u=i(50597),c=i(48368),d=i(52121),h=i(48604),f=i(181),m=i(66106),p=i(47783),g=i(83966);t.AllWorkerFunctionCandidates={_extractVideoFrame_:m._extractVideoFrame_,_readRawTags:p._readRawTags,_readTags:p._readTags,assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkerFunctions={assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkRequestMethods=(0,a.strEnum)(...(0,n.keys)(t.WorkerFunctions));let y=0;t.mkWorkRequest=function(e,t){return{id:++y,fn:e,args:t}},t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,s.isNumber)(e.id)},t.handleWorkRequest_=async function(e){const i=t.WorkerFunctions[e?.fn];if((0,o.isFunction)(i))return i(e?.args);throw new Error("invalid method "+(0,r.stringify)(e))}},58800:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerCluster=t.endWorkerCluster=t.workerClusterPriorEnd=void 0;const r=i(58587),s=i(36557),n=i(19851),a=i(50213),o=i(71567),l=i(25764),u=i(84777),c=i(86335),d=i(38835),h=i(84542),f=i(87445),m=i(41944),p=i(15674),g=i(42659),y=i(98553),w=i(31586),v=i(67478),b=i(54993),S=i(27395),P=i(5916),M=i(55534),_=i(29325),T=i(28874),E=i(30933),D=i(41657),k=(0,n.lazy)((()=>(0,a.mkLogger)("worker.cluster")));t.workerClusterPriorEnd=async function(){return(await t.workerCluster.prior())?.t.closeChildProcesses()},t.endWorkerCluster=function(){return(0,S.end)(t.workerCluster.prior())},t.workerCluster=(0,P.lazyAsync)({desc:"worker.workerCluster",later:async()=>{const e=await(0,c.pathToService)("worker");if(null==e)return k().throw("Could not find worker.js"+d.FatalErrorFlag);k().info("worker.js found at "+e);const t={id:-1,fn:"ping",args:{}},i=new r.BatchCluster({processFactory:async()=>(k().info("Spawning new worker",{execPath:process.execPath,worker:e.nativePath,maxProcs:(0,p.maxCpus)()}),(0,u.spawn)(process.execPath,[e.nativePath],0,{env:await(0,D.workerEnv)()})),...(0,s.batchClusterOptions)((0,p.maxCpus)(),"worker.BatchCluster"),streamFlushMillis:0,versionCommand:(0,y.stringify)(t),healthCheckCommand:(0,y.stringify)(t),taskTimeoutMillis:T.Settings.taskTimeoutMs.valueOrDefault,maxProcAgeMillis:4*T.Settings.taskTimeoutMs.valueOrDefault,minDelayBetweenSpawnMillis:(0,_.isPacked)()?g.secondMs:1,pass:o.ReadyStr,fail:d.FatalErrorRe,exitCommand:M.ServiceExitCommand});return i.on("taskData",(e=>{for(const t of(0,h.splitLines)((0,b.toS)(e))){const e=(0,v.parseJSON)(t);(0,f.isProgressEvt)(e)&&(0,m.emitProgressEvt)(e)}})),p.maxCpus.watchLater((e=>{const t=(0,w.clamp)(1,(0,E.cpuCount)(),e??(0,p.maxCpus)());return k().warn("maxConcurrentImports changed",{maxProcs:t,newValue:e}),i.setMaxProcs(t)})),new s.BatchClusterObserver("worker",i,l.EndableRanks.first)}})},41657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerEnv=void 0;const r=i(9727),s=i(28874),n=i(59107);t.workerEnv=async function(){const e={};return s.Settings.libraryDir.addToEnv(e),s.Settings.mountpoints.addToEnv(e,await(0,n.mountpoints)()),(0,r.childEnv)({overrides:e,forWorker:!0})}},83966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const s=r(i(1708)),n=i(41400),a=i(31586),o=i(7282),l=i(12089),u=i(45608),c=i(57159),d=i(89035);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),(0,o.isTest)()&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:s.default.pid,input:e?.input??"(no input)"}}})},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function w(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:w((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=w,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return w(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return w(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},75761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function w({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function v({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const v=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=v):p.src=v,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(w({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=w,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...v({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=v},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),s=i(31586),n=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),s=i(22573),n=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function w(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function v(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=w,t.fmtLocalToShort=function(e){return(0,a.map)(w(e),m)},t.nextMidnightTs=v,t.msUntilMidnight=function(){return v()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),s=i(73872);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const w=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,w),w}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s.hasPrior=()=>r,s}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),s=i(21605),n=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),s=i(68708),n=i(34666),a=i(32639);function o(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,n.isPrimitive)(e)||(0,n.isPrimitive)(t))return e===t;if(!(0,s.isObject)(e)||!(0,s.isObject)(t))return!1;for(const i of(0,s.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),s=i(42659),n=i(55835),a=i(31586),o=i(12168),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),s=i(50357),n=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class s extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=s},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,(t=>!e(i,t,s)));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),s=i(22573),n=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=w(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,s){return!(null==s||!o(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,s.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function w(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function v(e){return o(e)&&e>0}function b(e){return o(e)&&e>=0}function S(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function M(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function _(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=w(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=v,t.firstGt0=function(...e){for(const t of e){if(v(t))return t;const e=y(t);if(v(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=w(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return v(t)?String(t):void 0},t.mapNumeric=S,t.map2Numeric=function(e,t,i){return S(e,(e=>S(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,n.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return S(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=M,t.toPrecisionMaybe=function(e,t){return d(e,(e=>M(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=_,t.times=function(e,t){if(!v(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return _(0,100,v(t)?P(100*(v(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function w(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function v(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=w(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=w,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=v,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=v(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),s=i(30976),n=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),s=i(54993),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),s=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=w,t.ensureSuffix=v,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return v(w(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=w((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),s=i(68708),n=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let s=!0;const n=setTimeout((()=>{s&&(s=!1,i(a.Timeout))}),t);try{n.unref?.();const t=await e;s&&(s=!1,i(t))}catch(e){s&&(s=!1,r(e))}finally{clearTimeout(n)}}))}async function c(e,t,i=!0){const s=await u(e,t,i);if(s===a.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return s}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?a.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return c(e,s,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,n.tot)(i);const s=await u(e,t,r);return s===a.Timeout?(0,n.tot)(i):s}},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),s=i(30301),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(30301),s=i(54993);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},58939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(55835),s=i(31586);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},12236:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.noRecentAssetIdsProgress=t.isRebuildProgress=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0;const r=i(50989);t.SyncStatuses=(0,r.strEnum)("processing","paused","done"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI].includes(e?.uri)},t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),s=i(30301),n=i(31586),a=i(97238),o=i(29652);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return n(e)??[]},t.optToA=n},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),s=i(23541),n=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},98401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cancelFileAndProcCleanups=t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=t.maybeCleanup_=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(56519),o=i(76187),l=i(87290),u=i(79267),c=i(32144),d=i(13829),h=i(69734),f=i(95696),m=i(65238),p=i(70257),g=i(13940),y=i(12495),w=i(95402),v=i(28874),b=i(40958),S=i(42659),P=i(31586),M=i(64526),_=i(22526),T=i(69032),E=(0,r.lazy)((()=>(0,s.mkLogger)("library.Cleanup")));async function D(){const e=M.Library.instance();if(null==e)E().info("No library to vacuum.");else{E().info("Running tag and search maintenance...");try{await(0,T.runTagMaintenance)()}catch(e){E().warn("Failed to run tag maintenance",{error:e})}E().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,n.isDbJanitorService)()&&(E().info("Running database maintenance..."),await e.runDbBackup_())}E().info("Cleaning child processes..."),await(w.Pids.instance()?.killOldProcs()),E().info("Cleaning stale and temp files..."),await k(),await(0,a.mapAsync)({name:"fileCleanup",arr:j(),f:e=>e.cleanup()})}t.maybeCleanup_=(0,r.lazy)(D,5*S.minuteMs),t.cleanup_=D;const k=(0,r.lazy)((()=>(0,l.libraryDataDirPosixFile)()?.join("shared-state").rmrf())),x=(0,r.lazy)((()=>u.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:g.imageCacheDir_,staleMs:v.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ImageCacheName)}))),F=(0,r.lazy)((()=>u.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>f.PosixFile.for((0,m.readdirCacheDir)()),staleMs:v.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(m.ReadDirCacheName)}))),C=(0,r.lazy)((()=>u.FileCleanup.for({name:"previewWipCleanup",rootNativePath:l.libraryPreviewsDirPosixFile,staleMs:S.hourMs,isPrunable:e=>(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)}))),A=(0,r.lazy)((()=>u.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:d.defaultFsAdvisoryLockDir,staleMs:S.hourMs,isPrunable:h.isPsLockFileOrDir}))),I=(0,r.lazy)((()=>u.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,P.gt0)(v.Settings.syncReportRetentionCount.valueOrDefault)?(0,l.librarySyncReportsDir)():void 0,staleMs:S.hourMs,isPrunable:e=>(0,p.isWip)(e)||(0,c.isCsvExt)(e)})));function O(e){return(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)||(0,o.isSqliteFile)(e)}const L=(0,r.lazy)((()=>u.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,_.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:S.hourMs,isPrunable:O}))),R=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,_.libraryDbObjects_)().libraryDbBackupDir,staleMs:S.hourMs,minRetained:v.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:O})));async function N(){const e=await(M.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const B=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:N,staleMs:S.hourMs,minRetained:1,isPrunable:O})));function j(){return(0,b.compact)([x(),F(),C(),A(),(0,y.LogDirCleanup)(),I(),L(),R(),B()])}t.fileCleanups=j,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{w.Pids.instance()?.scheduleInterval();for(const e of j())e.scheduleInterval()})),t.cancelFileAndProcCleanups=function(){t.scheduleFileAndProcCleanups.unset(),w.Pids.instance()?.cancelInterval();for(const e of j())e.cancelInterval()}},64526:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(27395),u=i(25764),c=i(38836),d=i(99331),h=i(45608),f=i(15056),m=i(87290),p=i(38835),g=i(57159),y=i(61704),w=i(95696),v=i(18454),b=i(13940),S=i(48604),P=i(19851),M=i(23560),_=i(28874),T=i(2858),E=i(7014),D=i(63870),k=i(15674),x=i(22573),F=i(38639),C=i(42659),A=i(56409),I=i(68708),O=i(25470),L=i(22526),R=i(41844);class N extends c.EndableWrapper{static instance(){const e=_.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,M.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired_(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new A.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted_(),await(0,T.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted_();const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,F.isTrue)(e?.remote)){const e=_.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;_.Settings.maxConcurrentImports.hasValue()||(_.Settings.maxConcurrentImports.tmpValue=e,(0,k.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted_(),(0,M.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted_(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),v.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.previews=(0,P.lazy)((()=>(0,I.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new R.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,M.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.onEnd=(0,P.lazy)((async()=>{if(!(0,d.ending)())for(const{ea:e,t}of[{ea:this.dbModelJanitor.clear(),t:5*C.minuteMs},{ea:this.dbFsLock.clear(),t:(0,D.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=w.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise.then((()=>this))}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup_(){return(await this.dbModelJanitor())?.backup_()}}t.Library=N,r=N,n=new WeakMap,s={value:void 0}},19113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(62105),s=i(181),n=i(94448),a=i(39604);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},18449:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(7282),s=i(96706),n=i(29325),a=i(28874);t.sentryEnabled=function(){return(0,s.isEnvTrue)("ENABLE_SENTRY")||(0,r.isProd)()&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},95629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(16436)),l=a(i(48161)),u=a(i(1708)),c=i(19851),d=i(19043),h=i(50213),f=i(31578),m=i(7282),p=i(96175),g=i(23560),y=i(84968),w=i(81168),v=i(37805),b=i(25764),S=i(38836),P=i(99331),M=i(85100),_=i(98314),T=i(68301),E=i(70025),D=i(8769),k=i(34102),x=i(34592),F=i(42042),C=i(34474),A=i(20839),I=i(57902),O=i(45969),L=i(43334),R=i(40958),N=i(22573),B=i(42659),j=i(41400),z=i(98553),V=i(55835),W=i(12168),U=i(59455),q=i(54993),H=i(18449),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,M.serviceExitTimeoutMs)(e.name),release:v.release,environment:(0,m.nodeEnv)(),maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,D.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(T.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,w.ellipsize)(i,256));const r=await X(e);return await(T.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,k.ee)().on("fatal",$),(0,k.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Z(e.exception?.values)),(0,_.errorToS)(t?.originalException)])).join(": ")}function Z(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(Y))))}function Y(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function X(e){const t=await(0,F.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=v.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,x.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*A.DefaultLogFlushMs);const e=await(0,C.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,w.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,w.isString)(e.meta)?(0,w.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Z,t.sentryExceptionToS=Y,t.annotateEvent=X,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[I.LogLevels.fatal,"fatal"],[I.LogLevels.error,"error"],[I.LogLevels.warn,"warning"],[I.LogLevels.info,"info"],[I.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},37158:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const p=m(i(29907)),g=m(i(1708)),y=i(57206),w=i(19851),v=i(50213),b=i(59880),S=i(23560),P=i(19913),M=i(71567),_=i(37805),T=i(38836),E=i(99331),D=i(45608),k=i(56038),x=i(55534),F=i(42499),C=i(49776),A=i(96706),I=i(98314),O=i(38835),L=i(70025),R=i(8769),N=i(57159),B=i(34102),j=i(33456),z=i(87408),V=i(85021),W=i(17181),U=i(86941),q=i(28874),H=i(41692),G=i(2858),$=i(69385),J=i(22573),K=i(42659),Z=i(41400),Y=i(56409),X=i(55835),Q=i(41583),ee=i(54993),te=i(95629);t.setupEventHandlers=(0,w.lazy)((()=>{(0,B.ee)().on("resume",(()=>(0,$.resume)())),(0,B.ee)().on("pause",(()=>(0,$.pause)()))}));class ie extends T.EndableWrapper{constructor(e){super(e),r.add(this),s.set(this,void 0),n.set(this,new Y.Latch),a.set(this,new Map),this.setup_=(0,w.lazy)((()=>(0,k.time)("Service.setup",(()=>f(this,r,"m",o).call(this))))),u.set(this,(0,w.lazy)((()=>{const e=g.default.stdin.pipe(new j.LineReader);return e.on("data",(e=>f(this,r,"m",d).call(this,(0,ee.toS)(e)))),e}))),(0,S.isBillingService)()||(0,H.setSettingsDefaults)(),h(this,s,(0,v.mkLogger)("Service("+this.name+")"),"f"),f(this,r,"m",c).call(this),this.setup_()}get name(){return super.name}get ready(){return f(this,n,"f").promise}get isReady(){return f(this,n,"f").isResolved()}setInputHandler(e,t){f(this,a,"f").set(e.trim().toLowerCase(),t)}}t.Service=ie,s=new WeakMap,n=new WeakMap,a=new WeakMap,u=new WeakMap,r=new WeakSet,o=async function(){try{(0,J.mapNotBlank)((0,A.getEnv)("PS_FATAL_"+this.name),(e=>{throw new N.WrappedError(e,{fatal:!0})})),(0,J.mapNotBlank)((0,A.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Z.later)((()=>{throw new N.WrappedError(e)}),5*K.secondMs)})),(0,P.setServiceName)(this.name),(0,b.setProcessTitle)(),(0,S.isMainService)()&&await(0,U.mergeUserDataDirs_)(),await(0,G.readSettings)(),await f(this,r,"m",l).call(this),(0,W.setupLogger)(),(0,y.addDefaultJsonRevivers)(),(0,C.cacheDir)(),(0,t.setupEventHandlers)(),f(this,u,"f").call(this),await(0,F.setupLuxon)(),q.Settings.startPaused.valueOrDefault&&(0,$.pause)(),(0,E.ending)()?f(this,n,"f").reject():f(this,n,"f").resolve()}catch(e){console.error((0,I.errorToS)(e)),f(this,n,"f").reject((0,Q.toErr)(e)),(0,D.exit)({reason:(0,L.addErrorFlags)(this.name+" setup failed: "+(0,I.errorToS)(e),O.FatalErrorFlag),status:14})}},l=async function(){(0,S.isPermaService)()||(0,B.ee)().on("fatal",(e=>(0,D.exit)({error:e,status:12}))),g.default.on("unhandledRejection",(e=>(0,X.map)(e,(e=>(0,R.onError)("unhandledRejection",e))))),g.default.on("uncaughtException",(e=>(0,X.map)(e,(e=>(0,R.onError)("uncaughtException",e))))),g.default.on("SIGINT",(()=>(0,D.exit)({reason:"SIGINT",status:0}))),g.default.on("SIGHUP",(()=>(0,D.exit)({reason:"SIGHUP",status:0}))),g.default.on("SIGTERM",(()=>(0,D.exit)({reason:"SIGTERM",status:0}))),p.default.isWorker&&g.default.on("disconnect",(()=>(0,D.exit)({reason:"disconnect",status:0}))),await(0,te.installSentry)(this)},c=function(){this.setInputHandler("--version",(()=>(0,M.stdoutWrite)({version:_.version}))),this.setInputHandler(x.ServiceExitCommand,(()=>(0,Z.later)((()=>(0,D.exit)({reason:x.ServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,M.stdoutWrite)(k.PromiseTimer.instance().report()))),this.setInputHandler(V.HealthCheckCommand,(async()=>(0,M.stdoutWrite)(await(0,z.getStatusSummary)({refresh:!0}))))},d=async function(e){if(f(this,s,"f").debug("onLine()",{line:e,ending:this.ended||(0,E.ending)()}),await this.setup_(),e.startsWith("--")){const t=e.split(/\s+/,1)[0],i=f(this,a,"f").get(t);null==i?(f(this,s,"f").error("onLine(): unknown command",{line:e,knownCommands:[...f(this,a,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else f(this,s,"f").error("onLine(): failed to process",{line:e})}},56992:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calcVolumesTTL=t.setVolumesTTL=void 0;const r=i(19851),s=i(50213),n=i(76596),a=i(87290),o=i(28874),l=i(2858),u=i(63870),c=i(7014),d=i(42659),h=i(31586),f=i(12168),m=(0,r.lazy)((()=>(0,s.mkLogger)("SetVolumesTTL")));async function p(){if(!(0,l.libraryHasSettings)())return;const e=[],t=await(0,c.volumes)(),i=o.Settings.minDiskFreeGb.defaultValue*f.GB;for(const r of[(0,a.libraryOriginalsDirPosixFile)(),(0,a.libraryPreviewsDirPosixFile)()]){const s=await(0,c.bestVolumeForPath)(r,t);if(null==s)return void m().warn("Can't find volume for "+r+", using default TTL for volumes()");if(s.availablethis.maybeRunChunk(),intervalMs:7*N.secondMs,onEnd:()=>w(this,r,"m",a).call(this),rank:T.EndableRanks.first,endTimeoutMs:C.Settings.taskTimeoutMs.valueOrDefault}),r.add(this),this.recentlyProcessed=new P.TTLArray(N.minuteMs),s.set(this,[]),this.taskCount=(0,v.lazy)((()=>W.Task.count())),d.set(this,(0,v.lazy)((()=>{this.logger.debug("status",this.state())}),((0,b.isTest)()?1:30)*N.secondMs)),f.set(this,(()=>this.maybeRunChunk())),m.set(this,(0,v.lazy)((()=>this.logger.info("runChunk(): no-op",{isPaused:(0,O.isPaused)(),isFull:this.p.isFull(),isTooBusy:(0,A.isTooBusy)(),whyDoNotRun:(0,I.whyDoNotRun)(this),pendingWorkCount:this.pendingWorkCount(),queueItemCount:this.taskCount(),freeSlots:this.p.freeSlots()})),((0,b.isTest)()?1:30)*N.secondMs)),this.maybeRunChunk=(0,v.lazy)((()=>{setTimeout((()=>{this.ended||(0,E.ending)()||(w(this,r,"m",g).call(this),this.maybeRunChunk.unset())}),t.TaskListRunLaterMs)})),p.set(this,(0,v.lazy)((()=>{const e=C.Settings.minBusyPct.valueOrDefault,t=C.Settings.stuckCheckIntervalMs.valueOrDefault;if(e<=0||this.p.isIdle()||t<=0)return;const i=A.CpuUsage.instance().busyPct();if(this.logger.debug("maybeCheckForStuckTasks()",{cpuBusyPct:i,minBusyPct:e,stuckCheckIntervalMs:t}),!(0,V.gte)(i,e))for(const e of this.p.running)if(e.elapsedMs>t){const t=e.payload;this.logger.error("Stuck serial task. Aborting.",{task:t,elapsedMs:e.elapsedMs});const i="stuck after "+e.elapsedMs+"ms";t.abort(i),e.reject(new M.AbortError(i))}}),C.Settings.stuckCheckIntervalMs.valueOrDefault)),this.p=new k.Promises(e,L.maxConcurrentImports),this.p.ee.on("vacancy",this.maybeRunChunk),this.p.ee.on("drain",(()=>w(this,r,"m",l).call(this))),(0,x.ee)().on("resume",w(this,f,"f")),W.Task.ee.on("added",this.maybeRunChunk)}async awaitDrain(e=[],t=0){(0,R.isEmpty)(e)&&(e=W.TaskNames.values);const i=new z.Latch;return w(this,s,"f").push({l:i,taskNames:e,maxRemaining:t,who:(0,j.shortStack)()}),this.maybeRunChunk(),i}isRunnable(){return!this.p.isFull()}currentWorkCount(){return this.p.unsettledCount()}pendingWorkCount(){return this.taskCount()-this.currentWorkCount()}hasCapacity(e=C.Settings.taskListCap.valueOrDefault){return e<=0||this.taskCount()e.payload))}currentTasksByFn(e){return this.currentTasks().filter((t=>t.fn===e))}state(){return{...this.p.stats(),isDone:w(this,r,"m",l).call(this),freeSlots:this.p.freeSlots(),pendingWork:this.taskCount(),next10:w(this,r,"m",h).call(this,10).map((e=>e.toString())),recentlyProcessedLast10:this.recentlyProcessed.slice(-10).map((e=>e.toString())),isRunnable:this.isRunnable()}}doNotStartMoreWork(){return(0,E.ending)()||this.ended||(0,O.isPaused)()||this.p.isFull()||(0,A.isTooBusy)()||(0,I.doNotRun)(this)||0===this.pendingWorkCount()}}t.TaskList=U,s=new WeakMap,d=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,r=new WeakSet,n=function(){this.taskCount.unset()},a=async function(){(0,x.ee)().off("resume",w(this,f,"f"));const e=new M.AbortError((0,E.ending)()?"service ending":"TaskList ended");for(const t of w(this,s,"f"))t.l.reject(e);await this.p.awaitAll()},o=function(){(0,R.filterInPlace)(w(this,s,"f"),(e=>e.l.isPending())),W.Task.dbl.runf((e=>e.delete().where("retries","<",0))),w(this,r,"m",n).call(this)},l=function(){if(this.ended)return;if(w(this,r,"m",o).call(this),(0,R.isEmpty)(w(this,s,"f")))return;const e=W.Task.countTaskNames();for(const t of this.p.deferreds){const i=t.name;e[i]=(e[i]??0)+1}for(const t of w(this,s,"f"))(0,F.sum)(t.taskNames.map((t=>e[t]??0)))<=t.maxRemaining&&t.l.resolve()},u=function(){return(0,R.uniq)(this.currentTasks().filter((e=>e.isSerial)).map((e=>e.fn)))},c=function(){return this.currentTasks().map((e=>e.id))},h=function(e){return 0===e?[]:W.Task.ops().allf((t=>(t=W.Task.orderBy(t.distinct().whereNotIn("id",w(this,r,"m",c).call(this)).whereNotIn("fn",w(this,r,"m",u).call(this))),(0,V.gt0)(e)&&(t=t.limit(e)),t)))},g=function(){if(w(this,r,"m",n).call(this),w(this,p,"f").call(this),this.doNotStartMoreWork())w(this,m,"f").call(this);else{w(this,d,"f").call(this);const e=this.p.freeSlots(),t=w(this,r,"m",h).call(this,e);this.logger.debug("runChunk():",{freeSlots:e,next:t});for(const e of t)this.p.enqueue({name:this.name,payload:e,l:()=>w(this,r,"m",y).call(this,e),serialId:e.isSerial?e.fn:void 0})}w(this,r,"m",l).call(this)},y=async function(e){try{await(0,D.time)("task."+e.fn,e._run())}catch(t){this.logger.warn("Failed to run task",{task:e,error:t})}finally{this.maybeRunChunk()}},U.instance=(0,B.defer)((()=>(0,S.isTaskListManager)()?new U:void 0))},44834:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitWhenDone=void 0,t.ExitWhenDone="--exit-when-done"},21200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitWhenDoneArg=void 0;const r=i(28874),s=i(38639),n=i(44834);t.ExitWhenDoneArg={beforeParse:e=>e.option(n.ExitWhenDone,"Exit after jobs are completed. Defaults to false unless paths are specified on the command line."),afterParse:e=>{(0,s.isTrue)(e.exitWhenDone)&&(r.Settings.exitWhenDone.envValue=!0)}}},2775:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ForceArg=void 0;const r=i(28874),s=i(38639);t.ForceArg={beforeParse:e=>e.option("--force","Deletes prior cached directory metadata, and forces directory contents to be re-scanned."),afterParse:async e=>{(0,s.isTrue)(e.force)&&(r.Settings.forceSync.envValue=!0)}}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},12195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoFilterArg=void 0;const r=i(4175),s=i(38639);t.NoFilterArg={beforeParse:e=>e.option("--no-filter","Disables import filters. All paths will try to be imported, even if they are too small or are missing tags. See https://photostructure.com/faq/why-is-my-file-missing/ ."),afterParse:async e=>{(0,s.isFalse)(e.filter)&&(0,r.disableAllFilters)()}}},52288:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RebuildArg=void 0;const r=i(28874),s=i(38639);t.RebuildArg={beforeParse:e=>e.option("--rebuild","Rebuild your library by re-importing all your photos and videos (slow!) https://photostructure.com/faq/sync-vs-rebuild/"),afterParse:async e=>{(0,s.isTrue)(e.rebuild)&&(r.Settings.forceRebuildLibrary.envValue=!0)}}},46628:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(47783),c=i(97573),d=i(42231),h=i(40958),f=i(22573),m=i(68708),p=i(75020),g=i(54993),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function w(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function v(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(w));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...v(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...v(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=v},88224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(28874),o=i(42231),l=i(40958),u=i(20214),c=i(43487),d=i(46628),h=i(63175),f=i(4407),m=i(58886),p=i(32646),g=i(48144),y=i(60047),w=i(6186),v=i(42003),b=i(43723),S=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function P({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];if(t=(0,l.uniqBy)([e,...t],(e=>e.nativePath)),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,y.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),a.Settings.tagGeo.valueOrDefault)for(const e of t){const t=await(0,p.geoTagFile)(e);if(null!=t){u.push(t);break}}await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,b.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,g.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,v.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{S().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const P=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(w.normalizeTagRoot),o.joinTagPath)),M=await(0,w.tagDeltas)(i,P);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:P,result:M}),M}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await P({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=P},63175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(47783),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},4407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(47783),h=i(40958),f=i(55835),m=i(31586),p=i(75020),g=i(54993),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),w=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function v(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:v(e)})))}function M(e){if((0,m.within)(1,12,e))return(0,f.map)(w()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function _(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function T(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),M);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),w.unset()})),t.yearToOrdinal=v,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=M,t.dayTagRef=_,t.dateTag=T,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:T(r.date)}},58886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(19851),s=i(50213),n=i(42231),a=i(21404),o=i(40958),l=i(89937),u=i(75020),c=i(54017),d=i(94448),h=i(69032),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},32646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTagFile=t.geoTag=void 0;const r=i(48884),s=i(56519),n=i(50213),a=i(28874),o=i(47783),l=i(14245),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)((()=>(0,n.mkLogger)("curators.GeoTagger")));function p(e){const t=a.Settings.tagGeoMaxDistanceKm.valueOrDefault;if(t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t))return void m().warn("geoTag(): GeolocationDistance too large, skipping geo tag",(0,f.pickDeep)(e,...l.GeolocationFields));const i=a.Settings.tagGeoSynonyms.synonymMap(),s=a.Settings.tagGeoTemplate.valueOrDefault.map((t=>(0,r.first)(i.get(t)??[t],(t=>(0,f.pluckDeep)(e,t)?.value)))),n=(0,c.compactBlanks)(s);return m().tap({msg:"geoTag",result:0===n.length?void 0:(0,c.compact)([u.TagRoots.Where,...n]),meta:{picked:s}})}t.geoTag=p,t.geoTagFile=function(e){return(0,s.thenMap)((0,o.readTags)(e),p)}},48144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(47783),h=i(97573),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),w=i(96249),v=i(55835),b=i(75020),S=i(54993),P=i(6186),M=i(43723),_=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),T=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return _().tap({msg:"extractDashDashTags()",result:(0,v.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,v.mapOr)(T(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function D(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>T.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=D;const k=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(k,(e=>(i.push(e),"")));s.push(...(0,v.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,w.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function F(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function C(e,t){const[i,s]=(0,r.partition)(x(e),M.isWhoTag),n=(0,w.flatten)(i.map(M.nameTag)),a=(0,m.uniq)((0,w.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=F([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=F,t.processKeywords=C,t.keywordTagFiles=async function(e,t){return C([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,w.flatten)(e.map(D)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,w.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},60047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(56519),s=i(28874),n=i(47783),a=i(75020),o=i(40958),l=i(22573),u=i(55835);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},6186:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhereRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(50213),s=i(28874),n=i(42231),a=i(75020),o=i(40958),l=i(22573),u=i(45599);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.WhereRoot={name:a.TagRoots.Where,ordinal:5},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,t.WhereRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Where,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase()))),g=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhereRoot,...e.slice(1)]:g.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},42003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[w(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function w(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}t.friendlySubtype=y,t.fixCase=w},43723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(19851),s=i(50213),n=i(28874),a=i(47783),o=i(28630),l=i(66039),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(v)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function w(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function v(e){if(!(0,d.blank)(e))return Array.isArray(e)?(w(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=w,t.nameTag=v},98348:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(48884),d=i(19851),h=i(23560),f=i(25764),m=i(38836),p=i(99331),g=i(5916),y=i(12959),w=i(55332),v=i(91872),b=i(80632),S=i(51040),P=i(44955),M=i(15056),_=i(70025),T=i(57159),E=i(18454),D=i(28874),k=i(5233),x=i(42659),F=i(31586),C=i(68708),A=i(30976),I=i(17036),O=i(27134),L=i(35052);class R extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=x.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),D.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*x.secondMs),this.migrate_=(0,g.lazyAsync)({desc:"db.migrate",later:async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{await(0,O.verifyDb_)((()=>this.db))}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||D.Settings.dbForceRecover.valueOrDefault)&&(E.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new I.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e}}}),this.tableInfo_=(0,d.lazy)((()=>(0,L.localTableInfo)(this.db)))}toJSON(){return(0,C.pick)(this,"schema","dbFile")}get isOpen(){return!0===l(this,n,"f")?.open}get inTransaction(){return this.isOpen&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(t||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,b.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new T.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===D.Settings.dbAutoVacuumMode.valueOrDefault&&(0,F.gt0)(D.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%D.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&(this.logger.info("running incremental_vacuum..."),l(this,n,"f")?.pragma("incremental_vacuum")),l(this,n,"f")}async verify_(){await(0,O.verifyDb_)((()=>this.db))}assertHeartbeat_(){const e=(0,A.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{this.logger.info("closing db",l(this,n,"f")),await(0,k.retryOnReject_)((()=>{!0===l(this,n,"f")?.open&&l(this,n,"f")?.close()}),{timeoutMs:D.Settings.dbBusyTimeoutMs.valueOrDefault,maxRetries:5,errorIsRetriable:_.isSqliteBusyError,retryDelay:x.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,v.handleDbRetries_)("db.checkpoint",(()=>this.db),(()=>(0,O.checkpoint_)({db:this.db})),this.onRetry),await(0,v.handleDbRetries_)("db.optimize",(()=>this.db),(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,v.handleDbRetries_)("db.vacuum",(()=>this.db),(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,O.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,M.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,P.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,y.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,w.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=R,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,F.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},25470:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(66364),d=i(50213),h=i(23560),f=i(78406),m=i(25764),p=i(38836),g=i(99331),y=i(56038),w=i(12959),v=i(55332),b=i(76187),S=i(73209),P=i(28874),M=i(42659),_=i(75240),T=i(95700),E=i(22526),D=i(45648),k=5*M.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends f.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:M.minuteMs,rank:m.EndableRanks.db,endTimeoutMs:5*M.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new p.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),m.EndableRanks.postdb,k),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*M.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,D.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,D.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,T.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,y.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,w.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,v.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,_.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:k,endableRank:m.EndableRanks.postdb,noopIfContested:!1});(0,h.isDbManager)()&&await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,b.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),await this.db.closeDb()},o=function(){return this.ended||(0,g.ending)()||(0,c.isSuspended)()}},22526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(19851),s=i(50213),n=i(92407),a=i(55332),o=i(44955),l=i(15056),u=i(87290),c=i(98314),d=i(38835),h=i(73209),f=i(95696),m=i(17217),p=i(18454),g=i(57902),y=i(28874),w=i(2858),v=i(40958),b=i(22573),S=i(42659),P=i(94448),M=i(98348),_=i(45648),T=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,w._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function D(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function k(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function F(e=k(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw T().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,_.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=D,t.libraryDbInfoJsonFile=k,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=F,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:D(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await F(u,t);o=new M.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>T().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new M.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return T().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,v.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,_.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw T().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),i.release(),e}return T().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},86859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(54557),s=i(50213),n=i(99331),a=i(56038),o=i(65753),l=i(66184),u=i(70417),c=i(28874),d=i(40958),h=i(22573),f=i(45599),m=i(96249),p=i(31586),g=i(51926),y=i(57038),w=i(21074),v=(0,f.defer)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,y.knex)()(this.tableName)}prep(e,t=!1){const i=(0,w.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return v().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&v().log((0,l.defaultLogLevel)(),i+"(): "+(0,w.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;v().throw(t,{method:i,...(0,w.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,a.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,g.replaceAll)((0,g.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,w.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,m.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}async batched(e){let t,i=0;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,o.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&(await e.onResults(t),i+=t.length)}while((0,d.isNotEmpty)(t)&&!(0,n.ending)()&&(null==e.maxResults||e.maxResults>i));return{resultCount:i,done:null==t||t.length<(0,o.maxBatchPluckSize)()}}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}async pluckBatched(e){let t=0;const i=(0,u.min)([e.limit??(0,o.maxBatchPluckSize)(),e.maxResults]);if(i<=0||(0,p.lte0)(e.maxResults))return{done:!1,resultCount:t};let r;for(;null==e.maxResults||e.maxResults<=0||t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},36908:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(42231),o=i(40958),l=i(76790),u=i(23838),c=i(31586),d=i(54993),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},57038:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(31832)),n=i(19851),a=i(56519),o=i(55835),l=i(68708);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},17036:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(77598),l=i(19851),u=i(50213),c=i(7282),d=i(37805),h=i(4867),f=i(51040),m=i(77740),p=i(38835),g=i(8769),y=i(57159),w=i(34102),v=i(73209),b=i(95696),S=i(43899),P=i(18454),M=i(28874),_=i(40958),T=i(42659),E=i(41400),D=i(98553),k=i(55835),x=i(34666),F=i(32639),C=i(45648),A=i(94715),I=i(27134);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,A.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,_.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,D.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,v.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:M.Settings.dbMaintenanceTimeoutMs.valueOrDefault},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=A.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,F.isFunction)(s);return o?await s.bind(A.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.info("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,w.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),(0,c.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{if((0,m.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(T.secondMs,3*T.secondMs)),await(0,k.map)(e,(e=>e(r))),await(0,h.thenOrTimeoutError)({p:this.applyMigration_(r,i),timeoutMs:5*M.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch((e=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,C.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile(),r=(0,f.splitBatchSql)(i);if((0,_.isEmpty)(r))this.logger.info("No-op migration: "+e);else{t&&this.db.pragma("foreign_keys = OFF");for(const t of r)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,I.foreignKeyCheck_)(this.db)}}finally{t&&this.db.pragma("foreign_keys = ON")}}},94715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(97352),o=i(68852),l=i(81168),u=i(85810),c=i(42022),d=i(1971),h=i(79842),f=i(89724),m=i(17415),p=i(88600),g=i(20014),y=i(42231),w=i(87001),v=i(40958),b=i(55835),S=i(31586),P=i(97790),M=i(89937),_=i(54993),T=i(7656),E=i(36908),D=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),k=new RegExp(`^(${(0,o.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function F(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function C(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())D().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)}function A(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>k.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=F,t.fix_root_tags=C,t.isoToPrecisionMs=A,t.Migrations={fix_root_tags:C,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},A),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},w.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,_.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},F),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();D().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,v.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));D().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:T.rebuildTagAssetCounts,create_tag_fts:e=>{e.exec("DROP TABLE IF EXISTS tag_fts"),e.exec("CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize=\"unicode61\");")},rebuild_null_island:e=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,y.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")}}},27134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(14121),s=i(19851),n=i(50213),a=i(84777),o=i(12959),l=i(5531),u=i(91872),c=i(99315),d=i(76187),h=i(51040),f=i(38835),m=i(57159),p=i(29882),g=i(95696),y=i(89966),w=i(38156),v=i(28874),b=i(63870),S=i(5233),P=i(42659),M=i(41400),_=i(50357),T=i(98553),E=i(56409),D=i(31586),k=i(20214),x=i(51926),F=i(12168),C=i(59455),A=i(54993),I=i(94448),O=i(9508),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){L().debug("pragmaOrThrow_()",{db:N(e),db_open:e?.open,pragma:t,okResult:i});const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,_.eql)(r,i)||L().throw(`${t} failed for ${N(e)}: ${(0,T.stringify)({result:r})}`)}function N(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}function B(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function j(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function z(e){const t=(0,C.toA)(e.pragma("foreign_key_check"));t.length>v.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:v.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function V(e){await(0,u.handleDbRetries_)("db.quickCheck",e,B),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",e,j),await(0,M.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",e,z)}function W(e){return(0,O.withDbSync)(e,V,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,C.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,D.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,I.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=B,t.integrityCheck_=j,t.foreignKeyCheck_=z,t.verifyDb_=V,t.verifyDbFile_=W,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=v.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,C.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,D.gt0)(n?.busy)&&i>0?(await(0,M.delay)(250),e({db:t,retries:i-1})):n};const U=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*F.MiB,await(0,d.sqliteSizeBytes)(i)),n=new w.PushProgressObserver({path:(0,A.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,A.toS)(e);U.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),await W(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,k.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,k.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},21074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(48884),s=i(68852),n=i(81168),a=i(12943),o=i(96249),l=i(98553),u=i(31586),c=i(68708),d=i(32639),h=i(54993);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},35052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(22573),s=i(23838);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},9508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(80632),s=i(28874),n=i(30301),a=i(54993);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)((()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i})));try{return t((function(){const e=o();return e.open?e:o.refresh()}))}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const n=(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i});try{return await t(n)}finally{n.close()}}},43487:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(48884),c=i(19851),d=i(50213),h=i(88158),f=i(45393),m=i(56519),p=i(89724),g=i(38835),y=i(74128),w=i(79847),v=i(28874),b=i(47783),S=i(38010),P=i(40958),M=i(76790),_=i(75761),T=i(38639),E=i(11371),D=i(98553),k=i(55835),x=i(31586),F=i(20214),C=i(59455),A=i(64526),I=i(4407),O=i(54017),L=i(48722),R=i(37094),N=i(45295),B=i(39604),j=i(48723),z=i(41507),V=i(72761),W={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class U extends V.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,b.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,T.isTrue)(t.shown)})}const t=R.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(W):e.andWhere(W)}static findUnhiddenById(e){return(0,x.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return A.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{unlinkAssetFiles:i});const l=n.getAssetFiles({refresh:!0});if(t){(0,B.upsertToShaBlockslist)(...l.map((e=>e.sha)));for(const e of l)(0,y.syncReport)().onProgress({from:"Asset.remove",path:await e.getNativePath()??e.uri,state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}N.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),R.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&j.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,w.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(N.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,k.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,x.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,x.gte)(this.rating,v.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,L.toAssetId)(this)}renderCaption(e){return(0,k.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:j.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,P.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return j.Tag.ops().all(j.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??N.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:j.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:j.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,P.uniq)((0,C.toA)(e.tagIdsToAdd).filter((e=>(0,x.gt0)(e)&&!t.includes(e)))),r=(0,P.uniq)((0,C.toA)(e.tagIdsToRemove).filter((e=>(0,x.gt0)(e)&&t.includes(e))));if((0,P.isEmpty)(i)&&(0,P.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&j.Tag.deltaAssetCountAndAncestors(t,-1),(0,P.isEmpty)(i)||N.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,P.isEmpty)(r)||N.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,P.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&j.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,z.coalesceStreams)((0,P.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,M.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,T.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,x.gt0)(this.id)&&(0,x.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,D.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,T.isTrue)(e.shown)))??this.getAssetFiles({refresh:!0})?.find((e=>(0,T.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,F.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,_.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,E.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,_.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,_.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,F.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,C.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,k.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,x.gte)(this.rating,v.Settings.likeRating.valueOrDefault),hidden:(0,T.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=U,s=U,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("Asset.version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},U.$tableName="Asset",U.$uniqueColumnName="id",U.$booleanFields=["shown","hidden"]},54017:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(76760),o=i(19851),l=i(88158),u=i(45393),c=i(68852),d=i(81168),h=i(13991),f=i(54296),m=i(56519),p=i(76490),g=i(89724),y=i(98314),w=i(38835),v=i(8769),b=i(29882),S=i(95696),P=i(62105),M=i(74128),_=i(35721),T=i(69589),E=i(28874),D=i(28544),k=i(16170),x=i(45200),F=i(34238),C=i(87001),A=i(42233),I=i(21404),O=i(40958),L=i(17586),R=i(22573),N=i(38639),B=i(42659),j=i(33374),z=i(50357),V=i(75240),W=i(11371),U=i(55835),q=i(31586),H=i(68708),G=i(34666),$=i(89937),J=i(75020),K=i(64526),Z=i(41844),Y=i(43487),X=i(48723),Q=i(94710),ee=i(72761);class te extends ee.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>F.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=Y.Asset.shownUnhidden(e.q).join("AssetFile","AssetFile.assetId","Asset.id").where("AssetFile.version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("AssetFile.updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("AssetFile.mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("AssetFile.uri",i+"%");return t})).orderBy("AssetFile.id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,A.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,A.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("AssetFile.id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,q.gt0)(e)?te.ops().first(Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=Y.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,R.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(te.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=te.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=te.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:te.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,H.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith($.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,H.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,U.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,C.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,q.closeTo)(i.mtime,this.mtime,2*B.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return E.Settings.forceSync.valueOrDefault?E.Settings.forceSync.key+"=true":this.version!==u.AssetFileVersion?"AssetFileVersion: "+this.version+" != "+u.AssetFileVersion:this.whyNotMatchesFile(e)}async inSyncWithFile(e){const t=await this.whyNotInSyncWithFile(e);return this.logger().tap({msg:"inSyncWithFile()",result:null==t,meta:{whyNotInSync:t}})}async fileFields_(e){const t=e??await this.posixFile_();return null==t?void 0:await(0,h.assetFileStatFields_)(t)}isInLibrary(){return this.uri.startsWith($.PS_LIBRARY_PROTOCOL)}async isNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){const t=await this.whyNotNoop(e);return this.logger().tap({msg:"isNoop()",result:null==t,meta:{whyNotNoop:t}})}async whyNotNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){if(!0===e.forceSync)return"forceSync is true";if(!(0,q.gt0)(this.id))return"missing .id";if(!(0,q.gt0)(this.assetId))return"missing .assetId";{const e=await this.whyNotInSyncWithFile();if(null!=e)return e}if(await(0,Z.mayCopyAssetsToLibrary)()){const e=K.Library.instanceRequired_().assetFileRepository(),t=e.whyNotCopyFile(await this.posixFile_());if((0,R.blank)(t)&&null==await e.existingLibraryAssetFile(this))return"need to copy into library"}this.syncState=M.AssetFileSyncStates.noop}isVersionUpToDate(){return(0,G.gte)(this.version,u.AssetFileVersion)}async siblingCount(){return te.dbl.pluckFirstf((e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=(0,T.forceContextOrSetting)()){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,q.gt0)(this.id)&&!t.forceSync)return void(null==this.syncState&&(this.upsert(),this.syncState??(this.syncState=M.AssetFileSyncStates.noop)));const i=await this.isFileDeleted();if(!0===i)return this.syncState=M.AssetFileSyncStates.deleted,this.delete(),!0!==t.skipAssetRepair&&Q.Task.addOne("repairAsset",{assetId:this.assetId}),this;if(!1===i){const i=await this.updateFromFile_(e,t);return this.syncState??(this.syncState=null==i?M.AssetFileSyncStates.noop:M.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=M.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,H.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e,t=(0,T.forceContextOrSetting)()){const i=Date.now(),r=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&!0!==t.forceSync&&await this.matchesFile(e))return void r.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=M.AssetFileSyncStates.deleted,void r.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,R.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,H.assignAllFields)(this,(0,H.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=M.SyncFileStates.synced,r.elapsed("finished",Date.now()-i,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,H.assignFields)(this,(0,H.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...te.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,q.gt0)(this.assetId)?Y.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,x.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,R.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,C.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,R.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,R.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+w.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),D.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,_.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,j.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,N.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===W.ReducerNames.fit)).map((e=>(0,_.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,v.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=F.URI.parse(this.uri),t=(0,U.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>X.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=F.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,L.at)((0,L.at)(e,-1)?.tagPath,-1)}(0,z.eql)(e[0]?.tagPath,[J.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===$.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,L.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===J.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===$.PS_LOCAL_FILE_SCHEME){const t=F.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,H.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,N.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:ie(this.createdAt),updatedAtLocale:ie(this.updatedAt)})))}get isVideo(){return(0,k.isVideoMimeType)(this.mimetype)}}function ie(e){return(0,U.map)(e,(e=>(0,V.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=te,r=new WeakSet,s=function(){if((0,R.blank)(this.uri))return"blank uri";if((0,R.blank)(this.sha))return"blank sha";if(!(0,q.gt0)(this.width))return"missing width";if(!(0,q.gt0)(this.height))return"missing height";if(!(0,q.gt0)(this.capturedAtLocal))return"missing capturedAtLocal";if(!(0,q.gte0)(this.capturedAtPrecisionMs))return"missing capturedAtPrecisionMs";if(E.Settings.useImageHashes.valueOrDefault){const e=[];for(const t of["dctHash","diffHash","meanHash"])(0,R.blank)(this[t])&&e.push(t);if(1===e.length)return"missing image hash: "+e[0];if(e.length>1)return"missing image hashes: "+e.join(", ")}return this.isVersionUpToDate()?void 0:"outdated version"},te.$tableName="AssetFile",te.$uniqueColumnName="uri",te.$booleanFields=["shown"],te.$transientFields=["nativePath","syncState"]},48722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(76596),s=i(31586);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},37094:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},45295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},61204:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(19851),s=i(50213),n=i(97352),a=i(75020),o=i(4407),l=i(48723),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},95700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(19851),s=i(56038),n=i(28874),a=i(42659),o=i(41400),l=i(69032),u=i(61204),c=i(49796);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h());try{await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())}catch{}};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},55046:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(57975),n=i(50213),a=i(7282),o=i(65211),l=i(40958),u=i(38639),c=i(45599),d=i(31586),h=i(68708),f=i(34666),m=i(54993),p=i(57038),g=i(94448),y=i(33572),w=i(63872);class v{constructor(){this.$instanceId=(0,a.isTest)()?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new w.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if((0,a.isProd)())throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}update(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("update()",{self:this.toJSON()}),this.class().ops().updateOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=v,r=v,v.$schema="models",v.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),v.db=g.modelDb,v.$pkColumnNames=["id"]},94448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},33572:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(50213),s=i(40958),n=i(22573),a=i(38639),o=i(97790),l=i(51926),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},63872:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(48884),m=i(19851),p=i(50213),g=i(81168),y=i(48299),w=i(12943),v=i(38835),b=i(34102),S=i(28874),P=i(40958),M=i(76790),_=i(22573),T=i(50357),E=i(96249),D=i(98553),k=i(55835),x=i(31586),F=i(68708),C=i(59455),A=i(86859),I=i(33572);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,I.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new A.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,D.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,D.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,k.mapOr)(this.db(),(e=>e.isOpen),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,w.toDbValued)(t);return(0,F.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,F.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,C.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,M.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,C.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,D.stringify)(e)+v.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+v.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,k.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,D.stringify)(e)+v.NonRetriableErrorFlag+v.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,_.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,_.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);if(null==s)return;return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,D.stringify)(e))}reload(e){const t=[],i=this.allf((i=>{for(const r of e){const e=this.model.hasId(r)?this.model.pickId(r):this.$pickModelUcn(r);null!=e?(t.push([r,e]),i=i.orWhere(e)):h(this,s,"f").warn("reload(): given insufficient partial model",{fragment:r})}return i})),n=[];for(const[e,a]of t){const t=i.find((e=>(0,T.eqlSubset)(a,e)));if(null==t)h(this,s,"f").warn("reload(): failed to find result in db",{prior:e,dbArr:i});else{const i=h(this,r,"m",u).call(this,e);h(this,r,"m",l).call(this,i,t),i!==e&&h(this,r,"m",l).call(this,i,t),n.push(t)}}return n}upsert(e){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const t=this.columnNames(),i=[];for(const s of(0,f.batches)((0,C.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=new Map,n=new Set,a=(0,P.compact)(s.map((e=>this.fromJSON(e))));for(const t of a){const i=(0,D.stringify)(this.$pickModelUcn(t));e.set(i,t),this.model.hasId(t)||n.add(i),t.$beforeUpsert()}h(this,r,"m",c).call(this,a.map((e=>e.$toDbJSON(t))));const o=this.reload(a),l=new Map(o.map((e=>[(0,D.stringify)(this.$pickModelUcn(e)),e])));for(const e of a){const t=(0,D.stringify)(this.$pickModelUcn(e)),r=l.get(t)??e;n.has(t)&&r.$afterInsert(),r.$afterUpsert(),i.push(r)}}return i}delete(e){const t=(0,C.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,F.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,D.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,F.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},20958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(19851),s=i(50213),n=i(88158),a=i(99331),o=i(70025),l=i(8769),u=i(22573),c=i(98553),d=i(50989),h=i(72761);t.OperationNames=(0,d.strEnum)("rebuildLibrary","forceRestartSync");const f=(0,r.lazy)((()=>(0,s.mkLogger)("model.Operation")));class m extends h.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(m.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return m.getFirstPendingOp(e)??m.ops().insertOne(e)}static getFirstPendingOp(e){return f().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,u.blank)(e?.name)?f().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return f().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce_(e,t,i=n.identity){const r=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=r)return void f().debug("applyOnce(): already done",{priorCompleted:r});const s=this.ops().insertOne(e);try{const e=await t(s);return(0,a.ending)()||s.markCompleted(),e}catch(t){if((0,o.isRedoableError)(t))return void f().info("applyOnce(): redoable error",{crit:e,error:t});throw(0,l.onError)("Operation.applyOnce(): "+(0,c.stringify)(e),t),t}}markCompleted(){null==this.completedAt&&(this.completedAt=Date.now(),this.upsert())}}t.Operation=m,m.$tableName="Operation",m.$uniqueColumnName="id",m.$useCache=!1},49796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.toPct=void 0;const r=i(48161),s=i(1708),n=i(48884),a=i(50213),o=i(28874),l=i(40958),u=i(42659),c=i(45599),d=i(98553),h=i(55835),f=i(31586),m=i(68708),p=i(67478),g=i(51926),y=i(59455),w=i(54993),v=i(76386),b=i(33572),S=i(55009),P=i(72761),M=(0,c.defer)((()=>(0,a.mkLogger)("model.Progress")));function _(e){return null==e||!(0,f.isNumber)(e)||e<0||e>100?void 0:(0,f.sigFigs)(e,3)}t.toPct=_;const T=(0,g.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function E(){const e=o.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*u.dayMs}t.defaultMinCreatedAt=E;class D extends P.TimestampedModel{static vacuum(e=o.Settings.progressRetentionDays.valueOrDefault*u.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t)));for(const e of(0,n.batches)(i,o.Settings.dbBatchSelectSize.valueOrDefault))S.ProgressMeta.dbl.runf((t=>t.whereIn("progressId",e).delete())),D.dbl.runf((t=>t.whereIn("id",e).delete()))}static countCompletedDirectorySyncs(){return this.dbl.pluckFirstf((e=>e.where({state:"done"}).whereNotNull("completedAt").where("uri","like","ps%")))}static times(){return M().tap({msg:"times()",result:this.dbl.all({sql:T})})}static insertNew(e){const t=(0,h.map)(e.dek,d.stringify);return this.ops().insertOne({...(0,m.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&this.assignFromPojo(e),super.upsert()}$beforeUpsert(){super.$beforeUpsert(),null==this.id&&(this.pid??(this.pid=s.pid),this.hostname??(this.hostname=(0,r.hostname)())),"done"===this.state&&(this.completedAt??(this.completedAt=Date.now())),this.completePct=_(this.completePct),this.incompletePct=_(this.incompletePct),this.scanningPct=_(this.scanningPct)}$afterUpsert(){super.$afterUpsert(),(0,v.tellWebProgressUpdated)()}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,l.compactBlanks)((0,p.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,d.stringify)((0,l.compactBlanks)((0,y.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,m.omit)(e,"volume","uri"))}getMeta(){return S.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncomplete(e=E()){return this.logger().tap({msg:"priorIncompleteProgress()",result:D.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc")))})}getLastCompletedAt(e=E()){return D.dbl.pluckFirstf((t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e)))}getLastIncompleteStartAt(){return D.dbl.pluckFirstf((e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0)))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),S.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,l.diff)(t.map((e=>e.name)),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),S.ProgressMeta.ops().upsert((0,m.entries)(e).map((([e,t])=>({progressId:this.id,name:e,value:(0,w.toS)(t)})))),(0,l.isNotEmpty)(i)&&S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).whereIn("name",i).delete()))}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),S.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,m.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=D,D.$tableName="Progress",D.$uniqueColumnName="id"},55009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},39604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(19851),s=i(50213),n=i(95696),a=i(40958),o=i(22573),l=i(86859),u=i(94448),c=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),d=(0,r.lazy)((()=>new l.DbRequest(u.modelDb,"ShaBlocklist")));function h(e){return null!=(0,u.modelDb)()&&!(0,o.blank)(e)&&c().tap({msg:"isShaBlockslisted",result:null!=d().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}function f(...e){if(null==u.modelDb.prior())return;const t=(0,a.uniq)(e).map((e=>({sha:e})));return(0,a.isEmpty)(t)?void 0:d().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,u.modelDb)())return null;const t=h(await n.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=h,t.upsertFileToShaBlockslist=async function(e){if(null==(0,u.modelDb)())return;const t=await n.PosixFile.for(e).sha();return null==t?void 0:f(t)},t.upsertToShaBlockslist=f},48723:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(56038),o=i(34102),l=i(19851),u=i(50213),c=i(36372),d=i(97352),h=i(28874),f=i(81168),m=i(42231),p=i(75020),g=i(40958),y=i(22573),w=i(42659),v=i(41400),b=i(50357),S=i(55835),P=i(31586),M=i(34666),_=i(20214),T=i(51926),E=i(59455),D=i(12168),k=i(6186),x=i(57038),F=i(21074),C=i(7656),A=i(43487),I=i(48722),O=i(45295),L=i(98784),R=i(41507),N=i(72761),B=4*w.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,v.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:A.Asset.dbl.pluckFirst(A.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset(),this.ops().clearDbCache()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{r.clear();for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.update({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,T.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,F.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:C.RecursiveAssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),this.ops().upsertOne(i)}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return A.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,_.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();return(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)})),r.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,T.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(A.Asset.dbl.all(t).map(I.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return A.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,D.fmt)(e.length)+" of ")+(0,D.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,T.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:C.RecursiveAssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?A.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(A.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(I.toAssetId))));for(const t of r)t.assetIdA.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(this.id??0),"Asset.id",i)).limit(t))).map(I.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!0,z.cmp=(e,t)=>(0,M.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=A.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(k.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e}),B);const V=(0,l.lazy)((()=>A.Asset.dbl.pluckFirstf((e=>e.count()))),w.minuteMs)},98784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(38156),s=i(3127),n=i(40958),a=i(41400),o=i(94715),l=i(55046),u=i(48723);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=new r.PushProgressObserver({op:"Rebuilding tag search index"},u.Tag.dbl.pluckFirstf((e=>e.count("*")))),t=this.dbl.db();o.Migrations.create_tag_fts(t.db),await u.Tag.ops().batched({qb:e=>e,onResults:t=>(this.$logger().throwIfAborted_(),this.insertFts(t),e.incrProgress(t.length),(0,a.delay)(1))}),e.completed()}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},41507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},94710:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Task=t.StaleTaskError=t.InvalidTaskError=t.TaskNames=t.Tasks=t.testTask=void 0;const c=i(78474),d=i(22454),h=i(23560),f=i(12089),m=i(76740),p=i(22911),g=i(99331),y=i(31562),w=i(38835),v=i(70025),b=i(8769),S=i(74128),P=i(28874),M=i(37692),_=i(40958),T=i(22573),E=i(42659),D=i(45599),k=i(98553),x=i(49769),F=i(68708),C=i(50989),A=i(59455),I=i(58723),O=i(34274),L=i(90901),R=i(61989),N=i(93755),B=i(69032),j=i(55046);t.testTask=(0,f.shim1)({name:"testTask",impl:async e=>{}}),t.Tasks={applyDeleted:I.applyDeleted,applyExcluded:I.applyExcluded,runTagMaintenance:B.runTagMaintenance,updateAssetFile:N.updateAssetFile_,repairAsset:async function(e){e.forceSync=!0,e.skipPreviews=!0,e.skipAssetTagging=!0;const t=await(0,R.updateAsset_)(e);return(0,_.isNotEmpty)(t?.assetIdsToUpdate)&&q.add(t?.assetIdsToUpdate.map((t=>({fn:"repairAsset",args:{...e,assetId:t},priority:W.repairAsset+1})))),null!=t&&!0!==t.deleted&&(0,T.blank)((0,A.toA)(t.rejected).join(""))&&(0,T.blank)(t.error)&&q.addOne("assetPostUpsertTasks",(0,F.omit)(e,"skipPreviews","skipAssetTagging")),t},assetPostUpsertTasks:L.assetPostUpsertTasks,syncFile:O.importFileToResult_,testTask:t.testTask},t.TaskNames=(0,C.strEnum)(...(0,F.keys)(t.Tasks));class z extends Error{}t.InvalidTaskError=z;class V extends Error{}t.StaleTaskError=V;const W={applyDeleted:16,applyExcluded:16,runTagMaintenance:14,updateAssetFile:13,repairAsset:12,assetPostUpsertTasks:10,syncFile:0,testTask:-1},U=["repairAsset"];class q extends j.Model{constructor(){super(...arguments),r.add(this),o.set(this,(0,D.defer)((()=>new m.Abortable)))}static countTaskNames(){const e={};for(const t of s.dbl.allf((e=>e.select("fn").count().groupBy("fn"))))e[t.fn]=t["count(*)"];return e}static orderBy(e){return e.orderBy([{column:"priority",order:"desc"},{column:"retries",order:"desc"},{column:"id",order:"asc"}])}static count(){return s.dbl.pluckFirstf((e=>e.count("id")))}static freeSlots(){return P.Settings.taskListCap.valueOrDefault-s.count()}static countByFn(e){return s.dbl.pluckFirstf((t=>t.where({fn:e}).count("id")))}static nextByFn(e,t=(e=>e)){return s.ops().allf((i=>s.orderBy(t(i.where({fn:e})))))}set args(e){this.argsJSON=(0,k.stringify)(e)}get args(){const e=(0,k.parseJSON)(this.argsJSON);return(0,F.notEmptyObj)(e)&&(e.halt=u(this,o,"f").call(this)),e}get isSerial(){return U.includes(this.fn)}toString(){return`Task#${this.fn}(${this.argsJSON})`}static addOne(e,t){return s.add([{fn:e,args:t}])[0]}static add(e,t=!1){if((0,_.isEmpty)(e))return[];const i=s.ops().upsert(e.map((e=>({fn:e.fn,argsJSON:(0,k.stringify)(e.args)})),t));return s.ee.emit("added",i),(0,h.isTaskListManager)()||(0,M.addStateEvent)("checkTasks"),i}$beforeUpsert(){this.priority??(this.priority=W[this.fn]),this.retries??(this.retries=P.Settings.maxRetries.valueOrDefault)}donePromise(){return(0,h.isTaskListManager)()?(0,x.getOrSet)(u(s,s,"f",n),this.id,(()=>new p.Deferred(this.toString(),{payload:this}))):(0,y.untilTrue)((()=>null==s.ops().findById(this.id)),{intervalMs:E.secondMs})}abort(e){this.logger().warn("aborting task",{reason:e,task:this}),u(this,o,"f").call(this).abort(e),this.delete(),(0,T.blank)(this.args.path)||(0,S.syncReport)().onProgress({path:this.args.path,from:this.fn,state:S.SyncFileStates.failed,details:e})}async _run(){if(this.retries<0)throw this.logger().warn(".run(): too many retries"+w.InternalErrorFlag,{job:this}),this.delete(),new z;if(!u(this,r,"m",l).call(this))throw this.logger().warn(".run(): someone already started this task",{job:this}),new V;try{const e=Date.now(),i=await t.Tasks[this.fn](this.args);return this.logger().throwIfAborted_(u(this,o,"f").prior()),s.taskResolvedCounts.incr(this.fn),s.ee.emit("resolved",this,i,Date.now()-e),this.delete(),u(s,s,"f",n).get(this.id)?.resolve(i),i}catch(e){if((0,g.ending)())throw this.logger().info("task failed, but we're ending. We'll leave it for next time.",{task:this}),e;throw s.taskRejectedCounts.incr(this.fn),(0,v.isRedoableError)(e)?(this.retries++,this.priority--,this.upsert()):!0===(0,v.isRetriableError)(e)&&this.retries>=0?this.logger().warn("run failed, but we can retry it later",{task:this,error:e}):(s.ee.emit("rejected",this,e),this.delete(),u(s,s,"f",n).get(this.id)?.reject(e),(0,b.onError)(this.toString()+" failed",e)),e}finally{u(s,s,"m",a).call(s)}}}t.Task=q,s=q,o=new WeakMap,r=new WeakSet,a=function(){for(const[e,t]of u(this,s,"f",n).entries())t.isSettled&&u(this,s,"f",n).delete(e)},l=function(){const e=this.retries;if(1===s.dbl.runf((t=>t.where({id:this.id,retries:e}).update({retries:e-1}))).changes)return--this.retries,!0;{const e=this.toJSON(),t=this.reload();return this.logger().warn(".#decrRetries(): someone already started this task",{before:e,reloaded:t}),!1}},q.$tableName="Task",q.$uniqueColumnName="fn,argsJSON",q.$useCache=!1,q.taskResolvedCounts=new d.CountingSet,q.taskRejectedCounts=new d.CountingSet,q.ee=new c.EventEmitter,n={value:new Map}},72761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),this.createdAt??(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},58723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyExcluded=t.applyDeleted=void 0;const r=i(50213),s=i(43487),n=(0,r.mkLogger)("ops.ApplyRemovable");async function a(e,t,i){const r=e?"Deleting":"Excluding",a=e?"deletedAt":"excludedAt";await s.Asset.dbl.batched({qb:e=>e.select("id").where("shown",0).andWhere(a,"<=",t),onResults:async t=>{for(const a of t){n.throwIfAborted_(i);try{await s.Asset.remove({assetId:a,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){n.error(r+" failed",{assetId:a,error:e})}}}})}t.applyDeleted=function(e){return a(!0,e.createdAt,e.halt)},t.applyExcluded=function(e){return a(!1,e.createdAt,e.halt)}},76386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)((()=>(0,s.mkLogger)("progress.Progress")));t.ProgressRateMs=(0,r.lazy)((()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:1.5))),t.tellWebProgressUpdated=(0,r.lazy)((async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch((e=>h().warn(".tellWebProgressUpdated: failed",{error:e})))}),(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},22968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeRebuildLibrary=t.forceRebuildLibraryLater=t.rebuildLibraryOperationCrit=void 0;const r=i(45393),s=i(28874),n=i(98553),a=i(43487),o=i(54017),l=i(20958),u=i(33567);function c(){return{name:l.OperationNames.rebuildLibrary,value:(0,n.stringify)({AssetVersion:r.AssetVersion,AssetFileVersion:r.AssetFileVersion})}}t.rebuildLibraryOperationCrit=c,t.forceRebuildLibraryLater=function(){a.Asset.dbl.runf((e=>e.update({version:0}))),o.AssetFile.dbl.runf((e=>e.update({version:0}))),l.Operation.dbl.runf((e=>e.where(c()).delete()))},t.maybeRebuildLibrary=async function(){return s.Settings.skipLibraryRebuild.valueOrDefault?void 0:l.Operation.applyOnce_(c(),(()=>(new u.LibraryRebuild).doneLatch))}},33567:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LibraryRebuild=void 0;const c=i(19851),d=i(83412),h=i(25764),f=i(8769),m=i(76752),p=i(28874),g=i(15674),y=i(22573),w=i(42659),v=i(31586),b=i(12168),S=i(12236),P=i(35580),M=i(49796),_=i(94710),T=i(18209);class E extends d.DoneWrapper{constructor(){super("LibraryRebuild",(()=>u(this,r,"m",a).call(this)),h.EndableRanks.first),r.add(this),this.assetFileEta=new m.ETA,this.assetEta=new m.ETA,this.assetFilesUpdated=0,this.assetsUpdated=0,this.initialAssetTodoCount=(0,T.outdatedAssetCountSync)(),this.initialAssetFileTodoCount=(0,T.outdatedAssetCountSync)(),this.assetFileTodo=(0,c.lazy)((()=>(0,T.outdatedAssetFileCountSync)()),5*w.secondMs),s.set(this,(0,c.lazy)((()=>M.Progress.insertNew({uri:S.RebuildingURI,volume:"🔄",scanningPct:0})))),o.set(this,((e,t,i)=>{"updateAssetFile"===e.fn?(this.assetFilesUpdated++,this.assetFileEta.push(i),u(this,r,"m",n).call(this)):"repairAsset"===e.fn&&(this.assetsUpdated++,this.assetEta.push(i),u(this,r,"m",n).call(this))})),_.Task.ee.on("resolved",u(this,o,"f")),this.doneLatch.observe(u(this,r,"m",l).call(this))}assetTodo(){return(0,T.outdatedAssetCountSync)()}}t.LibraryRebuild=E,s=new WeakMap,o=new WeakMap,r=new WeakSet,n=async function({force:e=!1,done:t=!1}={}){const i=u(this,s,"f").call(this);if(e||!(0,v.gt)(i.updatedAt,Date.now()-w.secondMs))if((t??this.isDone())&&"done"!==i.state){const e=[];this.assetFilesUpdated>0&&e.push(`Updated file metadata for ${(0,b.fmt)(this.assetFilesUpdated)} files (roughly ${(0,b.fmt)(this.assetFileTodo())} remain).`),this.assetsUpdated>0&&e.push(`Refreshed ${(0,b.fmt)(this.assetsUpdated)} assets (roughly ${(0,b.fmt)(await this.assetTodo())} remain).`),i.dek=e,i.upsert({state:"done",hed:"Finished rebuilding your library 🎉",completePct:100,incompletePct:0,scanningPct:0})}else{let e="Rebuilding your library";const t=this.assetFileTodo(),r=await this.assetTodo(),s=(this.assetFileEta.etaMs(t/(0,g.maxConcurrentImports)())??0)+(this.assetEta.etaMs(r)??0),n=[];t>0&&n.push(`Updating file metadata (${(0,b.fmt)(this.assetFilesUpdated)} processed)`),r>0&&n.push(`Refreshing assets and previews (${(0,b.fmt)(this.assetsUpdated)} processed`);const a=t+r,o=this.assetFilesUpdated+this.assetsUpdated,l=(0,v.clamp)(0,100,Math.round(o/(a+o)*100)),u=(0,m.fmtEstimate)(s);(0,y.notBlank)(u)&&(e+=", "+u+"…"),i.dek=n,i.upsert({state:"processing",hed:e,completePct:l,incompletePct:100-l,scanningPct:0})}},a=function(){_.Task.ee.off("resolved",u(this,o,"f"))},l=async function(){this.logger.info("Starting library rebuild...");const e=p.Settings.forceFilters.getState();try{p.Settings.forceFilters.envValue=!0;const e=P.TaskList.instance(),t=await this.assetFileTodo(),i=await this.assetTodo();if(this.logger.info(".run()",{assetFileTodo:t,assetTodo:i}),0===t&&0===i)return;let s=!1;for(;!s;)s=(await(0,T.enqueueAssetFileUpdates)()).done,this.logger.info("run(): waiting for asset updates to complete..."),await e.awaitDrain(["updateAssetFile"],s?0:p.Settings.taskListCap.valueOrDefault/2);for(s=!1;!s;)s=(await(0,T.enqueueAssetUpdates)()).done,await e.awaitDrain(["repairAsset","assetPostUpsertTasks"],s?0:p.Settings.taskListCap.valueOrDefault/2);await u(this,r,"m",n).call(this,{done:!0,force:!0}),this.logger.info("rebuild complete!")}catch(e){(0,f.onError)("LibraryUpdater.run() failed",e)}finally{p.Settings.forceFilters.setState(e)}}},18209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.enqueueAssetUpdates=t.outdatedAssetCount=t.enqueueAssetFileUpdates=t.outdatedAssetFileCountSync=t.outdatedAssetCountSync=t.outdatedAssetFileCount=t.currentUriRoots=void 0;const r=i(50213),s=i(45393),n=i(70417),a=i(45200),o=i(5696),l=i(7014),u=i(40958),c=i(45599),d=i(41400),h=i(20214),f=i(54993),m=i(43487),p=i(54017),g=i(94710),y=(0,c.defer)((()=>(0,r.mkLogger)("sync.UpdateQueue")));async function w(){return[...await(0,h.thenCollect)((0,l.volumes)(),(async e=>(0,a.nativePath2uri)(e.mountpoint,e))),o.PSLIB_ROOT_URI].map(f.toS)}t.currentUriRoots=w,t.outdatedAssetFileCount=async function(){const e=await w();return p.AssetFile.dbl.pluckFirstf((t=>t.count("AssetFile.id").distinct().where("version","!=",s.AssetFileVersion).andWhere((t=>e.forEach((e=>t.orWhereLike("AssetFile.uri",e+"%")))))))},t.outdatedAssetCountSync=function(){return m.Asset.outdatedCount()},t.outdatedAssetFileCountSync=function(){return p.AssetFile.dbl.pluckFirstf((e=>e.count("id").where("version","!=",s.AssetFileVersion)))},t.enqueueAssetFileUpdates=async function(){const e=[];for(const t of await w())e.push(await p.AssetFile.dbl.batched({maxResults:g.Task.freeSlots(),onResults:async e=>{const t=[];for(const i of e)t.push({fn:"updateAssetFile",args:{assetFileId:i.id,path:await(0,a.uri2nativePath)(i.uri),skipAssetRepair:!0}});g.Task.add(t),y().info("Scheduled updateAssetFile",{tasks:t})},qb:(e,i)=>(e=e.select({id:"AssetFile.id",uri:"AssetFile.uri"}).distinct().orderBy("AssetFile.id","asc").where("AssetFile.version","!=",s.AssetFileVersion).andWhereLike("AssetFile.uri",t+"%"),(0,u.isNotEmpty)(i)&&(e=e.andWhere("AssetFile.id",">",(0,n.max)(i.map((e=>e.id))))),e)}));return y().tap({msg:"enqueueAssetFileUpdates",level:"info",result:{done:e.every((e=>e.done)),tasksAdded:(0,n.sumf)(e,(e=>e.resultCount))}})},t.outdatedAssetCount=async function(){const e=await w();return m.Asset.dbl.pluckFirstf((t=>t.count("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").where("Asset.version","!=",s.AssetVersion).andWhere((t=>e.forEach((e=>t.orWhereLike("AssetFile.uri",e+"%")))))))},t.enqueueAssetUpdates=async function(){const e=[];for(const t of await w())e.push(await m.Asset.dbl.pluckBatched({maxResults:g.Task.freeSlots(),onResults:e=>(g.Task.add(e.map((e=>({fn:"repairAsset",args:{assetId:e}})))),y().info("Scheduled repairAsset for ",{assetIds:e}),(0,d.delay)(1)),qb:(e,i)=>(e=e.select("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").orderBy("Asset.id","asc").where("Asset.version","!=",s.AssetVersion).andWhereLike("AssetFile.uri",t+"%"),(0,u.isNotEmpty)(i)&&(e=e.andWhere("Asset.id",">",(0,n.max)(i))),e)}));return y().tap({msg:"enqueueAssetUpdates",level:"info",result:{done:e.every((e=>e.done)),tasksAdded:(0,n.sumf)(e,(e=>e.resultCount))}})}},3996:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const a=i(19851),o=i(50213),l=i(79781),u=i(56519),c=i(56038),d=i(59189),h=i(38835),f=i(95696),m=i(48368),p=i(181),g=i(69589),y=i(28874),w=i(28544),v=i(47783),b=i(87001),S=i(40958),P=i(76790),M=i(22573),_=i(42659),T=i(55835),E=i(31586),D=i(43487),k=i(54017);t.isFileInSync=async function(e){return new F(f.PosixFile.for(e)).alreadySynced()};const x=new d.SerialLaterQueue;class F{constructor(e,t=(0,g.forceContextOrSetting)()){this.file=e,this.ctx=t,r.set(this,void 0),this.rejectedAssetIds=new Set,this.rejectedSiblingIds=new Set,this.alreadySynced=(0,c.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>n(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,c.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new k.AssetFile).updateFromFile_(this.file);return null==e?n(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,a.lazy)((async()=>{const e=await(0,v.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,a.lazy)((()=>y.Settings.useImageHashes.valueOrDefault?(0,m.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,a.lazy)((()=>(0,u.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,a.lazy)((async()=>{const e=await this.capturedAt_();return n(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,c.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,M.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return n(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await x.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return n(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new D.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,c.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,p.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtAndImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,c.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return n(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;n(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw n(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),s(this,r,(0,o.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f")}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),n(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}n(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(e=this.file){const t=await e.uri_();if(null!=t)return k.AssetFile.ops().firstf((e=>e.whereIn("uri",[...(0,b.uriEncodingVariants)(t),this.file.fileuri()])));n(this,r,"f").warn("byUri() uri is null",{file:e})}async assetByNormalizedPathUri(){const e=await this.file.normalize();return e.nativePath===this.file.nativePath?void 0:(await this.byUri(e))?.getAsset()}async assetBySha(){const e=await this.file.sha_();return D.Asset.findFirstByFile((t=>(t=t.where("AssetFile.sha",e),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds))),this.rejectedSiblingIds.size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),t)))}async assetByCapturedAtAndImageHash(){const e=await this.capturedAt_();if(null==e)return n(this,r,"f").throw("Cannot import, capturedAt is null"+h.InternalErrorFlag);if(y.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(k.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=y.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=k.AssetFile.query();return(0,E.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(_.secondMs,y.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,c.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)n(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(y.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void n(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const a=await this.dominantLabhashes();if((0,S.isNotEmpty)(a)){const t=e.localBoundaries({delta:4*s});if(null==t)n(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",a).orWhereIn("mode1",a).orWhereIn("mode2",a))));if(null!=e)return e}}const o=this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash));if(null!=o)return o;if(y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const r={};for(let e=0;e0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds)));const i=await this.firstSimilarAsset(k.AssetFile.ops().all(t));return null!=i&&n(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const s=(0,P.sortBy)(e.filter((e=>!this.rejectedSiblingIds.has(e.id)&&!this.rejectedAssetIds.has(e.assetId))),(e=>[(0,T.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of s)if(null!=e){await e.getNativePath();const i=k.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const s=(0,l.whyNotSameAsset)(t,e,i);if(null==s)return n(this,r,"f").info("Found sibling AssetFile",e),D.Asset.ops().findById(e.assetId);this.rejectedSiblingIds.add(e.id),n(this,r,"f").debug("Contemporary assetFile not similar: "+s,e?.uri)}}}t.AssetFileFinder=F,r=new WeakMap},34274:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult_=void 0;const u=i(19851),c=i(50213),d=i(73568),h=i(38835),f=i(95696),m=i(62105),p=i(74128),g=i(181),y=i(69589),w=i(28874),v=i(40958),b=i(22573),S=i(38639),P=i(59455),M=i(64526),_=i(19113),T=i(94710),E=i(3996),D=i(90901);t.importFileToResult_=async function(e){const t=M.Library.instanceRequired_();return(0,p.syncReport)().wrap_({path:e.path,from:"AssetFileImporter",fn_:()=>new k(f.PosixFile.for(e.path),t.assetFileRepository(),e).apply_()})};class k{constructor(e,t,i){r.add(this),this.file=e,this.repo=t,this.start=Date.now(),s.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else if(this.ctx.forceFilters||null==await this.prior()){const t=await(0,m.whyRejectFile)(this.file,(0,_.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,s,"f").throwIfAborted_();const i=await this.prior();if((0,v.isNotEmpty)(e)&&null!=i&&(l(this,s,"f").info("Deleting prior AssetFile",{rejected:e,prior:i}),i.delete(),this.ctx.skipAssetRepair?l(this,s,"f").info("Skipping asset repair",{assetId:i.assetId}):(l(this,s,"f").info("Scheduling asset repair",{assetId:i.assetId}),T.Task.addOne("repairAsset",{assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)}))),null!=i){const t=i.getAsset();null!=t?.deletedAt&&e.push("Asset is marked as deleted"),null!=t?.excludedAt&&e.push("Asset is marked as excluded")}if(l(this,s,"f").throwIfAborted_(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,b.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,s,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,s,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,s,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,r,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,s,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new E.AssetFileFinder(e,this.ctx),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=k,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(){l(this,s,"f").throwIfAborted_();const e=await l(this,s,"f").tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if((0,v.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,s,"f").throwIfAborted_();const t=await l(this,s,"f").tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,s,"f").throwIfAborted_();const i=await l(this,s,"f").tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return l(this,s,"f").throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return l(this,s,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,s,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,s,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;await l(this,s,"f").tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:w.Settings.taskTimeoutMs.valueOrDefault}),l(this,s,"f").throwIfAborted_();try{o=await(0,D.assetPostUpsertTasks_)({asset:a,...this.ctx})}catch(e){e instanceof d.AbortError?l(this,s,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,s,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:r,assetFile:i,asset:a,uri:n,uris:[n,...(0,P.toA)(o?.newAssetFileUris)]}}},41844:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(50213),c=i(74128),d=i(81674),h=i(57902),f=i(4936),m=i(28874),p=i(47783),g=i(14245),y=i(67083),w=i(16170),v=i(54979),b=i(98604),S=i(40958),P=i(22573),M=i(98553),_=i(68708),T=i(89937),E=i(59455),D=i(54017),k=i(94710);t.mayCopyAssetsToLibrary=async function(){return m.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,u.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!0!==m.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,d.l)())return"no active subscription";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(m.Settings.libraryDir.valueOrDefault))return e+" already contained by "+m.Settings.libraryDir.valueOrDefault;const t=await(0,v.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,w.isMimeTypeIncluded)(t,m.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(T.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,E.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(D.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),k.Task.addOne("repairAsset",{assetId:t,forceSync:!0})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,M.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return a.addAssetFile(d),(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,p.readCapturedAt)(e),i=(0,f.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,p.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,p.readTags)(e);if(null!=i){if(m.Settings.writeGeolocationTagsToLibraryCopies.valueOrDefault){const e=(0,g.geolocationToXmp)(i);(0,_.isEmptyObj)(e)||await(0,p.writeTags_)(t,e)}return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred)}this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},90901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const r=i(50213),s=i(92434),n=i(73568),a=i(99331),o=i(39250),l=i(38835),u=i(57159),c=i(48604),d=i(66106),h=i(69589),f=i(40958),m=i(45599),p=i(23838),g=i(31586),y=i(64526),w=i(88224),v=i(43487),b=i(41844),S=i(68640),P=(0,m.defer)((()=>(0,r.mkLogger)("sync-file.AssetPostUpsertTasks"))),M=(0,m.defer)((()=>new o.LastOneInWins("Asset tasks")));async function _(e){const t=e,i=e,r=(0,g.toGt0)(t.asset?.id)??(0,g.toGt0)(i.assetId);if(null==r)throw new Error("assetPostUpsertTasks_(): unexpected null assetId"+l.InternalErrorFlag);const o=(0,h.forceContextOrSetting)(e),m=P().addContext(`.postUpsertAssetTasks_(Asset:${r})`);if(m.abortable=o.halt,o.skipPreviews&&o.skipAssetTagging)return void m.info("skipped (skipPreviews && skipAssetTagging)");const _=t.asset??v.Asset.ops().findById(r);if(null==_)return m.throw("unexpected null asset",{asset:_});try{return await M().enqueue({key:r,abortable:m.abortable,fn:()=>async function(e,t,i){const r=(0,h.forceContextOrSetting)(i),n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted_(),(0,f.isEmpty)(a)&&(await v.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,b.mayCopyAssetsToLibrary)())for(const[t,i]of(0,p.groupBy)(a,(e=>e.sha)).entries()){e.throwIfAborted_();try{for(const r of i)r.isInLibrary()&&await r.exists()&&e.debug("no-op for file SHA: already in library.",{sha:t,uri:r.uri});for(const e of i)if(await e.exists()){const t=await y.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,r);if(null!=t){o.newAssetFileUris.push(t.uri);continue}}}catch(r){e.warn("Failed to copy variation to library, but we'll try to continue",{sha:t,uris:i.map((e=>e.uri)),error:r})}}e.throwIfAborted_();const l=r.skipPreviews?void 0:await(0,S.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...r}),u=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?P().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,s.bestExistingAssetFile)(e.getAssetFiles())}(t,l);if(null==u)return e.throw("null primaryOrShownAssetFile_()",{asset:t});const m=await u.posixFile_();if(!0!==r.skipPreviews&&t.isVideo()){if(null==m)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});o.transcoded=null!=await(0,d.transcode_)(m,c.Previews.instance().ap(n).mp4(),{force:r.forceRebuildPreviews,halt:r.halt})}return e.throwIfAborted_(),t.markShownAndUpsert_(u),r.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,w.tagAndUpsertAsset_)(t),o}(m,_,{...e,...o})})}catch(e){if(e instanceof n.AbortError)return void m.warn("aborted, next caller will clean up my mess",{error:e});const t=[e];if(!(0,a.ending)()){m.error("failed, marking asset unshown",{error:e});try{_.markUnshownAndUpsert()}catch(e){m.error("failed to mark asset unshown",{upsertError:e}),t.push(e)}}throw new u.WrappedError("Failed to post-process assset "+_.id,{causes:t})}}t.assetPostUpsertTasks=function(e){try{return _(e)}catch(e){if(e instanceof n.AbortError)return void P().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=_},61989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset_=t.updateAsset=void 0;const r=i(48884),s=i(50213),n=i(45393),a=i(79184),o=i(79781),l=i(92434),u=i(56519),c=i(70417),d=i(69589),h=i(28874),f=i(40958),m=i(22573),p=i(38639),g=i(50357),y=i(43487),w=i(54017),v=i(3996),b=i(90901);async function S(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,r=(0,s.mkLogger)(`sync-file.UpdateAsset(${i})`);r.abortable=t.halt;const S=y.Asset.ops().findById(i);if(null==S)return r.throw("no such asset");const M=S.getAssetFiles({refresh:!0});if((0,f.isEmpty)(M))return r.warn("No asset files: deleting."),S.delete(),{asset:S,rejected:"Empty asset (no AssetFiles)"};const _=S.$clone(),T=S.getShown()?.$clone();for(const e of M)r.throwIfAborted_(),await e.upsertIfNeeded_(void 0,t);M.some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&S.clear(),await P(r,M);const E=(0,l.sortAssetFiles)(M),D=E?.[0];if((0,f.isEmpty)(E)||null==D)return r.warn("No existing files. Skipping for now."),S.markUnshownAndUpsert(),{asset:S,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!D.isVersionUpToDate())return r.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:D}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${D.id}, could not be updated. Un-showing Asset:${i}`};const k=await D.capturedAt();if(null==k)return r.warn("Best file failed to extract a captured-at",{bestAcceptedAF:D}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${D.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const x=new Set,[F,C]=await(0,u.partitionAsync)(E,(e=>(0,o.isSimilarAssetFile)(e,D)));if(r.throwIfAborted_(),(0,f.isNotEmpty)(C)){const e=await(0,a.aggregateAssetFiles)(C);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});x.add(e.id);for(const i of t)e.addAssetFile(i);w.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),r.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function A(e){return(0,f.uniq)(F.map((t=>t[e])))}const I=await Promise.all(F.map((e=>e.capturedAt()))),O=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,L=I.map((e=>e?.localBoundaries({delta:O}))),R=(0,c.min)(L.map((e=>e?.start)))??k.localBoundaries({delta:O})?.start,N=(0,c.max)(L.map((e=>e?.end)))??k.localBoundaries({delta:O})?.end,B=w.AssetFile.ops().all(w.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${D.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",A("sha")),null==R||null==N?r.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:R,endBoundary:N}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[R,N]),e.orWhereIn("AssetFile.meanHash",A("meanHash")).orWhereIn("AssetFile.diffHash",A("diffHash")).orWhereIn("AssetFile.dctHash",A("dctHash"))))));if(r.throwIfAborted_(),h.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const e=await D.posixFile();if(null==e)r.info("bestAcceptedAF has no posixFile, cannot expand query for fuzzy dates",{bestAcceptedAF:D});else{const i=new v.AssetFileFinder(e,t);for(const e of[...F,...B])i.rejectedAssetIds.add(e.assetId),i.rejectedAssetIds.add(e.id);let s=h.Settings.maxContemporaryAdoptionAssets.valueOrDefault;for(;--s>0;){r.throwIfAborted_();const e=await i.assetByCapturedAtAndImageHash();if(null==e){r.info("allowFuzzyDateImageHashMatches(): no additional assets found to adopt");break}if(r.info("allowFuzzyDateImageHashMatches(): found asset with similar image",{a:e}),null!=e){i.rejectedAssetIds.add(e.id);for(const t of e.getAssetFiles())r.info("found asset file by fuzzy date and image hash",{uri:t.uri,assetId:e.id}),B.push(t),i.rejectedAssetIds.add(t.id)}}}}r.info("asset file candidates for adoption: ",B.map((e=>e.posixPathFromGrandparent)));const j=[];for(const e of B){r.throwIfAborted_();try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,D)&&(r.info("adopting similar asset file",{af:e}),x.add(e.assetId),e.shown=!1,S.addAssetFile(e),e.upsert(),j.push(e))}catch(t){r.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}}r.info("fetched expansion",{retainAFs:F.map((e=>e.id)),rejectAFs:C.map((e=>e.id)),externalAssetFiles:B.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:j.map((e=>e.posixPathFromGrandparent))}),await P(r,[...F,...j]),t.skipPreviews&&t.skipAssetTagging?(r.info("skipping previews and tagging",t),S.upsert()):await(0,b.assetPostUpsertTasks_)({...t,asset:S});const z=!(0,g.eql)(_,S),V=!(0,g.eql)(T,S.getShown()),W=!(z||V||t.forceRebuildPreviews||t.forceSync);return r.tap({msg:"updateAsset() result",level:"info",result:{asset:S,assetIdsToUpdate:Array.from(x),assetFiles:S.assetFiles,skipped:W},meta:{ctx:t,assetChanged:z,primaryAssetFileChanged:V}})}async function P(e,t){const[i,s]=(0,r.partition)(t,(e=>e.isVersionUpToDate()));for(const t of s){e.throwIfAborted_();const r=i.find((e=>e.sha===t.sha));if(null!=r){e.info("backfilling",{sibling:r,dest:t});const i=await t.updateFromShaSibling_(r);null!=i&&i.upsert()}}}t.updateAsset=async function(e){try{const t=await S(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}},t.updateAsset_=S},93755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t.updateAssetFile_=t.updateAssetFile=void 0;const r=i(50213),s=i(92434),n=i(98314),a=i(74128),o=i(69589),l=i(87001),u=i(40958),c=i(22573),d=i(68708),h=i(43487),f=i(54017),m=i(94710);async function p(e){const t=Date.now(),i=e,s=e,n=s.af?.id??i.assetFileId,u=(0,r.mkLogger)(`updateAssetFile(${n})`),d=s.af??f.AssetFile.ops().findById(n);if(null==d)return u.throw("db record not found",{assetFileId:n});const h=await d.posixFile_(),p=(0,o.forceContextOrSetting)(e),w={id:n,assetFileId:n,path:h?.nativePath,uri:d?.uri};if(null==h){const e=["cannot resolve URI"];return(0,c.blank)(d.mountpoint)||e.push("is "+d.mountpoint+" mounted?"),(0,a.syncReport)().onProgress({path:d.uri,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:e.join(": "),state:a.SyncFileStates.skipped}),{...w,error:"file for URI not found"}}const v=await(h?.isDeletedUri(d.uri));if(null==v)return u.info("no-op: file URI points to an unmounted volume",w),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:((0,c.toNotBlank)(d.mountpoint)??"volume")+" is not currently mounted",state:a.SyncFileStates.skipped}),{...w,skipped:!0};const b=e.whyReject??await d.whyRejected();if(v||!(0,c.blank)(b)){const e={...w,rejected:b,deleted:v};return u.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:v?"file no longer exists":"rejected: "+b,state:a.SyncFileStates.deleted}),d.delete(),!0!==p.skipAssetRepair&&m.Task.addOne("repairAsset",{assetId:d.assetId}),e}const S=await h.uri_();if(!await(0,l.uriIsEquivalent)(S,d.uri)){const e=await g(d,S,p);if(null!=e)return{...w,...e}}return!p.forceSync&&await d.matchesFile()?(u.info("no-op: file already matches db record",w),d.touch(),{...w,skipped:!0}):{...w,...await y(d,p)}}async function g(e,t,i){const n=(0,r.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,u.uniq)([...(0,l.uriEncodingVariants)(e.uri),...(0,l.uriEncodingVariants)(t)]);n.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const o=f.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,u.isNotEmpty)(o)){n.warn("Found other AssetFiles with equivalent URIs.",{afIds:o.map((e=>e.id))});const t=[e,...o],r=(0,s.sortAssetFiles)(t);if((0,u.isEmpty)(r))return n.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,d.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const l=t.map((e=>e.id));for(const e of r)if(await e.exists()){f.AssetFile.dbl.runf((t=>t.whereIn("id",l.filter((t=>t!==e.id))).delete()));const r=y(e,i);return h.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,u.uniq)(t.map((e=>e.assetId)))))),r}}n.info("no-op, no duplicate URIs.")}async function y(e,t){const i=Date.now();return null!=await e.upsertIfNeeded_(void 0,t)&&h.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:await e.getNativePath(),elapsedMs:Date.now()-i,from:"updateAssetFileIfNeeded()",state:e.syncState??a.SyncFileStates.unknown}),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await p(e)}catch(t){return{id:e.assetFileId,...e,error:(0,n.errorToS)(t)}}},t.updateAssetFile_=p,t.handleAssetFileUriChange=g,t.updateAssetFileIfNeeded=y},68640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const r=i(99331),s=i(38835),n=i(48604),a=i(50213),o=i(69589),l=i(87001),u=i(40958),c=i(45599),d=i(50357),h=i(31586),f=i(68708),m=i(59455),p=i(43487),g=(0,c.defer)((()=>(0,a.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,m.toA)(e.assetFiles).find((e=>(0,h.gt0)(e.assetId)))?.assetId,i=(0,o.forceContextOrSetting)(e),a=g().addContext(".Asset:"+t);if(i.skipPreviews)return void a.warn("skipPreviews is true: no-op");if(!(0,h.gt0)(t))return a.throw("invalid assetId",{assetId:t});const c=e.asset??p.Asset.ops().findById(t);if(null==c)return a.throw("Asset:"+t+" not found");a.throwIfAborted_(i.halt);try{const e=await c.getExistingAssetFiles();if((0,u.isEmpty)(e))return void a.warn("no existing assetFiles",{asset:c});const r=n.Previews.instance().ap(t),o=await r.readInfo();a.throwIfAborted_(i.halt);const h=await(0,n.buildAssetPreviews_)({...i,assetId:t,assetFiles:e}),m=e.find((e=>e.id===h?.assetFileId))??e.find((e=>(0,l.uriIsEquivalent)(h?.uri,e.uri)));a.info("buildAssetPreviews_()",{result:h,primaryAssetFile:m});const p=await(m?.posixFile_());if(null==m||null==p||!0!==await(p?.exists()))return a.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:h,assetFiles:e.map((e=>(0,f.pick)(e,"id","uri"))),primaryAssetFile:m,primaryPosixFile:p});const g=(0,d.eql)(o,h),y=null==h||g;return{...h,noop:y}}catch(e){throw(0,r.ending)()||(a.warn("Failed to update previews. Un-showing asset "+t,{error:e}),c.markUnshownAndUpsert()),e}}},34742:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(93944).install()}catch{}const r=i(69554),s=i(38790),n=i(53978),a=i(43380),o=i(43334),l=i(28874),u=i(5670),c=i(21200),d=i(2775),h=i(31503),f=i(12195),m=i(52288),p=i(53767);!async function(){if(o.isElectron)new p.SyncService;else{const e=await new r.CLI(u.ServiceNames.sync,"[files-or-directories...]","If paths are provided on the command line, they should be fully-qualified.\n\n* Paths to directories will be scanned recursively.\n* Paths to files will be imported if they pass configured filters.\n\nNote that sync will spawn 1 or more `worker` processes to work in parallel.").add(m.RebuildArg,d.ForceArg,n.TimingArg,f.NoFilterArg,c.ExitWhenDoneArg,a.WriteSettingsArg,h.LogArgs,s.ColorArgs).parse();l.Settings.argvScanPaths.envValue=e.args,new p.SyncService}}()},94019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(87290),o=i(34102),l=i(16287),u=i(45969),c=i(43334),d=i(28874),h=i(45200),f=i(69375),m=i(7014),p=i(41400),g=i(31586),y=i(92244),w=i(46832);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const v=(0,r.lazy)((async()=>{const e=[];for(const t of await(0,m.volumes)()){if(!0===t.ignorable||!1===t.ok||(c.isMac||(0,u.isDocker)())&&"/"===t.mountpoint||(0,f.isExcludedMountpoint)(t.mountpoint)||!(0,g.gt0)(t.size))continue;const i=await(0,w.toUriPath)(t.mountpoint,(0,h.nativePath2uri)(t.mountpoint,t));null!=i&&e.push(i)}return e}));async function b(){const e=[],i=[],r=d.Settings.argvScanPaths.toNotEmpty()??d.Settings.scanPaths.values;for(const s of r)if(await(0,l.isReadableDirectory)(s)){const r=await(0,w.toUriPath)(s);null==r?(e.push(s),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",s)):i.push(r)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",s);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,p.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{v.unset()}))})),t.pathsToSync=async function(){const e=[];if(d.Settings.argvScanPaths.isNotEmpty()){for(const i of d.Settings.argvScanPaths.values){const r=await(0,w.toUriPath)(i);null!=r?e.push(r):(0,t.logger)().warn("pathsToSync(): Ignoring scanPath element: failed to create URI path",i)}return e}e.push(...(await b()).result),!0===d.Settings.scanAllDrives.value&&e.push(...await v());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),w.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:d.Settings.libraryDir.valueOrDefault,originalsDir:d.Settings.originalsDir.value})));d.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),d.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},76907:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.precheckFiles=void 0;const r=i(50213),s=i(98314),n=i(74128),a=i(69589),o=i(45200),l=i(98604),u=i(22573),c=i(45599),d=i(54017),h=(0,c.defer)((()=>(0,r.mkLogger)("sync.PrecheckFiles"))),f="AssetFilePrecheck";async function m(e,t){const i=(await(0,o.nativePath2uri)(e.nativePath)).toString(),r=d.AssetFile.ops().firstf((e=>e.where({uri:i})));if(null==r)return(0,n.syncReport)().onProgress({path:e.nativePath,from:f,state:n.SyncFileStates.enqueued,details:"Path is new to the library. Scheduling import."}),!0;const s=await r.whyNotNoop(t);return(0,u.blank)(s)?((0,n.syncReport)().onProgress({path:e.nativePath,from:f,state:n.SyncFileStates.noop,details:"in sync",url:(0,l.mkAssetUrl)(r.assetId)?.toString()}),r.touch(),!1):((0,n.syncReport)().onProgress({path:e.nativePath,from:f,state:n.SyncFileStates.enqueued,details:"update needed: "+s,url:(0,l.mkAssetUrl)(r.assetId)?.toString()}),!0)}t.precheckFiles=async function(e,t=(0,a.forceContextOrSetting)()){const i=[];for(const r of e)try{await m(r,t)&&(h().debug("precheckFiles(): stale path",{nativePath:r.nativePath}),i.push(r))}catch(e){h().info("precheckFiles(): failed to check path",{nativePath:r.nativePath,error:e}),(0,n.syncReport)().onProgress({path:r.nativePath,from:f,state:n.SyncFileStates.rejected,details:(0,s.errorToS)(e)})}return i}},63461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncCompleted=void 0,t.SyncCompleted={syncCompleted:!0}},98622:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runTimeIsStale=t.SyncCron=void 0;const r=i(1708),s=i(17415),n=i(28874),a=i(41400),o=i(30301),l=i(31586);t.SyncCron=(0,o.lazy)((()=>{const e=n.Settings.syncCronTZ.valueOrDefault??(0,s.toValidIanaZone)(r.env.TZ);return n.Settings.syncCron.cron(null==e?void 0:{timezone:e})})),(0,a.later)((()=>{n.Settings.syncCron.watchLater((()=>t.SyncCron.unset())),n.Settings.syncCronTZ.watchLater((()=>t.SyncCron.unset()))})),t.runTimeIsStale=function(e){return null==e||(0,l.lte)((0,t.SyncCron)().nextRun(new Date(e))?.getTime(),Date.now())}},56179:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},f=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncDirectory=t.DefaultFileHandler=void 0;const m=i(89788),p=i(19851),g=i(50213),y=i(7282),w=i(45255),v=i(81168),b=i(73568),S=i(83412),P=i(99331),M=i(98314),_=i(38835),T=i(60652),E=i(29882),D=i(74128),k=i(76752),x=i(70417),F=i(28874),C=i(14036),A=i(69385),I=i(15674),O=i(22573),L=i(38639),R=i(42659),N=i(45599),B=i(55835),j=i(31586),z=i(68708),V=i(12168),W=i(54993),U=i(35580),q=i(54017),H=i(20958),G=i(49796),$=i(55009),J=i(94710),K=i(76907);async function Z(e){const t=await(0,K.precheckFiles)(e);J.Task.add(t.map((e=>({fn:"syncFile",args:{path:e.nativePath}}))))}t.DefaultFileHandler=Z;class Y extends S.DoneWrapper{static async for({root:e,rootUri:t,fileHandler:i=Z}){const r=await e.directoryEntry();if(null!=r&&r.isDirectory())return new Y(e,r,t,i);(0,g.mkLogger)("sync.DirectorySync").error("Cannot sync "+e+": it's not a directory (or not readable)",{root:e,rootUri:t})}constructor(e,t,i,d){super("sync.DirectorySync("+e+")",(()=>h(this,r,"m",s).call(this))),r.add(this),this.root=e,this.rootDirent=t,this.rootUri=i,this.fileHandler=d,this.start=Date.now(),this.eta=new k.ETA,this.recentlyScannedDirs=new m.BoundedList(10),this.progress=(0,N.defer)((()=>this.logger.tap({msg:".progress()",level:"warn",result:G.Progress.insertNew({uri:this.rootUri,volume:this.root.nativePath})}))),this.forceDirectoryScan=(0,N.defer)((()=>{const e=F.Settings.forceSync.valueOrDefault,t=F.Settings.argvScanPaths.values.some((e=>this.root.eql(e)));return this.logger.tap({msg:"forceDirectoryScan",result:e||t,meta:{forceSync:e,isArgvPath:t}})})),this.initialMeta=(0,N.defer)((()=>this.forceDirectoryScan()?void 0:this.progress().getMetaAsRecord())),this.minPriorCreatedAt=(0,N.defer)((()=>(0,x.max)([H.Operation.getFirstPendingOp({name:"forceRestartSync"})?.createdAt,(0,G.defaultMinCreatedAt)()]))),this.priorMeta=(0,N.defer)((()=>this.progress().getPriorIncomplete(this.minPriorCreatedAt())?.getMetaAsRecord())),this.priorScannedDir=(0,N.defer)((()=>this.priorMeta()?.lastScannedDirectory)),this.priorScannedDirsCount=(0,N.defer)((()=>(0,j.toInt)(this.priorMeta()?.scannedDirectoryCount)??0)),this.priorProcessedImageCount=(0,N.defer)((()=>(0,j.toInt)(this.priorMeta()?.processedImageCount)??0)),this.priorProcessedVideoCount=(0,N.defer)((()=>(0,j.toInt)(this.priorMeta()?.processedVideoCount)??0)),this.scannedDirsCount=0,n.set(this,0),a.set(this,0),this.priorEnqueuedStaleFiles=(0,N.defer)((()=>(0,L.isTrue)(this.priorMeta()?.enqueuedStaleFiles)??!1)),this.enqueuedStaleFiles=!1,this.completed=!1,this.upsertProgressMeta=(0,p.lazy)((()=>{const e=this.progress().getMetaAsRecord(),t={lastScannedDirectory:this.recentlyScannedDirs.at(-1)??this.priorScannedDir()??"",scannedDirectoryCount:(0,W.toS)(this.scannedDirectoryCount()),completedDirectoryScan:(0,W.toS)((0,L.isTrue)(this.priorMeta()?.completedDirectoryScan)||(h(this,o,"f").call(this)?.isDone()??!0)),enqueuedStaleFiles:(0,W.toS)(this.priorEnqueuedStaleFiles()||this.enqueuedStaleFiles),processedImageCount:(0,W.toS)(this.processedImageCount()),processedVideoCount:(0,W.toS)(this.processedVideoCount()),completedDirectorySync:(0,W.toS)((0,L.isTrue)(e.completedDirectorySync)||this.completed)};this.progress().setMetaRecord(t)}),(0,y.isTest)()?100:R.secondMs),this.directoryListener=e=>{null==e||(0,O.blank)(e.nativePath)?this.logger.warn("directoryListener() called with blank dir"+_.InternalErrorFlag,{dir:e}):(this.scannedDirsCount++,this.recentlyScannedDirs.push(e.nativePath),this.logger.debug("directoryListener()",{scannedDirsCount:this.scannedDirsCount,dir:e.nativePath}),this.upsertProgress({force:!0}))},o.set(this,(0,N.defer)((()=>(0,L.isTrue)(this.priorMeta()?.completedDirectoryScan)?void 0:new T.DirectoryIterator(this.rootDirent,this.ctx())))),this.pendingCount=(0,p.lazy)((()=>J.Task.countByFn("syncFile")),R.secondMs),l.set(this,((e,t,i)=>{if("syncFile"===e.fn){const t=e;this.onFileResolved(t.args.path,i)}else this.logger.info("onTaskResolve() non-syncFile task",{task:e,result:t,elapsedMs:i})})),u.set(this,((e,t)=>{this.logger.error("onTaskRejected()",{task:e,error:t})})),this.doneLatch.observe(h(this,r,"m",c).call(this)).catch((t=>{this.logger.error("SyncDirectory failed for "+e,{error:t}),(0,D.syncReport)().onProgress({path:e.nativePath,from:"SyncDirectory",state:t instanceof b.AbortError?"canceled":"failed",details:(0,M.errorToS)(t)})}))}upsertProgress(e){const t=h(this,r,"m",d).call(this,e);if(this.logger.info("upsertProgress()",{update:t}),null!=t){const e=this.progress().upsert(t);return this.upsertProgressMeta(),e}}scannedDirectoryCount(){return this.priorScannedDirsCount()+this.scannedDirsCount}ctx(){return{startAtNativePath:(0,B.map)(this.initialMeta()?.lastScannedDirectory,E.splitNativePath),hasCapacity:()=>U.TaskList.instance().hasCapacity(),fileHandler:this.fileHandler,directoryListener:this.directoryListener,ended:()=>(0,P.ending)()||this.ended}}earliestStartTime(){return this.progress().getLastIncompleteStartAt()??this.start}async maybeEnqueueStaleAssetFiles_(){if(!F.Settings.forceSync.valueOrDefault&&(0,L.isTrue)(this.priorMeta()?.enqueuedStaleFiles))this.logger.info("maybeEnqueueStaleAssetFiles() no-op: prior enqueuedStaleFiles.");else{const e=this.progress(),t=this.earliestStartTime(),i=U.TaskList.instance();this.logger.info("maybeEnqueueStaleAssetFiles() starting",{earliestStartTime:t});const r=Math.min(Math.round(F.Settings.taskListCap.valueOrDefault/4),F.Settings.dbBatchSelectSize.valueOrDefault),s=F.Settings.taskListCap.valueOrDefault-r;let n=0;await q.AssetFile.ops().batched({batchSize:r,onResults:async e=>{this.logger.throwIfAborted_(),await Promise.all(e.map((e=>e.getNativePath()))),J.Task.add(e.map((e=>({fn:"updateAssetFile",args:{path:e.nativePath,assetFileId:e.id,whyReject:"missed by directory sync"}})))),n+=e.length,await i.awaitDrain([],s)},qb:e=>e.select("id").whereLike("uri",this.rootUri+"%").andWhere("updatedAt","<",t)}),this.logger.info("maybeEnqueueStaleAssetFiles() finished enqueue",{assetFileQueuePendingCount:n}),e.setMeta($.ProgressMetaNames.enqueuedStaleFiles,"true")}}processedCount(){return this.processedImageCount()+this.processedVideoCount()}processedVideoCount(){return this.priorProcessedVideoCount()+h(this,a,"f")}processedImageCount(){return this.priorProcessedImageCount()+h(this,n,"f")}onFileResolved(e,t){var i,r;(0,C.isVideoExt)(e)?f(this,a,(i=h(this,a,"f"),++i),"f"):f(this,n,(r=h(this,n,"f"),++r),"f"),this.eta.push(t),this.upsertProgress()}get isScanning(){const e=h(this,o,"f").call(this);return null!=e&&!e.isDone()}estimatedScannedPct(){if(!this.isScanning)return 100;const e=100/-(this.scannedDirsCount/500+1)+100;return(0,j.sigFigs)(e,3)}percents(){if(this.completed||this.isDone())return{completePct:100,incompletePct:0,scanningPct:0};const e=(0,j.round)(this.estimatedScannedPct()),t=100-e,i=this.processedCount(),r=this.pendingCount(),s=0===r&&0===i?0:(0,j.round)(e*(i/(r+i))),n=100-(s+t),a={completePct:s,incompletePct:n,scanningPct:t};return this.logger.debug("percents(): ",{scannedPct:e,processed:i,pending:r,p:a}),100!==(0,x.sum)([a.completePct,a.incompletePct,a.scanningPct])&&this.logger.warn("percents(): BUGGED",{p:a,processed:i,pending:r,scannedPct:e,scanningPct:t,incompletePct:n,completePct:s}),a}}t.SyncDirectory=Y,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,r=new WeakSet,s=function(){J.Task.ee.off("resolved",h(this,l,"f")),J.Task.ee.off("rejected",h(this,u,"f"))},c=async function(){J.Task.ee.on("resolved",h(this,l,"f")),J.Task.ee.on("rejected",h(this,u,"f"));const e=this.initialMeta();this.logger.info("setup()",{meta:e});const t=U.TaskList.instance(),i=h(this,o,"f").call(this);if(null==i)this.logger.info("#run(): already completedDirectoryScan");else{this.logger.info("#run(): starting directory scan...");const e=Math.round(F.Settings.taskListCap.valueOrDefault),r=Math.max(2*(0,I.maxConcurrentImports)(),Math.round(F.Settings.taskListCap.valueOrDefault/2));for(;!i.isDone();)await this.awaitOrAbort((0,A.resolveOnResume)()),await i.next(w.ShortCommandTimeoutMs+Date.now()),t.hasCapacity(.9*e)||await this.awaitOrAbort(t.awaitDrain(["syncFile"],r));(0,D.syncReport)().onProgress({from:"SyncDirectory",state:"note",details:"Directory scan complete",path:this.root.nativePath,elapsedMs:Date.now()-this.start}),this.upsertProgress({force:!0})}await this.awaitOrAbort(t.awaitDrain()),(0,D.syncReport)().onProgress({from:"SyncDirectory",state:"note",details:"File imports complete: "+this.processedImageCount()+" images and "+this.processedVideoCount()+" videos",path:this.root.nativePath,elapsedMs:Date.now()-this.start}),await this.awaitOrAbort(this.maybeEnqueueStaleAssetFiles_()),await this.awaitOrAbort(t.awaitDrain()),this.ended||this.aborted||(this.logger.info("DONE! Marking Progress as complete and updating meta."),this.completed=!0,this.upsertProgress({force:!0,done:!0}))},d=function(e={}){const t=e.prior??{},i={},r=this.isDone()||(e.done??!1)||this.completed;if(!0!==e.force&&(0,j.gt)(t.updatedAt,Date.now()-R.secondMs))return;const s=U.TaskList.instance(),n=(0,A.isPaused)()||(0,P.ending)();i.state=r?"done":n?"paused":"processing";const a=s.pendingWorkCount();{const e=[];if(e.push((0,v.capitalize)(i.state)),!r&&a>0){const t=Math.min((0,I.maxConcurrentImports)(),a),i=this.eta.fmtEstimate(a/t);null!=i&&e.push(i)}i.hed=e.join(", ")}const o=[];this.processedCount()>0&&o.push("Processed "+(0,V.plur)(this.processedImageCount(),"photo")+" and "+(0,V.plur)(this.processedVideoCount(),"video")),!r&&a>0&&o.push((this.isScanning?"At least ":"")+(0,V.fmt)(a)+" remain to be processed"),r||n||!this.isScanning||o.push("Scanning "+(this.recentlyScannedDirs.shiftOrFirst()??this.root.nativePath)),this.scannedDirectoryCount()>0&&o.push("Scanned "+(0,V.plur)(this.scannedDirectoryCount(),"directory"));const l=s.currentTasksByFn("syncFile"),u=J.Task.nextByFn("syncFile",(e=>e.whereNotIn("id",l.map((e=>e.id))).limit(2)));return l.length>0&&o.push("Processing: "+(0,E.ellipsizePaths)({arr:l.map((e=>e.args.path)),maxPathLength:48,sampleSize:2})),u.length>0&&o.push("Queued: "+(0,E.ellipsizePaths)({arr:u.map((e=>e.args.path)),maxPathLength:48,sampleSize:2})),i.dek=o,(0,z.assignFields)(i,this.percents()),r&&(i.completedAt??(i.completedAt=Date.now())),this.logger.tap({msg:"#mkProgressUpdate()",level:"info",result:i})}},88204:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncFile=void 0;const a=i(83412),o=i(98314),l=i(74128),u=i(69385),c=i(49796),d=i(94710),h=i(76907);class f extends a.DoneWrapper{constructor(e){super("SyncFile: "+e),r.add(this),this.src=e,this.doneLatch.observe(n(this,r,"m",s).call(this)).catch((()=>{}))}}t.SyncFile=f,r=new WeakSet,s=async function(){await(0,u.resolveOnResume)();const e=await this.src.uri();if(null==e)return void(0,l.syncReport)().onProgress({path:this.src.nativePath,from:"SyncFile",state:l.SyncFileStates.rejected,details:"failed to build URI"});const t=c.Progress.insertNew({uri:e,volume:this.src.nativePath,state:"processing"});try{const[t]=await(0,h.precheckFiles)([this.src]);if(null!=t){const e=d.Task.addOne("syncFile",{path:this.src.nativePath});await e.donePromise()}else this.logger.info("syncFile: no-op",{uri:e})}catch(e){(0,l.syncReport)().onProgress({path:this.src.nativePath,from:"SyncFile",state:l.SyncFileStates.failed,details:(0,o.errorToS)(e)})}finally{t.upsert({state:"done",completedAt:Date.now()})}}},2387:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncManager=void 0;const a=i(83412),o=i(99331),l=i(98314),u=i(95696),c=i(74128),d=i(28874),h=i(98553),f=i(54993),m=i(98401),p=i(20958),g=i(76386),y=i(69032),w=i(56179),v=i(88204),b=i(92244),S=i(46832);class P extends a.DoneWrapper{constructor(){super("SyncManager"),r.add(this),this.doneLatch.observe(n(this,r,"m",s).call(this))}}t.SyncManager=P,r=new WeakSet,s=async function(){const e=d.Settings.argvScanPaths.toNotEmpty()??(d.Settings.exitWhenDone.valueOrDefault?[]:await(0,b.stalePathsToSync)());this.logger.info("#run starting",{paths:e});for(const t of e){this.logger.throwIfAborted_();const e=await(0,S.toUriPath)(t);try{null==e&&this.logger.throw("Could not convert to URI: "+(0,h.stringify)(t));const i=e.nativePath,r=u.PosixFile.forMaybe(i);null==r||null==e?(0,c.syncReport)().onProgress({path:i,from:"SyncManager",state:c.SyncFileStates.failed,details:"Cannot import: path could not be built."}):await r.isFile_()?(this.sync=new v.SyncFile(r),await this.sync.donePromise()):await r.isDirectory_()&&(this.sync=await w.SyncDirectory.for({root:r,rootUri:e.uri}),await(this.sync?.donePromise()))}catch(i){this.logger.info("Failed to sync path",{ea:t,error:i}),(0,c.syncReport)().onProgress({path:e?.nativePath??(0,f.toS)(t),from:"SyncManager",state:c.SyncFileStates.failed,details:(0,l.errorToS)(i)})}await(0,m.maybeCleanup_)(),await(0,y.runTagMaintenance)(),await g.tellWebProgressUpdated.refresh()}this.logger.info("#run complete",{paths:e}),p.Operation.markOpCompleted({name:"forceRestartSync"}),(0,o.ending)()||await(0,c.syncReport)().flushClose()}},92244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.isStale=t.bestPathToSync=t.stalePathsToSync=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(23560),o=i(22277),l=i(87290),u=i(57902),c=i(28874),d=i(40958),h=i(76790),f=i(42659),m=i(75240),p=i(31586),g=i(20958),y=i(49796),w=i(94019),v=i(98622),b=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));t.nativePathBlocklist=new o.TTLSet(10*f.minuteMs);const S=10*f.minuteMs;async function P(){const e=await(0,w.pathsToSync)(),t=c.Settings.forceSync.valueOrDefault?[]:await y.Progress.times();return b().tap({msg:"pathsAndTimesToSync()",level:u.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}function M(e,t){return null==e.lastStartedAt||null==e.lastCompletedAt||(0,p.lte)(e.lastStartedAt,t)||(0,v.runTimeIsStale)(e.lastCompletedAt)}function _(){return g.Operation.getFirstPendingOp({name:g.OperationNames.forceRestartSync})}async function T(e){const t=_(),i=t?.createdAt,s=e.filter((e=>M(e,i)));if((0,d.isEmpty)(s))return(0,a.isSyncService)()&&t?.markCompleted(),b().tap({msg:"bestStable(): No stale paths to sync!",level:"info",result:void 0,meta:{arr:e,forceRestartOp:t}});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,p.gt)(e.lastUpdatedAt,Date.now()-10*f.minuteMs))return b().tap({msg:"bestStable(): returning most recently updated",level:"info",result:{...e,why:"recently updated"}})}const n=(0,r.leastBy)(s,(e=>[e.lastStartedAt??0,e.lastCompletedAt??0]));return b().tap({msg:"bestStable(): returning least-recently-started or least-recently-completed:",level:"info",result:null==n?void 0:{...n,why:"least recently started or completed"},meta:{stale:s}})}function E(e,t){return null==e.lastStartedAt?"new":null==e.lastCompletedAt?"todo":(0,p.gt)(e.lastUpdatedAt,Date.now()-f.minuteMs)?"syncing":M(e,t)?"stale":"synced"}function D(e){return null==e?void 0:new Date(e).toISOString()}function k(e){if(null==e)return;const t=Date.now()-e;return t<2*f.secondMs?"just now":(0,m.fmtDuration)(t)+" ago"}t.pathsAndTimesToSync=P,t.stalePathsToSync=async function(){const e=await P(),t=_(),i=t?.createdAt,r=e.filter((e=>M(e,i)));return(0,h.sortBy)(r,(e=>[null!=e.lastUpdatedAt&&Date.now()-Se.nativePath)),t=await T(e),i=(0,l.libraryOriginalsDirPosixFile)()?.nativePath,r=_()?.createdAt;return e.map((e=>({path:e.nativePath,library:i===e.nativePath,status:E(e,r),isNext:e.nativePath===t?.nativePath,lastStartedISO:D(e.lastStartedAt),lastStarted:k(e.lastStartedAt),lastCompletedISO:D(e.lastCompletedAt),lastCompleted:k(e.lastCompletedAt)})))}},53767:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncService=void 0;const l=i(50213),u=i(7282),c=i(71567),d=i(78406),h=i(25764),f=i(38836),m=i(99331),p=i(45608),g=i(5916),y=i(73614),w=i(76596),v=i(8769),b=i(57159),S=i(63664),P=i(18454),M=i(21525),_=i(21473),T=i(41944),E=i(28874),D=i(2858),k=i(37692),x=i(93493),F=i(42659),C=i(45599),A=i(98553),I=i(98401),O=i(64526),L=i(37158),R=i(56992),N=i(35580),B=i(22968),j=i(63461),z=i(98622),V=i(2387);t.SyncService=class{constructor(){this.logger=(0,l.mkLogger)("SyncService"),r.set(this,void 0),s.set(this,(0,C.defer)((async()=>{await this.service.setup_(),this.logger.info("setup()",{library:E.Settings.libraryDir.valueOrDefault,exitWhenDone:this.exitWhenDone,argvScanPaths:E.Settings.argvScanPaths.values,scanPaths:E.Settings.scanPaths.values,skipLibraryRebuild:E.Settings.skipLibraryRebuild.valueOrDefault,argv:process.argv});const e=O.Library.instanceRequired_();await e.ready;const t=await(0,S.getRemoteOrLocalHealthSummary)();(0,M.isHealthCheckLevelFatal)(t.level)&&await(0,p.exit)({reason:"Health check failed: "+t.msg.join(": "),status:1}),await(0,D.maybeUpgradeSystemSettings)(),await(0,D.maybeUpgradeLibrarySettings)(),await(0,_.testSharp_)(),await(0,x.setupShimDelegates)(),(0,I.scheduleFileAndProcCleanups)(),N.TaskList.instance(),E.Settings.forceRebuildLibrary.valueOrDefault&&(this.logger.info("setup(): "+E.Settings.forceRebuildLibrary.key+" is true: setting all assets to require updates..."),(0,B.forceRebuildLibraryLater)()),(0,u.isTest)()&&T.onProgressEvt.setShim((async e=>console.log((0,A.stringify)(e)))),k.stateEvents.on("checkTasks",(()=>N.TaskList.instance().maybeRunChunk())),new d.EndableInterval({name:"SyncService.setVolumesTTL()",callback:()=>(0,R.setVolumesTTL)(),intervalMs:F.dayMs/4,initialDelayMs:5*F.minuteMs,rank:h.EndableRanks.first}),new f.EndableWrapper("SyncService end status",(async()=>this.logger.info("end status",await this.status())),h.EndableRanks.first),this.run()}))),n.set(this,(0,g.lazyAsync)({desc:"SyncService.run",later:async()=>{if(this.logger.info(".run(): starting"),(0,I.scheduleFileAndProcCleanups)(),await(0,B.maybeRebuildLibrary)(),this.logger.info(".run(): finished library rebuild"),await(N.TaskList.instance()?.awaitDrain()),this.logger.info(".run(): finished task list drain"),o(this,r,new V.SyncManager,"f"),await a(this,r,"f").donePromise(),(0,u.isTest)()&&(0,c.stdoutWrite)(j.SyncCompleted),this.exitWhenDone)return(0,p.exit)({reason:"Finished",status:0});this.logger.info("SyncManager completed. Running cleanups..."),await(0,I.cleanup_)(),(0,I.cancelFileAndProcCleanups)();const e=(0,z.SyncCron)().nextRun();this.logger.info("nextRun",{nextRun:e});const t=e.getTime()-Date.now();this.logger.info("Scheduling next sync run for "+e.toISOString()+" ("+(0,w.durationHMS)(t)+" from now)",E.Settings.syncCron.addToEnv({})),(0,y.setUnrefTimeout)((()=>this.run()),t)}})),this.exitWhenDone=E.Settings.exitWhenDone.valueOrDefault||E.Settings.argvScanPaths.isNotEmpty(),this.service=new L.Service("sync"),a(this,s,"f").call(this).catch((e=>(0,v.onError)(new b.WrappedError("SyncService.setup() failed",{cause:e,fatal:!0}))))}async status(){const e=a(this,r,"f");return{libraryDir:E.Settings.libraryDir.value,ending:(0,m.ending)(),sync:e?.sync?.name,summary:P.HealthCheck.summary()}}run(){const e=a(this,n,"f").prior();return this.logger.info("run()",{prior_pending:e?.isPending}),null!=e&&e.isPending?(this.logger.warn(".run(): preventing overrun: prior run is still pending"),e):a(this,n,"f").refresh()}},r=new WeakMap,s=new WeakMap,n=new WeakMap},46832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.posixFileToUriPath=t.toUriPath=void 0;const r=i(53265),s=i(45200),n=i(22573),a=i(68708),o=i(54993);async function l(e,t){if((0,a.isObject)(e)&&!(0,n.blank)(e.nativePath)&&!(0,n.blank)(e.uri))return e;const i=(0,r.resolve)((0,o.toS)(e)),l=await t??await(0,s.nativePath2uri)(i);return null==l?void 0:{nativePath:i,uri:l.toString()}}t.toUriPath=l,t.posixFileToUriPath=function(e){return l(e.nativePath,e.uriObject_())}},7656:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.DirectAssetCountForTagQuery=t.RecursiveAssetCountForTagQuery=t.nonLeafTagIds=void 0;const r=i(50213),s=i(56038),n=i(95704),a=i(38156),o=i(42659),l=i(45599),u=i(41400),c=i(31586),d=i(51926),h=(0,l.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function f(e){return e.prepare((0,d.compressWhitespace)("SELECT"," t1.id,"," count(t2.id) AS cnt","FROM"," Tag t1"," JOIN Tag t2 ON t1.id = t2.parentId","GROUP BY"," 1","HAVING"," cnt > 0")).pluck().all()}async function m(e,i=[]){const r=e.prepare(t.RecursiveAssetCountForTagQuery).pluck(),o=e.prepare(t.DirectAssetCountForTagQuery).pluck(),l=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId"),c=new Set(f(e)),d=new a.PushProgressObserver({op:"Rebuilding tag asset counts"},e.prepare("SELECT count(*) FROM Tag").pluck().get());await(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e){const e=!c.has(t);(0,s.timeSync)("db.rebuildTagAssetCounts("+(e?"leaf":"cte")+")",(()=>{const s=(e?o:r).get({tagId:t});l.run({tagId:t,assetCount:s,updatedAt:Date.now()}),d.incrProgress(),h().debug("_rebuildTagAssetCounts()",{isLeaf:e,whereClauses:i,tagId:t,assetCount:s})})),t%10==0&&(h().throwIfAborted_(),await(0,u.delay)(1))}}}),d.completed()}t.nonLeafTagIds=f,t.RecursiveAssetCountForTagQuery=(0,d.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.DirectAssetCountForTagQuery=(0,d.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," AssetTag"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," AssetTag.tagId = :tagId"," AND Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL;"),t.rebuildTagAssetCounts=async function(e,t=o.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>m(e,["assetCount IS NULL"]))),(0,c.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rm(e)))}},69032:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(1728),c=i(56038),d=i(34102),h=i(49076),f=i(69589),m=i(28874),p=i(42231),g=i(85087),y=i(98770),w=i(59107),v=i(63870),b=i(7014),S=i(22573),P=i(42659),M=i(41400),_=i(75240),T=i(31586),E=i(34666),D=i(51926),k=i(75020),x=i(54017),F=i(48723),C=i(98784),A=i(7656),I=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>C.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return I().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=((0,o.isTest)()?5:30)*P.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=I().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),F.Tag.validate_(),s.throwIfAborted_(i?.halt),await L(),i.recountAllTags&&(s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)(),s.info("rebuilding tag asset counts..."),await(0,A.rebuildTagAssetCounts)(F.Tag.dbl.db().db,0))}catch(e){I().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,T.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),I().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const L=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{I().info("updating tag mountpoints...");const e=F.Tag.findByPath([k.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await N(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function R(){t.tagFtsRebuild.unset(),L.unset()}async function N(e){if(null==e||2!==e.depth||!e._path.startsWith(k.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===k.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),F.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,v.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,_.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),F.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,M.later)((()=>{(0,d.ee)().on("clearCache",R),m.Settings.libraryDir.watchLater(R)})),t.fixFileRootTag=N,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,D.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,v.volumeMetadataTtlMs)()}),(0,M.later)((()=>{w.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},16436:e=>{"use strict";e.exports=require("@sentry/node")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},87550:e=>{"use strict";e.exports=require("better-sqlite3")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},66150:e=>{"use strict";e.exports=require("fast-xml-parser")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},31832:e=>{"use strict";e.exports=require("knex")},51168:e=>{"use strict";e.exports=require("luxon")},93973:e=>{"use strict";e.exports=require("ml-kmeans")},4927:e=>{"use strict";e.exports=require("papaparse")},83058:e=>{"use strict";e.exports=require("picomatch")},57272:e=>{"use strict";e.exports=require("plist")},85949:e=>{"use strict";e.exports=require("process")},57160:e=>{"use strict";e.exports=require("punycode.js")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},93944:e=>{"use strict";e.exports=require("source-map-support")},49378:e=>{"use strict";e.exports=require("trash")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},29907:e=>{"use strict";e.exports=require("cluster")},76982:e=>{"use strict";e.exports=require("crypto")},34589:e=>{"use strict";e.exports=require("node:assert")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=34742);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/web.js b/bin/web.js index c075204..98056d9 100755 --- a/bin/web.js +++ b/bin/web.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463:(e,t,i)=>{const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,s),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223:e=>{const t=36e5,i=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const r=i.exec(e);if(!r)throw new TypeError(`invalid time period format ("${e}")`);const s=parseFloat(r[1]);switch(r[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*s);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*s);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(s*t);case"day":case"days":case"d":return Math.round(864e5*s);case"week":case"weeks":case"w":return Math.round(6048e5*s);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*s)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227:(e,t,i)=>{const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120:(e,t,i)=>{const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827:(e,t,i)=>{const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015:(e,t,i)=>{const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function T(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function D(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=T,t.least=function(e){return T(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=k,t.collectBatched=function(e,t,i){const s=[];for(const n of k((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of k((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await D(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),b=i(99331),S=i(95937),P=i(98314),_=i(38835),T=i(70025),M=i(8769),E=i(43334),k=i(95402),D=i(28874),x=i(63870);class C extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>n(this,r,"m",s).call(this)),i,"worker"===e?(0,x.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,k.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,S.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&k.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,b.ending)()||!0===(0,T.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,r=new WeakSet,s=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(E.isWin?3:1)*c.minuteMs,maxTasksPerProcess:D.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:D.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:D.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,x.commandTimeoutMs)(),taskTimeoutMillis:D.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,s.set(this,void 0),n.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,s,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]=t))}get length(){return u(this,n,"f")}set length(e){l(this,n,(0,d.clamp)(0,u(this,n,"f"),e),"f")}clear(){this.length=0}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,n,"f")),e<0||e>=u(this,n,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,s,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,n,"f"){u(this,s,"f")[e]=c}));return u(this,n,"f")}pop(){return u(this,r,"m",o).call(this,u(this,n,"f")-1,(e=>{var t;return l(this,n,(t=u(this,n,"f"),--t),"f"),u(this,s,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,n,"f"){u(this,s,"f")[e]=c,l(this,a,e,"f")}));return u(this,n,"f")}shift(){return u(this,r,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,n,(i=u(this,n,"f"),--i),"f"),u(this,s,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",o).call(this,u(this,n,"f")-1-e,(e=>{const i=u(this,s,"f")[e];u(this,s,"f")[e]=u(this,s,"f")[t],u(this,s,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=n(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),s=i(31586),n=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),s=i(65843),n=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),s=i(20014),n=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)((()=>!1))},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),s=i(98553);var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},57206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(77988),s=i(51168),n=i(45599),a=i(98553),o=i(68708),l=i(24689),u=i(21330),c=i(57159),d=i(28544),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},19851:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?T():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const _={timeoutMs:10*a.secondMs};async function T(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=T,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),s=i(32105),n=i(14593);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),s=i(55835),n=i(59455),a=i(48884);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),s=i(54557);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},26033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._isSupportedNode=t.RequiredNodeRange=t.isSupportedNode=void 0;const r=i(45599),s=i(76280);function n(e=process.versions.node){return(0,s.semverSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange="18||20||21",t._isSupportedNode=n},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),s=i(42659),n=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,s]of(0,l.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,l.keys)(e))if(r[n]=t(n,e[n]),s++,(0,o.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,n.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),s=i(73024),n=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return A();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function _(){return"ubuntu"===(0,t.osDistributionLinux)()}function T(){return"fedora"===(0,t.osDistributionLinux)()}function M(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=_,t.hasApt=function(){return P()||_()},t.isFedora=T,t.isAlpine=M;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},k={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return D(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function A(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":D(e,k);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=A,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(A())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(_())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(T())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(M())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},45393:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=4},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(72993),s=i(50213),n=i(23560),a=i(43334);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(85949).title=t}catch(e){(0,s.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},92782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),s=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),s=i(56409),n=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return s.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),s=i(54993);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),b=i(24399),S=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let T=!0;const M=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),T)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;T=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(1708)),n=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),s=i(57150),n=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,n.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,s.logStartup)())}},28850:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),s.set(this,void 0),n(this,r,e,"f")}_call(){return(0,l.time)(a(this,r,"f")+(null==a(this,s,"f")?"(local)":"(remote)"),null==a(this,s,"f")?this.impl():a(this,s,"f").call(this))}setShim(e){n(this,s,e,"f")}hasShim(){return null!=a(this,s,"f")}clearShim(){n(this,s,void 0,"f")}}r=new WeakMap,s=new WeakMap},12089:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=a,s.set(this,void 0),n.set(this,void 0),l(this,s,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",a).call(this,e),(()=>u(this,r,"m",o).call(this,e)))}setShim(e){l(this,n,e,"f")}hasShim(){return null!=u(this,n,"f")}clearShim(){l(this,n,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",a).call(this,e))}}s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,s,"f")+(null==u(this,n,"f")?"(local)":"(remote)"),null==u(this,n,"f")?this.impl(e):u(this,n,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return s(this,r,"f")[Symbol.iterator]()}get length(){return s(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=s(this,r,"f").length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),a=this.valueOf(s(this,r,"f")[n]);if(e===a)return{found:!0,index:n};e>a?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&s(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...s(this,r,"f")];const a=t=>t<0||t>s(this,r,"f").length-1?null:(i??this.diff)(s(this,r,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return s(this,r,"f").shift()}at(e){return(0,a.at)(s(this,r,"f"),e)}toA(){return[...s(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===s(this,r,"f").length-1){const e=[...s(this,r,"f")];return s(this,r,"f").length=0,e}return s(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return s(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),s=i(82328),n=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),s=i(95705);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" …(+"+s+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function T(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=T;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(T(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['‘’].*['‘’]$/,k=/^["“”„«»〃].*["“”„«»〃]$/;function D(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||k.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const A=/#.*$/gm;t.stripComments=function(e){return e.replace(A,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=_;const T=/[^\da-z]+/gi;function M(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(T,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=M,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),s=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},88264:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TTLArray=void 0;const r=i(31586);class s{constructor(e,t){this.ttlMs=e,this.maxLength=t,this.times=[],this.a=[],this.expirationListeners=[]}[Symbol.iterator](){this.vacuum();const e=[...this.a];return function*(){for(const t of e)yield t}()}push(...e){(0,r.times)(e.length,(()=>this.times.push(Date.now()))),this.a.push(...e),null!=this.maxLength&&this.vacuum()}pushUniq(...e){e.forEach((e=>{this.includes(e)||this.push(e)}))}includes(e){return this.vacuum(),this.a.indexOf(e)>=0}find(e){return this.vacuum(),this.a.find(e)}some(e){return this.vacuum(),this.a.some(e)}shift(){return this.vacuum(),this.times.shift(),this.a.shift()}first(){return this.vacuum(),this.a[0]}last(){return this.vacuum(),this.a[this.a.length-1]}shiftOrFirst(){return this.length>1?this.shift():this.first()}pop(){return this.vacuum(),this.times.pop(),this.a.pop()}onExpire(e){this.expirationListeners.push(e)}slice(e,t){return this.vacuum(),this.a.slice(e,t)}get length(){return this.vacuum(),this.a.length}clear(){return this.times.length=0,this.a.length=0,this}get values(){return this.vacuum(),[...this.a]}map(e){return this.vacuum(),this.a.map(e)}oldestEntryAge(){return this.vacuum(),this.times[0]}vacuum(){if(0===this.a.length)return;const e=this.a.length;if(null!=this.maxLength){const e=this.a.length-this.maxLength;this.times.splice(0,e),this.a.splice(0,e)}const t=Date.now()-this.ttlMs,i=this.times.findIndex((e=>e>t));if(-1===i?this.clear():i>0&&(this.times.splice(0,i),this.a.splice(0,i)),e!==this.a.length)for(const e of this.expirationListeners)e()}}t.TTLArray=s},75387:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},65211:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(19851),s=i(76790),n=i(22573),a=i(54993),o=i(7282),l=i(55222);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!(0,o.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),u=0}},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),s=i(55835),n=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},79184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(59455),s=i(48884),n=i(22859),a=i(28874),o=i(79781),l=i(92434);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(50357),o=i(55835),l=i(31586),u=i(68708),c=i(12168),d=i(23467),h=i(73168),f=i(50213),m=i(86580),p=i(48368),g=i(80361),y=i(28874),v=i(28544),w=i(75767),b=i(16170),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} ≠ ${o}`}function _(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function T(e,t){return[_(e),_(t)]}function M(e,t,i){const r=(0,w.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.aKey}:${r.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=v.CapturedAt.fromAssetFile(e),f=v.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const _=a.isFuzzy||f.isFuzzy;if(_&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",T)??P(e,i,"model",T);if(null!=E)return E;const k=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),D={cameraId:M(e,i,"cameraId")??null,imageId:M(e,i,"imageId")??null,lensId:M(e,i,"lensId")??null,exposureSettings:(0,w.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(k,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(k)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:D});const x=(0,s.compact)((0,u.values)(D));if((0,s.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:_});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(D).filter((e=>null==D[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos ≠ images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=E(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},13991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(19851),s=i(55835),n=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),v=i(14036),w=i(45200),b=i(34238),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function _(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>T(e*t)))}function T(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function M(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=_,t.sortScale=T,t.mtime2sort=M;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function k(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function D(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=_(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:M(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=D(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=k,t.assetFileSortCriteriaPojo=D,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of k(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),s.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,n(this,s,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return n(this,s,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,n(this,s,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=n(this,r,"f")&&clearTimeout(n(this,r,"f")),a(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,s=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(87997)),n=i(31586);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),b=i(45599),S=i(26905),P=i(55835),_=i(31586),T=i(68708),M=i(20214),E=i(57153),k=i(85556),D=i(50213),x=i(70025),C=i(95937),A="TIMEOUT",F=(0,b.defer)((()=>(0,D.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,_.gt0)(t)?new s(A).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const s=i[r];if(s.isSettled){if(s.name===A)return void F().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield s.value}}if(i.every((e=>e.name===A)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,T.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new k.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,s=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},83412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DoneWrapper=void 0;const r=i(56409),s=i(38836);class n extends s.EndableWrapper{constructor(){super(...arguments),this.doneLatch=new r.Latch}isDone(){return this.doneLatch.isSettled()||this.ended}donePromise(){return this.doneLatch.promise}}t.DoneWrapper=n},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,s.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,s=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},39250:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(23838),a=i(54993),o=i(15674),l=i(73568),u=i(76740),c=i(99331),d=i(42638);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new d.Promises(e,t)}vacuum(){return s(this,r,"f").filterInPlace(((e,t)=>t.isPending&&!0!==t.payload?.aborted)),s(this,r,"f").valueCount()}enqueue({key:e,abortable:t,fn:i}){for(const t of s(this,r,"f").get(e)??[])t.payload?.abort("aborted by new work");if(this.vacuum(),(0,c.ending)())throw new l.AbortError("ending");const n=t??new u.Abortable,o=this.p.serial((0,a.toS)(e),(()=>i(n)),n);return s(this,r,"f").add(e,o),o}},r=new WeakMap},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new b(e,t,i,r)};class b extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,n,0,"f"),d(this,s,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,r,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,n,"f")}isStale(){return null==c(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,s,"f")?void 0:Date.now()-c(this,s,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,n,(i=c(this,n,"f"),++i),"f")}},u=function(e){d(this,s,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),s=i(80049);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},22781:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),s.set(this,!1),n.set(this,!1)}_call(){return a(this,s,"f")?(o(this,n,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,r,"f")):(o(this,s,!0,"f"),o(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,s,!1,"f"),!0===this.runLaterIfBusy&&a(this,n,"f")&&(o(this,n,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,s,"f")}prior(){return a(this,r,"f")}async force(){return await a(this,r,"f"),this._call()}}r=new WeakMap,s=new WeakMap,n=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var b=i(20214);async function S(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,l.gt0)(s)?(0,c.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function T({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const u=a??(o.length<=s?w.PermissivePromises:new w.Promises(i,(()=>s))),d=(0,l.gt0)(n)?e=>(0,c.thenOrTimeoutError)(t(e),n):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=S,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await S(s);r.push(...await S(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=T,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await T({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await T({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await T({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){s=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await T({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),b=i(73614);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function T(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),r=t();return T(e,Date.now()-i),r},t.pushTime=T,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>_(e,t)),i)}},42638:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),b=i(82647),S=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},59189:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(1708)),n=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),b=i(88158),S=i(45969),P=i(43334),_=i(28874),T=i(3790);function M(e){return E().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const E=(0,n.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,b.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const k=["HOME","LANG","USER"],D=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?k:D),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,S.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,_.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,o.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(s.default.env,(e=>M(e)||!(0,T.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:F({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let A=!1;function F({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,g.childProcLocale)():{},...C(r),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(s);if((0,y.isLogged)("debug")&&!A){A=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(s).map((([e,t])=>[e,(0,T.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return s}t.childEnv=F},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),b=i(22911),S=i(4867),P=i(73614),_=i(70025),T=i(57159),M=i(36868),E=i(66184),k=i(45643),D=i(95402),x=i(9727),C=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function A(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function F(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",A(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",A(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",A(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",A(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,D.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,k.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",A(e)),!0;{D.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,D.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,k.waitForPidExit)(i,5e3)}function I(e,i,r,s=0){const a=new Date,o=[];return(0,v.niceable)(i,r)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&F(e)}),s-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,D.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,E.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new b.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(a.stdin);const v=new d.Latch;null==a.stdout?v.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==a.stderr||s?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,S.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,S.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,S.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const E=p.join("");(0,l.notBlank)(E)&&g.push(new Error(E)),!r&&(0,o.isNotEmpty)(g)&&C().warn(f+" resulted in errors:",g);const k=i.isIgnorableError??_.isIgnorableError,D=g.filter((e=>!0!==k(e)));if(D.length>0)throw 1===D.length?D[0]:new T.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!n&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:E}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,D.killPid)(a.pid,!0),e}}t.endProcess=F,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},86335:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(77598),u=o(i(1708)),c=i(19851),d=i(40958),h=i(22573),f=i(50268),m=i(68708),p=i(5670),g=i(50989),y=i(12168),v=i(59455),w=i(41583),b=i(54993),S=i(80875),P=i(50213),_=i(81168),T=i(27395),M=i(25764),E=i(59958),k=i(70025),D=i(83278),x=i(85021),C=i(29325),A=i(43334),F=i(28874),I=i(84777),O=i(55534),L=i(85100),R=i(34330),N=(0,c.lazy)((()=>(0,P.mkLogger)("child.ChildService")));async function B(e){const t=(0,_.ensureSuffix)(e,".js"),i=D.BaseFile.projectRoot(),r=D.BaseFile.for(u.default.cwd()),s=(0,C.isPacked)()?[i.join("bin",t),A.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];(0,C.isPacked)()||(A.isElectron?(s.push(r.join("dist","app",t)),s.push(i.join("src","desktop","dist","library",t))):s.push(i.join("src","library","dist","library",t)));for(const e of s)if(null!=e&&!0===await e.isNonEmptyFile((0,C.isPacked)()?y.KB:128))return N().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:C.isPacked,paths:s.map(b.toS)}});return N().throw("Failed to find path to "+e,{paths:s,fatal:!0})}t.pathToService=B,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=(0,g.strEnum)(...p.ServiceNames.pick("web","sync"));class j{static async mk_(e,t={}){const i=t.pathToService??await B(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,v.toA)(t.nodeArgs),new j(e,i,t)}constructor(e,t,i){var o,l;r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,L.serviceExitTimeoutMs)(e),this.logger=(0,P.mkLogger)(this.name);const c=[...(0,v.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&c.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale","forWorker"),this.spawnOpts.forceCLocale=!1,(l=(o=this.spawnOpts).env??(o.env={}))[E.UV_THREADPOOL_SIZE]??(l[E.UV_THREADPOOL_SIZE]=(0,b.toS)(("web"===e?F.Settings.webUvThreads:F.Settings.syncUvThreads).valueOrDefault)),this.wc=new R.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&await(this.opts.onPreRestart?.()),this.restartCount++,(0,I.spawn)(u.default.execPath,c,-1,this.spawnOpts)),endableRank:M.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:a(this,r,"m",n).bind(this),onStderr:a(this,r,"m",s).bind(this),onError:this.opts.onError??(e=>!1===(0,k.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:O.ServiceExitCommand,...i}),(0,T.addEndable)(M.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(x.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(O.ServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,_.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,w.toErr)(i)),this.write(e,t-1)}}}t.ChildService=j,r=new WeakSet,s=function(e){const t=(0,S.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},n=function(e){if(!(0,h.blank)(e))try{const t=(0,S.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){const e="failed"===t.state||"error"===t.level;this.logger.log(e?"error":"info",".onStdout(): health check summary",t),e&&this.wc.onError(this.name+".onStdout()",t,e)}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),s=i(41400),n=i(19851),a=i(28874);(0,s.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,n.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},85100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(23560),s=i(28874),n=i(45255);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?s.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},34330:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),b=i(25764),S=i(99331),P=i(42638),_=i(38835),T=i(8769),M=i(57159),E=i(66003),k=i(50213),D=i(45643),x=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new A({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class A{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,k.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new M.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,T.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=A,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,T.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,T.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),s=i.sibling(r);if(s.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",s.posixPathFrom((0,l.examples)()));const n=(0,d.originalsDir)();if(s.isSelfOrDescendantOf(n))return a.join("$library",s.posixPathFrom(n));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",s.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(6858),a=i(1708),o=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return s(this,r,"f").push(...e),this}async parse(e=a.argv,t){let i=(0,m.addHelpFooter)(new n.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of s(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":o.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,a.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of s(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),s=i(38639),n=i(17181),a=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,s.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),a.Settings.logColor.envValue=e,(0,n.setupLogFormatter)()}))}}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(1708)),n=i(22573),a=i(38639);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},53978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},43380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(28874),s=i(2858),n=i(22573),a=i(38639),o=i(46292);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},54772:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return _(w(e))}function y(e){return(0,f.clampRGB)(M(T(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function T(e){const[t,i,r]=v(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function M(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=_,t.lab2xyz=T,t.xyz2rgb=M,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const k=new Map;function D(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return A(x(e))}function A(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function F(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function I(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(k,e,(()=>D(e,t))):D(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(F(e))},t.hsv2hsl=A,t.hsl2hsv=F,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},42079:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(31586),s=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),v=(0,s.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let _=y*v==0?0:b-w;_-=2*(_>Math.PI?1:0)*Math.PI,_+=2*(_<-Math.PI?1:0)*Math.PI;const T=2*(0,s.sqrt)(y*v)*Math.sin(_/2),M=(i+c)/2,E=(y+v)/2;let k;y*v==0?k=w+b:(k=(w+b)/2,k-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,k+=2*(k<0?1:0)*Math.PI);const D=(M-50)**2,x=1-.17*Math.cos(k-Math.PI/6)+.24*Math.cos(2*k)+.32*Math.cos(3*k+Math.PI/30)-.2*Math.cos(4*k-63*Math.PI/180),C=1+.015*D/(0,s.sqrt)(20+D),A=1+.045*E,F=1+.015*E*x,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*k-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*I)*O;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*A),2)+Math.pow(T/(o*F),2)+L*P/(a*A)*T/(o*F))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(40958),s=i(31586),n=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},32848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(48884),o=i(31843),l=i(70417),u=i(3048);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},40401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),v=i(85810),w=i(3048),b=i(76490),S=i(1971),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=T[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function D(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(_.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...M,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&D(g-1);const n=s.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n),2);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const A=(0,c.leastBy)(C,(e=>e.score));if(null==A)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),k(a,t);const F=(0,o.stringify)({...A?.description,elapsedMs:Date.now()-i}),I=(0,n.sortBy)(A?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:F,score:A?.score,totalColors:a.size,totalPixels:f.length,iters:A?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:F,dominantColorScore:A?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const _=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],T={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},M=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:T[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function k(e,t){const i=e.countSum,r=e.size;D(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function D(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{M.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=k,t.mergeLabhashes=D,t.mergeNearCentroids=x},85409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(31586),s=i(68708),n=i(50989);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),v=i(21330),w=i(928),b=i(54261),S=i(73389),P=i(51275),_=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function T(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function M(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function k(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void _().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=M(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function A(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=T,t.toDated=function(e){return T(e)?e:void 0},t.mapDated=function(e,t){return T(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=M,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):k(e)},t.datedToDateTime=k,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(A(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=D(e)),r??(r=D(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,v.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=A,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),s=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),s=i(31586),n=i(54557),a=i(91655),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),s=i(40958),n=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),v=i(79842),w=i(66649),b=i(98247),S=i(98725),P=i(928),_=i(54261),T=i(73389),M=i(89724),E=i(17415),k=i(88600),D=i(51275);function x(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,k.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(S.ISO_YMD_RE.exec(e)?.groups??S.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tx(e))).join("-")}toLocal(){return(0,M.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function A(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,_.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,E.zoneToTzOffsetMinutes)((0,w.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(s=>(0,d.map)((0,P.getDay)(e),(n=>(0,d.map)((0,P.getHour)(e),(a=>(0,b.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,h.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${x(n)}:${x(a)}`},t.toExifDateTime=A,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,T.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,_.hasTime)(e)||(i??(0,v.datedToPrecisionMs)(e))>=c.dayMs?O(e):A(e,(0,D.getZoneName)(e))?.toISOString({includeOffset:t})};const F="yyyy:MM:dd HH:mm:ss.SSS",I=F+"ZZ";function O(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>x(e))).join(t)}function L(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(w.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,v.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,D.hasZone)(t)?I:F):void 0},t.datedToYMD=O,t.toFuzzyDate=L,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,w.datedToMillis)(e)||null==(0,w.datedToMillis)(t))return;const[s,n]=[e,t].map((e=>(0,w.datedToMillis)(e))).sort(),o=(n-s)/(r+1),l=(0,D.getZoneName)(e),u=l===(0,D.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,_.hasTime)(e)))?L(c):c},t.setZone=function(e,t,i){const r={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,D.hasZone)(e)},s=(0,E.normalizeZone)(t);return null!=e&&null!=s&&(0,_.hasTime)(e)?e instanceof y.DateInterval?e.setZone(s,r):A(e)?.setZone(s,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,v.datedToDateTime)(e);if(null==i)return;const r=(0,D.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),v=i(68852),w=i(4001),b=i(28874),S=i(24689),P=i(79842),_=i(66649),T=i(98247),M=i(21330),E=i(54261),k=i(73389),D=i(16400),x=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,_.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,k.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const A=new Map;function F(e,t,i){try{const r=(0,T.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(A,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,T.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,T.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:T.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>F(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const e of n){const t=a(e);if(null!=t&&(0,x.isValidDate)(t))return t}}t.parseDated=I;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;M.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return M.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),s=i(31586),n=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),s=i(31586),n=i(68708);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),s=i(19851),n=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,s.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?T(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(T(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function _(e,t){return T(Date.now()-e,t)}function T(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},42499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(51168),s=i(19851),n=i(19043),a=i(28874);t.setupLuxon=(0,s.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,n.locale)()}))},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=_,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:_(i)};const T=/\b(?Z|UTC|GMT)\b/,M=/(?[-±+−])/,E=/[-−]/,k=/(?[01]\d)/,D=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:A((0,t.TimezoneOffsetRE)().exec(e))}function A(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return v(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),T,new m.RegExpEscaped("|"),M,k,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=A;const F=/\b(?(?:Etc\/)?GMT)\b/,I=(0,n.lazy)((()=>(0,m.concatRegexp)([F,M,D,m.RegExpOptional.from(x)])));function O(e){return A(I().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return _(i);if(null!=t){const i=S(e);if(null!=i)return _(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),v=(0,s.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),w=(0,s.lazy)((()=>(0,n.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),b=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,p.datedToISO)(e)))))),S=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,y.datedToLocal)(e)))))),P=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,m.datedToMillis)(e))))));function _(e){if(null==e)return!1;const t=M(e);return v().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return _(e)?e:void 0},t.isValidDate=_;const T=String(new Date("bad"));function M(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===T)return T;const t=(0,n.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,E())&&s.push("year is in the future"),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):S().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):b().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(t)).join("; "))}catch(t){return v().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=M;const E=(0,s.lazy)((()=>r.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return _(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==M({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),s=i(31586),n=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},82261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},92407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(19851),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},55332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(19851),s=i(50213),n=i(76187),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},91872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i,r){const a=Date.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}))}},12943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(79842),s=i(66649),n=i(40958),a=i(68708);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},65753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(19851),s=i(7282),n=i(28874);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*((0,s.isTest)()?.25:5))))},80632:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(54993),u=i(50213),c=i(23560),d=i(65211),h=i(29882),f=i(53265),m=i(66430),p=i(66184),g=i(28874),y=i(15674),v=i(87550);function w(){const e=g.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,a.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=g.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=g.Settings.logSql.valueOrDefault}){e=(0,f.resolve)(e),(0,h.mkdirpSync_)((0,r.dirname)(e));const b=(0,h.posixPathFromGrandparent)(e),S=(0,m.nativePathSizeSync)(e),P=(0,u.mkLogger)("db.mkdb("+b+")");if(null!=S){const E=Math.round(S/o.MiB),k=Math.ceil(1.5*E);k>g.Settings.dbCacheSizeMb.valueOrDefault&&(P.info("Dynamically setting dbCacheSize to "+g.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:E}),g.Settings.dbCacheSizeMb.envValue=k);const D=Math.round(1.5*E);D>g.Settings.maxMemoryMb.valueOrDefault&&(P.warn("Large database: setting maxMemoryDb to "+D+"MB",{dbFileSizeMb:E,"Settings.maxMemoryMb":g.Settings.maxMemoryMb.valueOrDefault}),g.Settings.maxMemoryMb.envValue=D)}P.info("Opening "+e+"...");const _={fileMustExist:!1,readonly:!1};if((0,a.gt0)(t)&&(_.timeout=Math.ceil(t)),i){const x=(0,u.mkLogger)("SQLite("+b+")"),C=(0,p.defaultLogLevel)();function A(e,...t){var i;(0,n.blank)(e)||x.log(C,(i=e,(0,l.toS)(i).replace(/\s{2,}/g," ")),{args:t})}_.verbose=A}const T=new v(e,_);P.info("Open. Setting PRAGMAs...");for(const F of(0,s.compact)(['encoding = "UTF-8"',"threads = "+(0,y.maxCpus)(),"foreign_keys = ON","page_size = "+w(),"trusted_schema = 0","cache_size = -"+Math.round(g.Settings.dbCacheSizeMb.valueOrDefault*o.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL",(0,a.gt0)(g.Settings.dbBusyTimeoutMs.valueOrDefault)?"busy_timeout = "+g.Settings.dbBusyTimeoutMs.valueOrDefault:null,"temp_store = MEMORY","synchronous = "+g.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,c.isDbJanitorService)()?(0,l.toS)(g.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+g.Settings.dbAutoVacuumMode.valueOrDefault]))P.tapThunk({msg:"PRAGMA "+F,result:()=>T.pragma(F)});const M=T;return M.__uid=(0,d.uid)(),M},t.pageSizeBytes=w},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},95704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(40958),s=i(31586),n=i(59455),a=i(65753),o=i(51040);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},76187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(17217),s=i(87391),n=i(7311);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},51040:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+$/gm,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(19851),s=i(50357),n=i(30976),a=i(50213),o=i(95696),l=i(80632),u=i(76187),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},87391:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},27180:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(5916),s=i(84777),n=i(89966),a=i(63870),o=i(87550);t.sqliteVersion_=(0,r.lazyAsync)({desc:"db.sqliteVersion",later:async function(){let e;try{e=new o(":memory:");const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,n.sqliteNativePath_)(),r=(await(0,s.stdout_)(i,["-version"],{timeoutMs:(0,a.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:r.split(/\s+/,1)[0],fullToolVersion:r,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,a.commandTimeoutMs)()})},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),b=i(29882),S=i(45969),P=i(43334),_=i(28874),T=i(41692),M=i(32774),E=i(80612),k=i(32551),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function x(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function C(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:M.DefaultDockerLibraryDir},...x()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,k.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,k.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,k.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...x()),i}t.tmpCacheDirs=x,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:x(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:C(),desc:"cache"})));const A=(0,d.lazy)((()=>{(0,T.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(F)}));function F(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{A();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,b.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),s=i(45969),n=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},79960:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(45255),o=i(84777),l=i(16287),u=i(57902),c=i(43334),d=(0,r.lazy)((()=>(0,n.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,o.stdout_)("defaults",h,{timeoutMs:a.ShortCommandTimeoutMs});if((0,s.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),s=i(45969),n=i(32774);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),s=i(96706),n=i(29882);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),s=i(49776),n=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},48195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotLibraryDir=t.isLibraryDir=void 0;const r=i(19851),s=i(22573),n=i(98553),a=i(12168),o=i(50213),l=i(15056),u=i(98314),c=i(17217),d=i(16287),h=i(2858),f=i(87290),m=(0,r.lazy)((()=>(0,o.mkLogger)("dir.IsLibraryDir")));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),s=i(54993),n=i(29882),a=i(28874);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),s=i(55835),n=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e),!1)}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function T(e){return y(_(e))}async function M(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await T(t),await M(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=T,t.setupLibraryDbDir_=M},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),s=i(7282),n=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),s=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),b=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,n.join)((0,m.homeDir)(),".psenv"));const t=(0,b.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,d.debom)(s.default.readFileSync((0,g.resolve)(r))),n=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(n))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),s=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(1708)),n=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),s=i(19851),n=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),s=i(26905),n=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},68301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(19851),s=i(42659),n=i(75240),a=i(55835),o=i(31586),l=i(68708),u=i(59455),c=i(54993),d=i(50213),h=i(45255),f=i(37628),m=i(99331),p=i(46292),g=i(38835),y=i(32144),v=i(29882),w=i(95696),b=i(55222),S=i(28874),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function _(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class T{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*s.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=s.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),s=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=s,meta:{event:_(e),recentEventCount:r,maxErrorsPerDay:s,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:_(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:_(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=T,T.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new T(w.PosixFile.for(e).join("events"))))))},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),s=i(38639),n=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function b(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function S(e){return!!((0,s.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||b(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=b,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===S(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=S;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),s=i(31586),n=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),s.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(n(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),s=i(19851),n=i(15197);t.ee=(0,s.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new n.CapturingEventEmitter(e)}))},41293:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiHealthRouter=void 0;const s=r(i(7252)),n=i(45599),a=i(18454),o=i(51773);t.ApiHealthRouter=class{constructor(e="/api/health"){this.mountpoint=e,this.router=(0,n.defer)((()=>s.default.Router().get(this.mountpoint,(0,o.wrap)(this.constructor.name+".health",this.health)))),this.health=async(e,t)=>{t.json(await a.HealthCheck.awaitSettled())}}}},51773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableCache=t.truthyQuery=t.extractLang=t.requestLang=t.extractTagPath=t.jsonOrRedirect=t.getSeedOrRedirect=t.getFit=t.getSeed=t.wrap=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(97790),u=i(97238),c=i(99036),d=i(41942),h=i(54993),f=i(48884),m=i(50213),p=i(97352),g=i(56038),y=i(38835),v=i(57159),w=i(51140),b=i(68178),S=i(62327),P=(0,r.lazy)((()=>(0,m.mkLogger)("express.Handlers")));function _(e){return(0,l.opt)(e).filter(n.notBlank).map(h.toS).map((e=>e.split(","))).map(s.compactBlanks).map((e=>e.map((e=>e.split(";").map((e=>e.trim())))))).flatMap((e=>(0,f.greatestBy)(e,(([,e])=>(0,p.firstGt0)((0,p.extractFloat)(e),1))))).map((([e])=>e)).get()}t.wrap=function(e,t){return async(i,r,s)=>(0,g.time)(e,(()=>(0,S.wrapWithToast)({f:()=>t(i,r,s),response:r})))},t.getSeed=function(e){return(0,u.toSeed)(e.query.seed)},t.getFit=function(e){return c.ThumbFits.validOrElse((0,h.toS)(e.query.fit),c.ThumbFits.square)},t.getSeedOrRedirect=function(e,t){const i=(0,u.toSeed)(e.query.seed);if(null==i){let i=(0,b.requestedUri)(e);"/tag/"===i.path&&(i=i.with({path:"/tag"})),i.query.append("seed",(0,h.toS)((0,u.prngSeed)())),t.redirect(i.toString())}return i},t.jsonOrRedirect=function(e,t){if(null==e)return(0,S.sendErrorToast)(new v.WrappedError("Internal error: jsonOrRedirect(null)"+y.InternalErrorFlag,{fatal:!1,doNotSend:!0}),t,404);for(const i of[d.XLocationRedirect,d.XLocationReplace]){const r=e[i];(0,n.notBlank)(r)&&(P().debug("jsonOrRedirect(): "+i,r),t.setHeader(i,r),t.status(w.HttpStatus.SeeOther))}return t.json(e)},t.extractTagPath=function(e){const t=e.replace(/^(?:\/api)?\/tag\/?/,""),i=t.split("/").map(decodeURIComponent),r=(0,n.blank)(t)?[]:i;return P().info("extractTagPath()",{path:e,result:r,trimmed:t,tagPath:i}),r},t.requestLang=function(e){const t=e.headers["accept-language"];return _(Array.isArray(t)?t.join(","):t)},t.extractLang=_,t.truthyQuery=function(e,t){return(0,o.mapOr)(e.query[t],(e=>!(0,a.isFalse)(e)),(()=>!1))},t.disableCache=function(e){e.setHeader("Cache-Control","no-store, max-age=0"),e.setHeader("Pragma","no-cache"),e.setHeader("Expires","Fri, 01 Jan 1990 00:00:00 GMT")}},68259:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onFinished=void 0,t.onFinished=function(e,t){let i=!1;e.on("error",(r=>{i||(i=!0,t(r,e))}));const r=()=>{i||(i=!0,t(null,e))};for(const t of["end","finish","close"])e.on(t,r);return e}},27821:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.redirectRouter=void 0;const s=r(i(7252)),n=i(49586),a=i(51140),o=i(62327);t.redirectRouter=function(e){return s.default.Router().use(((t,i)=>(0,n.isAjaxRequest)(t.headers)?(0,o.sendRedirectionToast)({response:i,redirectOrReplace:"redirect",url:"/splash"}):i.redirect(a.HttpStatus.Found,e)))}},40749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.referrer=t.isXhr=void 0;const r=i(54993),s=/^XMLHttpRequest$/i;t.isXhr=function(e){return e.xhr||null!=s.exec((0,r.toS)(e.header("X-Requested-With")))},t.referrer=function(e){return e.header("Referer")}},78147:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RequestLogger=void 0;const r=i(7252),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(50213),u=i(8769),c=i(18454),d=i(51576),h=i(43705),f=i(82647),m=i(28874),p=i(51140),g=i(68259),y=i(68178);t.RequestLogger=class{constructor(){this.logger=(0,l.mkLogger)("web.RequestLogger"),this.responseTimes=new f.Average,this.accessLogger=m.Settings.logWebRequests.valueOrDefault?new h.LogWriter((0,n.firstNotBlank)(m.Settings.logWebDir.valueOrDefault,m.Settings.logDir.valueOrDefault),{processName:(0,s.lazy)((()=>"webrequest"))}):void 0,this.router=(0,r.Router)().use(((e,t,i)=>{const r=Date.now(),s=e.method,n=`${e.protocol?.toUpperCase()}/${e.httpVersion}`,l=`${s} ${(0,y.requestedUri)(e)} ${n}`,h=e.path.startsWith("/sse/")||"/updates"===e.path||"/api/splash"===e.path||"/api/status"===e.path?void 0:setTimeout((()=>this.logger.warn("Request is still processing: "+l,{elapsedMs:Date.now()-r})),4*(this.responseTimes.p84??a.secondMs));(0,g.onFinished)(t,(i=>{(0,o.map)(h,clearTimeout),null!=i&&(0,u.onError)(l,{error:i});const a=p.HttpStatusIs.success(t.statusCode)||p.HttpStatusIs.redirect(t.statusCode),f=Date.now()-r,m={from_ip:e.ip,protocol:n,method:s,statusCode:t.statusCode,ok:a,elapsedMs:f,runState:c.HealthCheck.runState(),userAgent:e.headers["user-agent"]};null!=i&&(m.error=i),this.responseTimes.push(f),(0,d.logBroadcaster)()?.log(a?"info":"warn","HttpRequestLogger",l,m),this.accessLogger?.log("info","",l,m),null==d.logBroadcaster.prior()&&null==this.accessLogger&&this.logger.log(null==i&&a?"debug":"warn",l,m)})),i()}))}}},68178:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addXSettingsHandler=t.requestedUri=void 0;const r=i(19851),s=i(41400),n=i(98553),a=i(37805),o=i(89724),l=i(34102),u=i(81674),c=i(28874),d=i(34238),h=i(69385),f=(0,r.lazy)((()=>({protocol:"http",host:c.Settings.hostname.valueOrDefault??"localhost",url:"/"})));t.requestedUri=function(e,t){const i={...f(),...t};return d.URI.parse((e?.protocol??i.protocol)+"://"+(e?.headers?.host??i.host)+(e?.originalUrl??i.url))};const m=(0,r.lazy)((()=>"lite"));async function p(){m.set(await(0,u.t)()),y.unset()}const g=(0,r.lazy)((()=>(0,c.isProd)()?"":"+"+(0,o.nowLocal)())),y=(0,r.lazy)((()=>{const e={ver:a.version+g(),paused:(0,h.isPaused)(),ll_vh:c.Settings.lazyLoadExtraVh.valueOrDefault,tier:m()};return Buffer.from((0,n.stringify)(e)).toString("base64")}));(0,s.later)((()=>{(0,l.ee)().on("settingsChanged",(()=>y.unset())),(0,l.ee)().on("reloadLicenses",p),u.m.watch(p),(0,l.ee)().on("pause",(()=>y.unset())),(0,l.ee)().on("resume",(()=>y.unset()))})),t.addXSettingsHandler=function(e,t,i){t.setHeader("X-Settings",y()),i()}},43394:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serveStaticGz=void 0;const r=i(22573),s=i(54993),n=i(50213),a=i(56639),o=i(81168),l=i(38835),u=i(83278),c=i(14036),d=i(51773),h=/\.asar\/?/i;t.serveStaticGz=async function(e){const t=(0,n.mkLogger)("serveStaticGz"),i=u.BaseFile.for(e),f=await i.descendants((e=>e.ext.endsWith(".gz"))),m=(0,a.toMap)(f,(e=>(0,r.mapNotBlank)((0,c.extMimetype)((0,o.stripSuffix)(e.ext,".gz")),(t=>["/"+(0,o.stripSuffix)(e.posixPathFrom(i),".gz"),{contentType:t,nativePath:e.nativePath}]))));return t.debug("ready to serve",[...m.keys()]),0===m.size&&t.error("Can't read "+i+". Please visit https://forum.photostructure.com/ for help."+l.FatalErrorFlag),(0,d.wrap)("serveStaticGz",(async(e,i,r)=>{if(null!=e.path.match(h))return i.sendStatus(404);const n=m.get((0,s.toS)(e.path));return null==n?r():(t.debug("get",{path:e.path,result:n}),i.set("Content-Encoding","gzip"),i.set("Content-Type",n.contentType),i.sendFile(n.nativePath))}))}},18405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSentEventsRouter=void 0;const s=r(i(7252)),n=i(40958),a=i(22573),o=i(25764),l=i(38836),u=i(36868),c=i(72901),d=i(51773);class h extends l.EndableWrapper{constructor(e){super("SSERouter("+e+")",(()=>this.close()),o.EndableRanks.first),this.path=e,this.streams=[]}router(){return s.default.Router().get(this.path,(0,d.wrap)(this.name,this.updates.bind(this)))}async close(){await Promise.all(this.streams.map(u.endStream)),this.streams.length=0}async updates(e,t){if(this.ended)return void t.sendStatus(503);this.logger.info("Sending updates to "+(e.ip??e.ips));const i=(0,u.remoteDesc)(e.socket);t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"}),this.streams.push(t),t.once("error",(e=>{(0,n.removeSame)(this.streams,t),this.logger.warn("onError("+i+")",{error:e})})),t.once("close",(()=>{(0,n.removeSame)(this.streams,t),this.logger.debug("stream to "+i+" closed. ("+this.streams.length+" remain)")}));const r=(0,n.compact)(this.firstEvents(e,t));(0,n.isNotEmpty)(r)&&(this.logger.info("firstEvents",{firstEvents:r}),t.write((0,c.mkEventStream)(...r)))}endStream(e){(0,u.endStream)(e).catch((()=>{})),(0,n.removeSame)(this.streams,e)}writeToStreams(...e){const t=(0,c.mkEventStream)(...e);if(this.logger.info("writeToStreams",{events:e,payload:t}),!(0,a.blank)(t))for(const e of this.streams)if(!0===e?.closed||null==e?.socket)this.endStream(e);else try{e.write(t)}catch(t){null==e.socket||e.closed?this.endStream(e):this.logger.warn("writeToStreams failed to write to stream",{stream:(0,u.remoteDesc)(e.socket),error:t})}}}t.ServerSentEventsRouter=h},62327:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapWithToast=t.expressErrorHandlerWithToast=t.sendErrorToast=t.send404Toast=t.sendWarningServerToast=t.sendRedirectionToast=t.sendServerToast=t.requireEnabled=t.requirePlus=void 0;const r=i(19851),s=i(55835),n=i(41942),a=i(71050),o=i(27776),l=i(41583),u=i(50213),c=i(98314),d=i(70025),h=i(81674),f=i(49586),m=i(51140),p=i(68178),g=(0,r.lazy)((()=>(0,u.mkLogger)("express.ServerToastHelpers")));function y({response:e,toast:t,httpStatusCode:i,reload:r}){return(0,s.map)(i,(t=>e.status(t))),g().warn("sendServerToast()",{requestedURI:(0,p.requestedUri)(e.req),toast:t,httpStatusCode:i}),e.json({toast:t,reload:r})}function v(e,t,i){g().warn("sendErrorToast",e);const r=(0,d.stripErrorFlags)((0,c.errorToS)(e));y({response:t,toast:{text:404===i?"Not found":"Well, darn, that didn't work",uuid:r,details:r,type:(0,d.isFatalError)(e)?"error":"warning",button1Text:"Return home",button1Url:"/"+a.DismissAnchor,button1Class:"info",onClickUrl:a.DismissAnchor},httpStatusCode:i??m.HttpStatus.ServiceUnavailable})}t.requirePlus=async function(e,t,i){if(await(0,h.l)()){const e={toastPlusOnly:!0};return t.status(m.HttpStatus.Forbidden),t.json(e)}return i()},t.requireEnabled=function(e){return(t,i,r)=>e.valueOrDefault?r():y({response:i,toast:{text:"This has been disabled by your administrator.",details:`(see setting "${e.name}")`,type:"warning"},httpStatusCode:m.HttpStatus.Forbidden})},t.sendServerToast=y,t.sendRedirectionToast=function({response:e,toast:t,url:i,redirectOrReplace:r}){if((0,f.isAjaxRequest)(e.req.headers)){const s="replace"===r?n.XLocationReplace:n.XLocationRedirect;return e.setHeader(s,i),g().warn("sendRedirectionToast()",{requestedURI:(0,p.requestedUri)(e.req),toast:t,key:s,url:i}),e.json({toast:t})}return e.redirect(i)},t.sendWarningServerToast=function({response:e,toast:t,httpStatusCode:i,reload:r}){return t.type??(t.type="warning"),y({response:e,toast:t,httpStatusCode:i,reload:r})},t.send404Toast=function({text:e,details:t,response:i,httpStatusCode:r=404}){return y({response:i,toast:{text:e,details:t,type:"warning",button1Text:"Go home",button1Url:(0,o.mkHomeFullPath)()+a.DismissAnchor,button1Class:"info",onClickUrl:a.DismissAnchor,timeout:!1},httpStatusCode:r})},t.sendErrorToast=v,t.expressErrorHandlerWithToast=function(e,t,i,r){null==e?r():v(e,i)},t.wrapWithToast=async function({f:e,response:t}){try{await e()}catch(e){(0,s.map)((0,l.toErr)(e),(e=>v(e,t)))}}},30576:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.viewRouter=void 0;const s=r(i(7252)),n=i(51773);t.viewRouter=function({path:e,view:t,modeler:i}){return s.default.Router().get(e,(0,n.wrap)(t+"Router",(async(e,r)=>{const s=await(i?.(e,r))??{};return s.nonce=r.locals?.cspNonce,r.render(t,s)})))}},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(73024)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(76760)),n=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),s=i(76760);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),v=f(i(1708)),w=i(46466),b=f(i(57975)),S=f(i(38522)),P=i(19851),_=i(40958),T=i(5233),M=i(22573),E=i(42659),k=i(50357),D=i(96249),x=i(98553),C=i(55835),A=i(31586),F=i(68708),I=i(97790),O=i(39926),L=i(51926),R=i(59455),N=i(54993),B=i(48884),j=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),q=i(76850),H=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Y=i(43334),X=i(81168),Z=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),se=i(89968),ne=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),be=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const Se=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,M.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const s=(0,fe.resolve)(i),n=new Pe(s,t);return Se().set(i,n),Se().set(s,n),n}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,X.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,A.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,k.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,q.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,be.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,F.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,T.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,X.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,A.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),_e)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,A.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,n=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,X.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*E.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),s=i(88840),n=i(14036),a=i(29882);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,n.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),b=i(16287),S=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class T{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new T(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new T(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return T.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new T(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>T.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new T(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=T},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),v=i(54557),w=i(50213),b=i(88158),S=i(56519),P=i(46292),_=i(32551),T=i(35280),M=i(87290),E=i(96706),k=i(57902),D=i(43334),x=i(78984),C=i(33995),A=i(28874),F=i(21144),I=i(83278),O=i(48313),L=i(85772),R=i(78133),N=i(46356),B=i(17217),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:A.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?k.LogLevels.debug:k.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((D.isWin?"*":"")+"/"+t.s+"/",t.desc));if(D.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}D.isLinux&&e.push(new U(`${(0,_.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{A.Settings.excludeGlobsOmitDefaults.watchLater(J),A.Settings.excludeGlobsAdd.watchLater(J),A.Settings.excludeGlobsOmit.watchLater(J),A.Settings.globsCaseInsensitive.watchLater(J),A.Settings.libraryDir.watchLater(K),A.Settings.originalsDir.watchLater(K),A.Settings.scanPaths.watchLater(K),A.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ne,whyNoMedia:L.whyNoMedia,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ne}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!A.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of A.Settings.excludeGlobsOmit.values)i(e);for(const e of A.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const X=[{disableAllFilters:()=>!0}],Z=[{notBlank:()=>!1}];function Q(e){return A.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Z:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return A.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Z:(0,t.excludeBundles)().dir}async function ie(e){return A.Settings.disableAllFilters.valueOrDefault?void 0:x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ne(e){return!(0,T.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,M.libraryDirPosixFile)(),(0,M.libraryOriginalsDirPosixFile)(),...A.Settings.argvScanPaths.values,...A.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,F.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ne},88561:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},79267:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const c=i(19851),d=i(40958),h=i(42659),f=i(31586),m=i(71371),p=i(50213),g=i(7282),y=i(409),v=i(78406),w=i(25764),b=i(99331),S=i(91655),P=i(34102),_=i(89968),T=i(85772);class M{static for(e){return new M(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,a,d=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=a,this.minRetained=d,s.set(this,void 0),this.intervalMs=(0,c.lazy)((()=>(0,f.clamp)((0,g.isTest)()?0:5*h.minuteMs,h.dayMs,this.staleMs/2))),n.set(this,void 0),this.cleanup=(0,y.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>u(this,r,"m",o).call(this)}),l(this,s,(0,p.mkLogger)("fs.FileCleanup("+e+")"),"f")}scheduleInterval(){return(null==u(this,n,"f")||u(this,n,"f").ended)&&l(this,n,new v.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:w.EndableRanks.first}),"f"),u(this,n,"f")}cancelInterval(){u(this,n,"f")?.end(),l(this,n,void 0,"f")}}t.FileCleanup=M,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(e){if(!(0,f.gt0)(this.minRetained))return new Set;const t=new m.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},o=async function(){try{if((0,b.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await _.DirectoryEntry.for(e);if(null==t)return[];u(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,S.fmtFullDuration)(this.staleMs," ")});const i=await u(this,r,"m",a).call(this,t),n=Date.now()-this.staleMs,o=new Set,l=[],c=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,T.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,f.gte)(e.mtimeMs(),n)))if(e.isDirectory())try{await e.rmdir_(),c.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(u(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,P.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&u(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),l.push(e.nativePath),o.add(e.dir)}catch(t){u(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const h=[...l,...c];return(0,d.isNotEmpty)(h)&&t.clear(),u(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:l.length,pruned_dir_count:c.length}),h}catch(e){return void u(this,s,"f").error("cleanup() failed",{error:e})}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,n.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),s=i(17217),n=i(16287),a=i(68284);async function o(e){return(0,r.pick)(await(0,n.stat_)((0,s.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,s.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),s=i(19851),n=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,s.set(this,[]),n.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,n,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,s,"f").push(e)}close(){u(this,n,"f").close()}}t.FileWatcher=m,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,s,"f"))t(e,this.nativePath)}}},13829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(55835),s=i(13538),n=i(81168),a=i(37628),o=i(46292),l=i(73209),u=i(95696);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},73209:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const _=i(58587),T=P(i(44652)),M=i(87997),E=i(40958),k=i(17586),D=i(42659),x=i(50357),C=i(75240),A=i(55835),F=i(31586),I=i(30976),O=i(13538),L=i(54993),R=i(7282),N=i(68852),B=i(23560),j=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),q=i(55222),H=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,s,Math.max(Date.now(),b(this,s,"f",n)+1),"f",n),(0,E.compactBlanks)([q.TokenRadix.encode(b(this,s,"f",n)),B.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return b(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>b(this,r,"m",w).call(this)),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=s,s,(i=b(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(b(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await b(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+b(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),b(s,s,"f",o).push(this)}get acquired(){return b(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await b(this,r,"m",f).call(this,e)??b(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,k.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,x.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==b(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:D.secondMs);S(this,c,setInterval((()=>b(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=b(this,c,"f")&&(clearInterval(b(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(b(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),S(this,u,!1,"f"),(0,A.map)(b(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?b(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>b(this,r,"m",v).call(this)),(0,F.toGt0)(this.staleMs)??D.secondMs),"f"),b(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(b(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>b(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await b(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await b(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,_.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),b(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await b(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await b(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,E.filterInPlace)(b(s,s,"f",o),(e=>b(e,l,"f")!==b(this,l,"f")))},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),s=i(51926),n=i(54993),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(73024)),n=i(57075),a=i(46466),o=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44652)),n=r(i(73024)),a=i(46466),o=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(n.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),s=i(42659),n=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),s=i(54993),n=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,n.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,n.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,n.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,n.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(51926),n=i(54993);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(76760)),n=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},61704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(21144),s=i(17217);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=n(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),b=i(88561),S=i(65238),P=i(16287),_=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),T="NoMedia",M=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+T+"$","im"),E=Object.freeze(["."+T,T]),k=Object.freeze((0,u.flatten)(E.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function D(e){return null!=M.exec(e)}t.isNoMediaName=D;const x=(0,o.lazy)((()=>new b.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=v.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return D(i.base)||await(0,w.isCachedirTagFile)(i)?x().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await x().getOrSetAsync(i.nativePath,(()=>A(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function A(e){if(D(e.base))return x().set(e.parent().nativePath,e.nativePath),_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,S.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([F(e.nativePath,i),(0,S.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,w.isCachedirTagDirectory)(e)?_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function F(e,t){for(const i of g.isCaseSensitiveFs?k:E){if(!0===t?.aborted)return null;const r=a.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return _().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(D(r.basename))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,r.basename))});if(r.basename===w.CACHEDIR_TAG){const t=(0,a.join)(e,r.basename);if(await(0,w.isCachedirTagFile)(t))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=A,t._dirHasNoMediaChild=F},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),b=i(17217),S=i(16287),P=i(66430),_=i(5545);function T(e){return((0,b.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=T,t.containsHiddenPathname=function(e){return C(e).some(T)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!T(e)))},t.resolveSimpleFile=function(e){return(0,b.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return E((0,v.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return n.default.dirname((0,b.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=M.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function k(e){const t=n.default.parse((0,b.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,n.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,b.toNativePath_)(e.ancestor),i=(0,b.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function x(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(y.isLinux?r===s:(0,p.equalsIgnoreCase)(r,s))}function C(e){return(0,b.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function A(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function F({p:e,maxLength:t}){const i=(0,b.toNativePath_)(e);if(i.length<=t)return i;const r=C(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),O([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),O([...s,...n])}function I(e){return e.startsWith("\\\\")}function O(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),y.isWin?"":n.default.sep)}t.parseNativePath=E,t.parentBasename=k,t.grandParentBasename=function(e){return k(n.default.parse((0,b.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return x(b.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return x(b.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return x(b.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=A,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,b.toNativePath_)(e),r=(0,b.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,v.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=F,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(F({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;if(A(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await s.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,b.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,b.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),b=i(16287),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function T(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,...T()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...M(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),b=i(22573),S=i(42659),P=i(26905),_=i(75240),T=i(55835),M=i(31586),E=i(68708),k=i(13538),D=i(89937),x=i(12168),C=i(54993),A=i(48884),F=i(50213),I=i(45255),O=i(81168),L=i(56519),R=i(56038),N=i(31562),B=i(84777),j=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),q=i(43334),H=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Y=i(34238),X=i(87001),Z=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),se=i(73209),ne=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,A.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,F.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,Z.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),r=new fe(i,t);return(0,O.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,T.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Z.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,T.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,A.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,T.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,M.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,k.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,M.clamp)(I.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,T.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,M.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,T.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,T.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),v=i(83278),w=i(19748),b=i(92423),S=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):null}async function T(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function M(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function k(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function D(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function A(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function F(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function I(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:A,notFileTooBig:F}]}function O(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:_},{notVideoTooShort:T},{notVideoTooLong:M},{notRejectedRating:k},{notExcludedKeyword:D}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=_,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=A,t.notFileTooBig=F,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(76760)),n=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(s.default.join((0,p.execDir)(),"resources"),s.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=s.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),s=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),s=i(84542);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(51455)),n=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),b=i(88561),S=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function _(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const T=(0,a.lazy)((()=>new b.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||T.prior()?.delete(e)}async function E(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await T().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=k(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(s===f.Timeout&&(0,g.onTimeout)({soft:!1}),s!==f.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),T.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!T().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=T().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?E(e):k(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return T().get(e)},t.readdirUncached_=k},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const s=i(73024),n=r(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=n.default.resolve(t,...e);if((0,s.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??n.default.resolve(...e))},t.execDir=(0,l.defer)((()=>n.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(22454),s=i(28874),n=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},8797:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.showFileInFolder=void 0;const r=i(58587),s=i(31421),n=i(19851),a=i(40958),o=i(50213),l=i(43334),u=i(24399),c=i(28874),d=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ShowFileInFolder")));async function h(e,t){try{(0,s.spawn)(e,t,{detached:!0,stdio:"ignore"}).unref()}catch(i){d().warn("spawn() failed",{err:i,cmd:e,args:t})}}t.showFileInFolder=async function(e){if(await e.isEmpty())return!1;if(c.Settings.showFileInFolderUsesThunar.valueOrDefault&&l.isLinux)return async function(e){return h("dbus-send",["--type=method_call","--dest=org.xfce.Thunar","/org/xfce/FileManager org.xfce.FileManager.DisplayFolderAndSelect",`string:"${e.dir}"`,`string:"${e.base}"`,'string:""','string:""'])}(e);if((0,a.isNotEmpty)(c.Settings.showFileInFolderCommand.values)){const t=c.Settings.showFileInFolderUsesFileUri.valueOrDefault?e.fileuri():e.nativePath,i=[...c.Settings.showFileInFolderCommand.values,t],r=i.shift();return d().info("custom showFileInFolderCommand: running",{cmd:r,args:i}),h(r,i)}return l.isLinux?async function(e){return h("nautilus",["-s",e.fileuri()])}(e):l.isWin?async function(e){const t=e.nativePath.replace(/"/g,"").replace(/'/g,"''");try{return await u.PowerShell.instance().execute(`start explorer.exe -ArgumentList '/select,"${t}"'`,r.SimpleParser),!0}catch(t){return d().warn("explorerSelect("+e+") failed",t),!1}}(e):!!l.isMac&&async function(e){return h("open",["-R",e.nativePath])}(e)}},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),s=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const s=r(i(73024)),n=r(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function S(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(S(r),S(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}t.stat_=v,t.statMaybe=w,t.statToType=b,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),s=i(56409);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(57075)),n=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),v=i(19851),w=i(40958),b=i(22573),S=i(42659),P=i(98553),_=i(31586),T=i(68708),M=i(50989),E=i(51926),k=i(85556),D=i(54993),x=i(89788),C=i(23467),A=i(7282),F=i(23560),I=i(77377),O=i(71567),L=i(73568),R=i(25764),N=i(38836),B=i(99331),j=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),q=i(5012),H=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Y=i(84542),X=i(73428);t.AssetFileSyncStates=(0,M.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,M.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,M.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,M.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const Z={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,T.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,M.strEnum)(...(0,T.keys)(new class{constructor(e,t,i,r,s,n,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,v.lazy)((()=>(0,X.writeTextfile_)(re().nativePath,(0,E.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(Z)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=S.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,H.isCsvExt)(e)&&(0,_.gte)(e.mtimeMs(),t)))},t.syncReport=(0,v.lazy)((()=>new se));class se extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new x.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,s,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,b.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,q.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,D.toS)(e.path),state:e.state,details:(0,D.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:t,at:new Date(t).toISOString(),...i,...(0,T.pick)(e,"from","elapsedMs","url")};(0,T.isEmptyObj)(e.meta)||(s.meta=(0,P.stringify)(e.meta)),(0,A.isTest)()&&process.stdout.write((0,P.stringify)(e)+Y.Newline),f(this,r,"m",u).call(this,s)}}maybeSystemData(e){(0,F.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:n}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,B.ending)()||r instanceof L.AbortError?t.SyncFileStates.canceled:r instanceof k.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return f(this,n,"f")??f(this,r,"m",h).call(this)}async flushClose(){return f(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,n,"f");return m(this,n,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,s,"f")}}t.SyncReport=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,r,"m",c).call(this,i):(f(this,r,"m",c).call(this,{...i,details:(0,w.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Y.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,s,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,j.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,s,"f").nativePath),this.logger.info("Opening new report: "+f(this,s,"f")),(0,A.isTest)()&&(0,O.stdoutWrite)({syncReport:f(this,s,"f").nativePath},!1),m(this,n,(0,g.createWriteStream)(f(this,s,"f").nativePath),"f"),f(this,n,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Y.Newline),f(this,n,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(48161)),n=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44652)),n=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},79847:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkFileUri=t.trashOrUnlinkFileUris_=void 0;const o=n(i(51455)),l=a(i(49378)),u=i(40958),c=i(22573),d=i(13538),h=i(83104),f=i(45255),m=i(31562),p=i(98314),g=i(34102),y=i(28874),v=i(45200),w=i(63870),b=i(16287),S=i(74128),P=i(84258),_="fs.Trash";async function T(e){const t=Date.now(),i=(0,w.commandTimeoutMs)(),r=(0,c.toNotBlank)(e.nativePath)??await(0,d.thenOrTimeout)((0,v.uri2nativePath)(e.uri,e.mountpoint),i);if((0,c.blank)(r)||r===h.Timeout)return(0,S.syncReport)().onProgress({from:_,state:"failed",details:"Could not convert URI to native path",path:e.uri,elapsedMs:Date.now()-t}),{uri:e.uri,unlinked:!1};const s=await(0,b.statMaybe)(r);if(null==s)return(0,S.syncReport)().onProgress({from:_,state:"noop",details:"Failed to delete: no such file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(!s.isFile())return(0,S.syncReport)().onProgress({from:_,state:"noop",details:"Failed to delete: not a file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(y.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,d.thenOrTimeoutError)((0,l.default)(r,{glob:!1}),i),await function(e){return(0,m.untilTrue)((async()=>null==await(0,b.statMaybe)(e)),{timeoutMs:f.ShortCommandTimeoutMs})}(r))return(0,S.syncReport)().onProgress({from:_,state:"deleted",details:"Moved file to trash",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0};(0,P.logger)().warn("soft-delete("+r+") didn't seem to work: the file is still there?")}catch(e){(0,S.syncReport)().onProgress({from:_,state:"note",details:"Failed to soft-delete file to trash: "+(0,p.errorToS)(e),path:r,elapsedMs:Date.now()-t}),(0,P.logger)().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}try{return await(0,d.thenOrTimeoutError)(o.unlink(r),i),(0,g.ee)().emit("fileChanged",r),(0,P.logger)().info("unlink("+r+") successful"),(0,S.syncReport)().onProgress({from:_,state:"deleted",details:"Permanently deleted file",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0}}catch(i){return(0,S.syncReport)().onProgress({from:_,state:"failed",details:"Could not move file to trash or delete: "+(0,p.errorToS)(i),path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!1}}}t.trashOrUnlinkFileUris_=async function(e){const t=[];for(const{uri:i,mountpoint:r}of(0,u.uniqBy)(e,(e=>e.uri)))try{t.push(await T({uri:i,mountpoint:r}))}catch(e){t.push({uri:i,unlinked:!1,error:e})}return t},t.trashOrUnlinkFileUri=T},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),s=i(41400),n=i(55835),a=i(92782),o=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),h=i(87128),f=i(95696);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=n(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await a.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(76760)),n=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},60526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(47783),a=i(63335),o=i(18454);t.exiftoolHealthCheck=(0,s.defer)((()=>o.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifTool…",settings:[],later:async()=>{const e=await(0,n.exiftoolVersion_)();return{level:"ok",msg:["ExifTool is OK","ExifTool "+(0,a.ver)(e),(0,r.tt)((0,n.exiftool)().options.exiftoolPath)],meta:{exiftoolVersion:e}}}})))},19652:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const a=i(51455),o=n(i(22915)),l=i(40958),u=i(82950),c=i(22573),d=i(45599),h=i(12168),f=i(50213),m=i(79960),p=i(32551),g=i(98314),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,p.homeDir)(),o.getHomeFolder(),o.getPicturesFolder(),o.getVideosFolder(),o.getDesktopFolder(),await(0,m.defaultApplePhotosLibrary)()]).sort(),t=new Map,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,a.readdir)(e,{withFileTypes:!0})}catch(i){if(["ENOTDIR","ENOENT"].includes(i?.code))continue;t.set(e,i)}const r=0===t.size?{level:"ok",msg:["Default media directories are OK","The following directories are readable:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Error reading "+(0,h.plur)(t.size,"media directory")+":",(0,u.li)([...t.entries()].map((([e,t])=>(0,u.tt)(e)+":"+(0,g.errorToS)(t,{maxLen:80}))))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},79483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(45599),s=i(45969),n=i(19652),a=i(18454);t.externalDirsHealthCheck=(0,r.defer)((()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",pendingMsg:"Checking default photo directories…",settings:[],later:n.externalDirectoryCheck})))},63664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const r=i(22573),s=i(45599),n=i(41400),a=i(50268),o=i(98553),l=i(50213),u=i(23560),c=i(45255),d=i(5916),h=i(28874),f=i(34238),m=i(51140),p=i(4988),g=i(18454),y=(0,s.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({desc:"health.getRemoteHealthSummary",later:async()=>{try{if((0,u.isWebService)())return;const e=await(0,p.get_)(f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}),{timeoutMs:c.ShortCommandTimeoutMs}),t=(0,o.parseJSON_)(e.data);if(m.HttpStatusIs.ok(e.statusCode)&&(0,a.isHealthCheckSummary)(t))return"ready"===t.state&&(0,r.toNotBlank)(t.libraryDir)!==(0,r.toNotBlank)(h.Settings.libraryDir.valueOrDefault)&&(y().error("getHealthSummary(): libraryDir mismatch! Switching to that library directory...",{local:h.Settings.libraryDir.valueOrDefault,remote:t.libraryDir}),h.Settings.libraryDir.value=t.libraryDir),y().debug("getHealthSummary()",{response:e}),t;y().warn("getHealthSummary(): invalid response",{response:e})}catch(e){y().warn("Failed to get health check summary from web service",{error:e})}}}),t.getLocalHealthSummary=(0,d.lazyAsync)({desc:"health.getLocalHealthSummary",later:()=>g.HealthCheck.awaitSettled()}),(0,n.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},87408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(63870),s=i(18454),n=i(89035),a=i(82638);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...s.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:s.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},18454:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b,S,P,_=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},T=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const M=i(19851),E=i(40958),k=i(76790),D=i(22573),x=i(41400),C=i(50357),A=i(26905),F=i(50268),I=i(55835),O=i(68708),L=i(30976),R=i(51926),N=i(13538),B=i(42279),j=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),q=i(50213),H=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Y=i(77740),X=i(98314),Z=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),se=i(21525),ne=i(82638),ae=(0,M.lazy)((()=>(0,q.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{_(this,s,"f",l).push(e+": failed: "+(0,X.errorToS)(t)),this.onResultChange()})),_(this,s,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return _(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){_(this,s,"f",l).push((0,R.isString)(e)?e:(0,X.errorToS)(e)),this.onResultChange()}static lastErrors(){return _(this,s,"f",l).toA()}static addLoadingMsg(e){_(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,E.compact)((0,j.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:_(this,s,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[_(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=_(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>_(this,s,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return _(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,F.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=_(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=s.summary();if(e.pendingCount>0){const t=await Promise.all(s.testResultsCritical());e=s.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){s.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,A.shortStack)());else{this.onResultChange(),_(this,s,"f",l).clear(),_(this,s,"f",d).clear(),_(this,s,"f",h).clear(),_(this,s,"f",c).clear(),this.summary.clear(),T(this,s,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new s(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return _(this,s,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,n,o,l,u,c,d,h,f,m,S,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=n,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=S,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),w.set(this,(0,M.lazy)((async()=>{await _(this,p,"f").prior(),(0,C.eql)(_(this,g,"f"),_(this,r,"m",v).call(this))||(this.onReset?.(),await this.refresh(),_(this,w,"f").unset())}))),this.refresh=(0,M.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await _(this,p,"f").prior();const e=_(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,q.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[F.HealthCheckSections.ordinal(this.section),l??999,this.id],T(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>_(s,s,"f",a).enqueue({name:this.id,l:()=>_(this,r,"m",b).call(this,o)}),ttlMs:S}),"f"),this.isCritical&&_(this,p,"f").watchLater({onChange:s.onCriticalResult,onError:s.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>_(this,w,"f").call(this)))}isStale(){return _(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return _(this,p,"f").settledCount()}reset(){return _(this,p,"f").unset(),this.onReset?.(),T(this,g,{starting:!0},"f"),this}setTTL(e){_(this,p,"f").setTTL(e)}result(){return _(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return _(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return _(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??_(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,E.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,E.isNotEmpty)(i)&&(r.links=(0,E.uniqBy)(i)),(0,E.isNotEmpty)(t)&&(r.buttons=(0,E.uniqBy)(t)),r}t.HealthCheck=oe,s=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,w=new WeakMap,r=new WeakSet,o=function(){return(0,E.filterInPlace)(_(this,s,"f",n),(e=>!e.isPending)),_(this,s,"f",n)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,ne.summarizeHealthChecksSync)({errors:_(this,s,"f",l),skipPending:_(this,s,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&T(this,s,!0,"f",u),i.state!==_(this,s,"f",c).last?.state&&_(this,s,"f",c).push({state:i.state,ts:Date.now()}),i},v=function(){return(0,O.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},b=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,A.shortStack)()}),T(this,g,_(this,r,"m",v).call(this),"f");try{if((0,Y.getDevEnvFlag)("PS_SLOMO")&&await(0,x.delay)((0,L.randomInt)(.3*i,.7*i)),this.isSkipped())return _(this,r,"m",S).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const s=await(0,N.thenOrTimeoutError)(e(),i);return _(this,r,"m",S).call(this,{test:s,elapsedMs:Date.now()-t})}catch(e){return _(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},S=function({test:e,src:t="#toResult",elapsedMs:i}){var r,n;const a=s.normalizeMsg(e.msg),o=e.level??((0,z.toS)(a).toLowerCase().includes("error")?"error":(0,z.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,E.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(T(this,y,(n=_(this,y,"f"),r=n++,n),"f"),r),(0,$.ending)()?u:this.logger.tap({level:se.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const s=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,D.toNotBlank)((0,X.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,Z.isFatalError)(e)&&s.toLowerCase().includes("warn")?"warn":"error"),_(this,r,"m",S).call(this,{test:{msg:s,level:t},src:"#toErrorResult",elapsedMs:i})},n={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new U.CountingSet},f={value:[]},oe.all=(0,M.lazy)((()=>Object.freeze((0,k.sortBy)(_(s,s,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,H.debounce)((()=>{ae().info("onCriticalResult()",s.summary.refresh())}),250),oe.summary=(0,M.lazy)((()=>_(s,s,"m",m).call(s))),oe.resetDebounced=(0,H.debounce)((()=>s.reset()),50)},85021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},88625:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=t.testHealthCheck=void 0;const r=i(19851),s=i(82950),n=i(45599),a=i(50268),o=i(50213),l=i(7282),u=i(44198),c=i(34102),d=i(2858),h=i(60526),f=i(79483),m=i(18454),p=i(39214),g=i(86403),y=i(42482),v=i(35675),w=i(89035),b=i(31974),S=i(20752),P=i(85200),_=i(37301),T=i(65756),M=i(15024),E=i(3956),k=i(29332),D=i(61274),x=i(38372),C=i(49913),A=i(84728),F=i(7245),I=i(16264),O=(0,n.defer)((()=>(0,o.mkLogger)("health.HealthCheckSetup")));t.testHealthCheck=(0,n.defer)((()=>m.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,settings:[],pendingMsg:"Test check…",later:async()=>{const e=a.HealthCheckLevels.validOrElse((0,u.env)().PS_TEST_HEALTH_CHECK_LEVEL,a.HealthCheckLevels.ok);return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,s.b)("details")}:`,(0,s.li)("alpha",(0,s.tt)("bravo"),"charlie")]}}}))),t.healthCheckSetup=(0,r.lazy)((()=>{(0,h.exiftoolHealthCheck)(),(0,p.heifHealthCheck)(),(0,y.libraryDirectoriesCheck)(),(0,v.libraryFreeSpaceCheck)(),(0,E.settingsEnvHealthCheck)(),(0,D.settingsSystemHealthCheck)(),(0,k.settingsLibraryHealthCheck)(),(0,f.externalDirsHealthCheck)(),(0,w.memoryHealthCheck)(),(0,b.nodejsHealthCheck)(),(0,S.notInDMGHealthCheck)(),(0,P.osHealthCheck)(),(0,_.powershellHealthCheck)(),(0,x.sharpHealthCheck)(),(0,g.jpegtranHealthCheck)(),(0,M.securityHealthCheck)(),(0,T.sqliteHealthCheck)(),(0,C.systemLoadHealthCheck)(),(0,F.videoHealthCheck)(),(0,I.volumeHealthCheck)(),(0,A.versionHealthCheck)(),(0,l.isProd)()||(0,t.testHealthCheck)();let e=(0,d.libraryHasSettings)();d.libraryHasSettings.watchLater((t=>{null!=t&&e!==t&&(O().info("libraryHasSettings changed. Resetting health checks.",{newValue:t}),e=t,m.HealthCheck.resetDebounced())}));for(const e of["volumesChanged","mountpointsChanged","error"])(0,c.ee)().on(e,(()=>{O().debug("Clearing health check cache",{event:e}),m.HealthCheck.resetDebounced()}));(0,c.ee)().on("fatal",(e=>m.HealthCheck.addError(e)))}))},39214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(41400),a=i(55835),o=i(34102),l=i(277),u=i(45969),c=i(63335),d=i(18454);t.heifHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-heif",pendingMsg:"Checking HEIF/HEIC tooling…",settings:["heifConvertPath"],links:[{text:"Read how to set up HEIF support with PhotoStructure",url:"https://photostructure.com/getting-started/heif-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getHeifSupportDetails)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["HEIF images will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.heifHealthCheck.prior()?.reset()))}))},86403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testJpegtran_=t.jpegtranHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(55835),a=i(98314),o=i(89966),l=i(51210),u=i(76280),c=i(63335),d=i(18454);async function h(){const e=await(0,o.jpegtranNativePath_)(),t=await(0,l.jpegtranVersion_)();return{nativePath:e,version:t,satisfies:(0,u.semverSatisfies)(t,">=1.5")}}t.jpegtranHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,pendingMsg:"Checking "+(0,r.tt)("jpegtran")+"…",settings:[],later:async()=>{try{const e=await h();return{level:"ok",msg:["jpegtran is OK",(0,n.map)(e.version,c.ver),(0,n.map)(e.nativePath,r.tt)]}}catch(e){return{level:"error",msg:["Something's amiss with jpegtran",(0,a.errorToS)(e)]}}}}))),t.testJpegtran_=h},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},42482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(98553),o=i(31586),l=i(94174),u=i(87290),c=i(98314),d=i(29882),h=i(45969),f=i(43334),m=i(28874),p=i(2858),g=i(59107),y=i(18454),v=i(42495);async function w(){const e=await(0,u.setupLibraryDirs_)();return(0,p.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,r.li)(...e.map((e=>(0,r.tt)(e))))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}t.libraryDirectoriesCheck=(0,n.defer)((()=>y.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directories…",settings:["libraryDir","originalsDir","previewsDir","cacheDir"],ttlMs:s.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,h.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],okLinks:[{type:"button",text:"Run library maintenance jobs",url:"/admin/run-maintenance",method:"POST",icon:"handyman"}],later:async()=>(await(0,p.readSettings)(),(0,h.isDocker)()?async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,r.tt)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,r.tt)(m.Settings.libraryDir.toEnvLine(m.Settings.libraryDir.defaultValue))}`]};const t=await(0,g.mountpoints_)(),i=(0,d.bestMountpointForDir)(e,t);if(null==i||"/"===i)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,r.tt)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[v.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,r.tt)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`];return null!=t&&(0,o.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,r.tt)(t.uid)+", groupid "+(0,r.tt)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[v.DockerVolumeLink]}}return await w()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,l.userDesc)()}.`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[v.DockerVolumeLink]}}}():async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"no-library",msg:["No PhotoStructure library is open",(0,a.stringify)(m.Settings.libraryDir.getState())]};if(!(0,p.libraryHasSettings)())return{level:"no-library",msg:["No PhotoStructure library is open",m.Settings.libraryDir.hasValue()?(0,r.tt)(m.Settings.libraryDir.toEnvLine()):void 0]};try{return await e.isReadWriteExecutable_()?await w():{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(t){return{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,l.userDesc)()}`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}())})))},35675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(31586),l=i(68708),u=i(12168),c=i(87290),d=i(77740),h=i(28874),f=i(7014),m=i(18454);t.libraryFreeSpaceCheck=(0,a.defer)((()=>(0,l.tap)(m.HealthCheck.for({section:"Library",id:"library-free-space",settings:["libraryDir","minDiskFreeGb","originalsDir","previewsDir","cacheDir"],pendingMsg:"Checking free space on library volume(s)…",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,c.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(e)} is not a directory`};const t=[];for(const e of await(0,c.setupLibraryDirs_)()){const i=await(0,f.bestVolumeForPath)(e);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.tt)(e)}`};let r=t.find((e=>e.vol.mountpoint===i.mountpoint));null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*u.GB,n=[];for(const{vol:e,paths:a}of t){const t=(0,s.b)(`Volume ${(0,s.tt)(e.mountpoint)} has ${(0,u.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.li)((0,r.uniq)(a).sort().map(s.tt))}`;if(e.available{for(const t of["minDiskFreeGb","libraryDir","originalsDir","configDir"])h.Settings[t].watchLater((()=>e.reset()))}))))},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},31974:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(1708)),n=i(82950),a=i(45599),o=i(26033),l=i(63335),u=i(18454);t.nodejsHealthCheck=(0,a.defer)((()=>u.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.js…",settings:[],links:[{text:"Read about PhotoStructure NodeJS support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e="You're running Node.js "+(0,l.ver)(s.default.versions.node)+".\nPhotoStructure requires "+(0,n.tt)(o.RequiredNodeRange)+".";return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",e]}:{level:"warn",msg:["Node.js is not a supported version",e]}}})))},20752:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(45599),s=i(43899),n=i(43334),a=i(18454);t.notInDMGHealthCheck=(0,r.defer)((()=>n.isMac&&n.isElectron?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure installation directory…",settings:[],later:async()=>s.ProjectPath.isInDMG()?{level:"error",msg:"PhotoStructure cannot run directly from a DMG disk image. Please drag and drop the PhotoStructure icon onto your Applications folder to install.",checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure isn't running directly from a DMG disk image"}}):void 0))},85200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const r=i(45599),s=i(96175),n=i(18454);t.osHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating system…",settings:[],links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,s.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,s.osFullName)()]}:{level:"warn",msg:["Operating system is not supported",(0,s.osFullName)()+" was detected, but only "+e+"."]}}})))},37301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(98314),a=i(43334),o=i(24399),l=i(63335),u=i(18454);t.powershellHealthCheck=(0,s.defer)((()=>a.isWin?u.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShell…",settings:["powerShellArgs"],ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,o.checkPowerShell_)();return{level:"ok",msg:["PowerShell is OK",(0,l.ver)(e)],meta:{version:e}}}catch(e){return{level:"error",msg:"PowerShell failed: "+(0,n.errorToS)(e)}}}}):void 0))},65756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(27180),a=i(98314),o=i(63335),l=i(18454);t.sqliteHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLite…",settings:[],links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await n.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,r.li)(["embedded: "+(0,o.ver)(e.libraryVersion),(0,r.tt)(e.sqliteNativePath)+": "+(0,o.ver)(e.toolVersion)])]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,a.errorToS)(e)}}}})))},15024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(31586),o=i(94174),l=i(77740),u=i(44198),c=i(59958),d=i(43334),h=i(18454);t.securityHealthCheck=(0,n.defer)((()=>{const e=d.isWin?"an administrator":"root";return h.HealthCheck.for({section:"System",id:"proc-not-superuser",pendingMsg:"Checking user permission level…",settings:[],later:async()=>{if("0"===(0,u.env)().PUID)return{level:"disabled",msg:`Admin health check is disabled (${(0,s.tt)("PUID=0")}).`};const t=(0,r.compact)([(0,a.gte0)((0,o.userid)())?"Current user id: "+(0,s.b)((0,s.tt)((0,o.userid)())):void 0,(0,a.gte0)((0,o.groupid)())?"Current group id: "+(0,s.b)((0,s.tt)((0,o.groupid)())):void 0,"Current user name: "+(0,s.b)((0,s.tt)(await(0,o.username)()??"(unknown)"))]);return!0===await(0,o.isRootUser)()||(0,l.getDevEnvFlag)(c.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK)?{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]}:{msg:["PhotoStructure is not running as "+e,...t],level:"ok"}}})}))},3956:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(12168),a=i(28874),o=i(63225),l=i(18454);t.settingsEnvHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settings…",settings:[],links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,a.allSettings)())if(t.hasValue()&&null!=t._envValue()){const i=!0===t.opts.sensitive?"********":t.toEnvValue(t._envValue());null!=i&&e.push((0,r.tt)(t.key+"="+i))}const t=[(0,n.plur)(e.length,"environment setting"),(0,r.li)(e)],i=(0,o.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,r.li)(i.map((e=>(0,r.tt)(e.envKey)+": "+e.msg))),"---",...t]}:{level:"ok",msg:t}}})))},29332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(45599),s=i(2858),n=i(18454),a=i(61274);t.settingsLibraryHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settings…",settings:["libraryDir"],links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")})))},61274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=t.validateSettingsToml=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(12168),o=i(81168),l=i(98314),u=i(95696),c=i(2858),d=i(32707),h=i(18454);async function f(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.tt)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.tt)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,a.plur)(i.settings.length,t+" setting override"),(0,s.b)("Source:"),(0,s.tt)(e),(0,s.b)("Settings:"),(0,s.li)(i.settings.map((e=>(0,s.tt)(e.key+"="+e.toEnvValue(e.value)))))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,l.errorToS)(t)}}}t.validateSettingsToml=f,t.settingsSystemHealthCheck=(0,n.defer)((()=>h.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settings…",settings:[],links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>f(u.PosixFile.forMaybe((0,d.systemSettingsFile)()),"system")})))},38372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpHealthCheck=void 0;const r=i(45599),s=i(98314),n=i(21473),a=i(18454);t.sharpHealthCheck=(0,r.defer)((()=>a.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharp…",settings:[],later:async()=>{try{return await(0,n.testSharp_)(),{level:"ok",msg:["Sharp is OK","Image processing is working as expected."]}}catch(e){return{level:"error",msg:["Something's amiss with Sharp",(0,s.errorToS)(e)]}}}})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},49913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(31586),o=i(28874),l=i(14854),u=i(18454);t.systemLoadHealthCheck=(0,n.defer)((()=>u.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system load…",settings:["cpuBusyPercent"],ttlMs:s.minuteMs,later:async()=>{if(o.Settings.cpuBusyPercent.valueOrDefault<=0)return{level:"ok",msg:["CPU utilization is not monitored",(0,r.tt)(o.Settings.cpuBusyPercent.key)+" is set to <= 0"]};const e=l.CpuUsage.instance().busyPct(),i=(0,l.isTooBusy)();return(0,t.systemLoadHealthCheck)().setTTL((i?6:60)*s.secondMs),{level:i?"stop-sync":"ok",msg:"CPU utilization is "+(0,a.fmtPct)(e)+"\n"+(i?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause if CPU utilization exceeds")+" "+(0,r.tt)(o.Settings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(o.Settings.cpuBusyPercent.valueOrDefault)}}})))},84728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(40044),a=i(18454);t.versionHealthCheck=(0,s.defer)((()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure version…",settings:["autoUpdateCheck","configDir","libraryDir","optOut"],ttlMs:r.hourMs,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:n.checkVersion_})))},7245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(41400),a=i(55835),o=i(34102),l=i(66106),u=i(45969),c=i(63335),d=i(18454);t.videoHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-video",pendingMsg:"Checking video tooling…",settings:["ffmpegPath"],links:[{text:"Read how to set up video support with PhotoStructure",url:"https://photostructure.com/getting-started/video-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getVideoToolDetails_)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["Videos will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["Videos will not be imported","No video tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.videoHealthCheck.prior()?.reset()))}))},16264:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(13538),l=i(83104),u=i(12168),c=i(48884),d=i(45255),h=i(43334),f=i(69108),m=i(48165),p=i(63870),g=i(7014),y=i(18454);t.volumeHealthCheck=(0,a.defer)((()=>y.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,pendingMsg:"Checking volumes…",settings:[],links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:h.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=Date.now(),i=await(0,o.thenOrTimeout)((0,g.volumes)(),(0,p.commandTimeoutMs)());if(i===l.Timeout){const i=await(0,o.thenOrTimeout)(h.isWin?(0,m.getLocalVolumesWin_)():(0,f.dfPosixRawLocal_)(),d.ShortCommandTimeoutMs);return(0,t.volumeHealthCheck)().logger.warn("volumes() timed out, retrying in 5m"),setTimeout((()=>(0,t.volumeHealthCheck)().refresh()),5*n.minuteMs),{level:"warn",msg:[i===l.Timeout?"Something seems wrong with your computer's volumes":"Something seems wrong with one or more remote filesystem mounts","Gathering volume metadata took longer than "+(0,n.fmtAgo)(e,"")+"."]}}const a=i.filter((e=>!1===e.ok));if((0,r.isNotEmpty)(a))return{level:"warn",msg:["One or more volumes are not healthy","Check the following:",(0,s.li)(a.map((e=>(0,s.tt)(e.mountpoint))))]};const[y,v]=(0,c.partition)(i,(e=>!0===e.remote)),w=["Storage volumes are OK"];return(0,r.isNotEmpty)(v)&&w.push((0,s.b)((0,u.plur)(v.length,"local volume")+":"),(0,s.li)(...v.map((e=>(0,s.tt)(e.mountpoint))))),(0,r.isNotEmpty)(y)&&w.push((0,s.b)((0,u.plur)(y.length,"remote volume")+":"),(0,s.li)(...y.map((e=>(0,s.tt)(e.mountpoint))))),{level:"ok",msg:w}}})))},95242:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),v=i(57159),w=i(83278),b=i(95696),S=i(62105),P=i(84258),_=i(38156),T=i(69589),M=i(28874),E=i(47783),k=i(29990),D=i(16047),x=i(42725),C=i(4192),A=i(32876),F=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class O{constructor(e,t,i){r.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,T.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(r=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,S.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await n(this,r,"m",s).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:n,height:a,sha:l,mimetype:u}=t;if(null==s||null==n||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:n,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(x.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(r,s)){const n=(0,k.fitSizes)(e,e.mimetype),a=(0,o.diff)(r,s);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=n.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:n});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=O,s=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},x.ImageSize.sq().length+x.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,F.sharpReadable_)({src:e,minDim:x.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,F.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,D.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,k.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=x.ImageSize.largestSq(),b=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,h.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of l){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&r.reducer===A.Fit&&M.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of x.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=M.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(r)+" -> "+(0,u.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,C.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),v=i(70417),w=i(35721);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},33106:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(9288)),n=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(40958),s=i(33374),n=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),s=i(54993),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),s=i(19851),n=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(9288)),n=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),v=i(88561),w=i(95696),b=i(17217),S=i(50213),P=i(23624),_=i(28874),T=i(12089),M=i(16170),E=i(1078),k=i(33106),D=i(86580),x=i(78011),C=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const A=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void A().warn("imageHash() failed for "+e,t)}};const F=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,D.fitToResolution)(i.dimensions,Math.round(_.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,D.fitToResolution)(i.dimensions,_.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,M.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?k.dctHash:k.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,M.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,T.shim1)({name:"img.imageHash",cache:F,impl:I}),t._imageHash_=I,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},80361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(33374),l=i(57924),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(21605),m=i(48884),p=i(50213),g=i(97352),y=i(85810),v=i(3048),w=i(32848),b=i(82647),S=i(38812),P=i(70417),_=i(23624),T=i(28874),M=i(86580),E=i(48368),k=i(2090),D=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function A(e,t,i=E.HashDim){const r=(0,_.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function F({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=A(e,i,r),l=A(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));D().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function I(e,t,i="debug",r={}){return D().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=F({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,M.validRotations)(r,s)}),m=F({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=F({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void D().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,v=(0,M.aspectRatio)(r),S=(0,M.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let _=0,x=0;n&&(x+=T.Settings.imageHashFuzzyDateDelta.valueOrDefault,_+=T.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=T.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,_+=T.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(_+=T.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=T.Settings.imageHashGreyscaleDelta.valueOrDefault);const A=R((_+(i.minImageCorr??T.Settings.minImageCoeffPct.valueOrDefault))/100),I=R((x+(i.minColorCorr??T.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,k.fmtAspectRatio)(v)} vs ${(0,k.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,A)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,A)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=I,z=j&&N.avg>=A;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:A,imageCoeffDelta:_,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:I,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return D().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=A(e,t,i);return f.Rotations.map((e=>(0,_.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=F,t.isSimilarImage=I,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return I(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},42725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},4192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},66778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.matchAndWriteRotation_=t.matchRotation=void 0;const r=i(19851),s=i(68708),n=i(21605),a=i(50213),o=i(56038),l=i(47783),u=i(67083),c=i(95141),d=i(48368),h=i(80361),f=(0,r.lazy)((()=>(0,a.mkLogger)("img.MatchRotation")));async function m(e,t){return(0,o.time)("img.matchRotation",(async()=>{const i=await(0,d.imageHash)(e),r=await(0,d.imageHash)(t),s=(0,h.compareImageHashes)(i,r);if(null!=i&&null!=r&&null!=s)return f().tap({level:"info",msg:"matchRotation()",result:{rotation:s.bRotation,exemplarImageHash:i,destImageHash:r,imageHashComparison:s},meta:{src:e,dest:t}});f().warn("failed to compute image hashes",{a:e,b:t})}))}t.matchRotation=m,t.matchAndWriteRotation_=async function(e,t,i=0){const r=await m(e,t);if(null==r)return;const a=(0,n.normalizeRotation)(r.destImageHash.rotation+r.rotation+i);if(f().info("matchRotation() computed newRotation",{currentRotation:r.destImageHash.rotation,additionalRotation:i,rotationToMatch:r.rotation,newRotation:a}),null==a)return void f().warn("Can't compute final orientation",{newRotation:a,file:t.nativePath,r});const o=(0,c.rotationToWriteTag)(a);if((0,s.isEmptyObj)(o))return void f().warn("rotationToWriteTag() returned null",{newRotation:a,mimetype:r.destImageHash.mimetype,file:t.nativePath});const d=await(0,u.ensureHistoryRecords)(await t.sidecar(),(0,u.mkHistoryRecords)(u.Actions.set,o));return await(0,l.writeTags_)(t,o),f().tap({level:"info",msg:"matchAndWriteRotation_()",result:{...r,writtenTags:o,rotation:a,historyRecords:d},meta:{exemplar:e,dest:t}})}},78011:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(9288)),n=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},52121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const r=i(19851),s=i(78923),n=i(95696),a=i(50213),o=i(28874),l=i(12089),u=i(16170),c=i(13940),d=i(4192),h=i(5733),f=i(50961),m=(0,r.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=n.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,s.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},48604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),s=i(31586),n=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(9288)),n=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,n.lazy)((()=>{s.default.simd(l.Settings.enableSIMD.valueOrDefault),s.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),s.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(77988),n=r(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),v=i(56519),w=i(56038),b=i(57159),S=i(95696),P=i(17217),_=i(28874),T=i(47783),M=i(16170),E=i(95141),k=i(54979),D=i(1078),x=i(63870),C=i(86580),A=i(277),F=i(16047),I=i(13940),O=i(5733),L=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,T.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await z(e,t))?.nativePath}async function j(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes<_.Settings.maxEmbeddedBuffer.valueOrDefault;try{const t=await B(e,i,l);if(null==t)return;const s=(0,n.default)(t,{failOn:_.Settings.imageFailOn.valueOrDefault}),o=await s.metadata(),u=(0,C.aspectRatio)(o);if(null!=a&&null!=u&&!(0,h.closeTo)(a,u,.2))return void N().info("imgFromExif("+e+", "+i+"): rejecting (aspect ratio mismatch)",{fileAspectRatio:a,renderedAspectRatio:u});const c=(0,C.lteBoth)(r,o);return N().debug("imgFromExif("+e+", "+i+")",{valid:c,minDim:r,useBuffer:l,fileAspectRatio:a,renderedAspectRatio:u,dim:(0,f.pick)(o,"width","height")}),c?{sharp:s,file:(0,m.isString)(t)?S.PosixFile.for(t):void 0}:void 0}catch(t){return void N().info("Failed to read image from EXIF tag "+i,{src:e,error:t})}}async function z(e,t){const i=t.toLowerCase().endsWith("tiff")?".tiff":".jpg";try{const r=await(0,I.tmpImageFile_)({src:e,tag:t,ext:i});return await r.applyIfEmpty_({retries:2,fn_:i=>(0,T.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=j,t.toSharp=function(e){const t=e;if((0,O.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:_.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=N().addParameterContext(e.nativePath);(0,O.setupSharp)();const n=await(0,k.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,D.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,M.isVideoMimeType)(n),S=(0,M.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const I=(0,C.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),z=(0,M.isSharpMimeType)(n)&&null==t,V=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||z||V)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:z,isMirrorOrientation:V});else{const i=!1,n=await(0,T.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[..._.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(..._.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>j(e,n,t,x,I)))}}}(0,M.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,F.isHeifMimeType)(n)&&await(0,A.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,A.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,L.isVideoSupported)())try{return await(0,v.thenMap)((0,L.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,w.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=z},21473:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=void 0;const s=r(i(34589)),n=i(76760),a=r(i(9288)),o=i(50357),l=i(98553),u=i(68708),c=i(23560),d=i(43899),h=i(28874),f=i(5733);t.testSharp_=async function e(t){try{(0,f.setupSharp)();const e=t??(0,n.join)(d.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(e,{failOn:"error"}),r=await i.resize(24,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,o.eql)((0,u.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:24,height:32,channels:3}),"Unexpected sharp output: "+(0,l.stringify)(r.info))}catch(i){if(!(0,c.isWorkerService)()&&h.Settings.enableSIMD.valueOrDefault)return h.Settings.enableSIMD.envValue=!1,e(t);throw i}}},181:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(9288)),n=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),v=i(54979),w=i(63870),b=i(5733),S=i(50961),P=i(66106),_=i(51210),T=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void T().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=T().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&T().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const M=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return M().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:M,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(T().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,_.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))T().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),v=i(56038),w=i(31562),b=i(98314),S=i(34102),P=i(88561),_=i(95696),T=i(17217),M=i(74128),E=i(31843),k=i(70417),D=i(33847),x=i(28874),C=i(94678),A=i(43207),F=i(47783),I=i(16170),O=i(95141),L=i(1078),R=i(63870),N=i(89782),B=i(13940),j=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,j.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,E.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function q(e){return await(0,t.isVideoSupported)()?_.PosixFile.for(await(0,t._extractVideoFrame_)((0,T.toNativePath_)(e))):void 0}async function H(e,t){const i=V("extractVideoFrame",e),r=_.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,j.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,B.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,F.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,N.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,A.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,j.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,F.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,j.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,F.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,A.extractDurationSec)(i);if(!(0,c.gt)(n,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=q,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await G())return;const n=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,F.readTags)(e),h=(0,L.extractSizeInfoFromTags)(d),m=(0,A.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,F.readRawTags)(t),r=await(0,F.readRawTags)(e),s=(0,A.extractDurationSec)(r),n=(0,A.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),s=x.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,C.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,v.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:r.halt,...g},m=x.Settings.transcodeMaxDim.valueOrDefault,p=(0,k.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,j.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,M.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-n})}catch(t){throw(0,M.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:Date.now()-n}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await q(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,j.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),v=i(84258),w=i(28874),b=i(76280),S=i(63870),P=i(19769),_=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function T(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:w.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=T;const M=/ffmpeg version n?(?\S+)/i,E=(0,u.lazy)((async()=>{const e=await T();if(null==e)return void _().info("failed to find ffmpeg in $PATH",{ffmpegPath:w.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=M.exec(t.result)?.[1];return _().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){E.unset(),t.ffmpegVersionDescription.unset()}function D(e){const t=e?.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function x(e){const t=[...w.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(w.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function A(e){const t=w.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(E(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",k),(0,g.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await E.prior()??E.refresh()},t.isFFmpegSupported=async function(){return null!=await E()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await T(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=x,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await T(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...x(t),...A(t),...D(t),"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){_().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,v.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return _().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return _().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await T(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(19851),s=i(42659),n=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),v=i(89782),w=i(13940),b=i(42725),S=i(19769),P=(0,r.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,w.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>k(e,t)})};const _=["-T"],T=["-Z","-"],M=["-o","1"],E=["-t","0","-j"];async function k(e,t){const i=await(0,v.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=b.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[..._,...T,...M,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],w={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:w});const k=(0,c.execFile)(g,y,void 0,w),D=[];function x(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});D.push(r)}}if(k.on("error",x),k.stderr.on("data",x),await t.writeStream_(k.stdout),(0,s.isNotEmpty)(D))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:D,path:e.nativePath});(0,c.endProcess)(k)}t.dcraw_emu_=k},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},45657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.r=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(45599),l=i(98553),u=i(55835),c=i(34666),d=i(50213),h=i(37628),f=i(37805),m=i(46292),p=i(95696),g=i(93756),y=i(28874),v=i(63870),w=i(71706),b=i(81674),S=i(33603),P=i(70114),_=(0,o.defer)((()=>(0,d.mkLogger)(T().l))),T=(0,r.rolazy)((()=>(0,w.j)("G8oAKIzTFfOihHWPgG6m/h0h65IqCWu72UHSOixdfW12GgbIbSdJW2sLEmvLsqcHfOPXk00SqojDRomicXUE+MuLfPaoTzFWZPq8AdmWyQVUWERkBLoYBhqafaAvY27+LDra0blcQ4Vnjn/ukQh/C4o0cd0B")));async function M(e){const t=await(0,S.sids)({timeoutMs:(0,v.commandTimeoutMs)()});if((0,s.isEmpty)(t))return _().warn("no-op: empty sids");const i=(0,l.stringify)({uids:[...t,e],coupon:y.Settings.coupon.valueOrDefault,version:f.version}),r={...T().r,body:i},n=await(0,g.request)(T().u,r);_().info(T().u,{req:r,response:n}),n.ok?await(0,P.writeLicense)(JSON.parse(n.body)?.[T().a],(0,v.commandTimeoutMs)()):_().warn(T().u,{req:r,response:n})}t.r=(0,r.rolazy)((async()=>{const e=T().s+": ";try{if(!y.Settings[T().s].valueOrDefault)return _().debug(e+"no-op (settings disabled)");const t=(await(0,b.m)()).filter((e=>null!=e.l&&(0,n.notBlank)(e.s))),i=new Date,r=t.find((e=>e.ok&&(0,c.gt)(i,e.l?.exp)));if(null!=r)return _().debug(e+"no-op: ",{current:r});const s=await(0,u.map)((0,m.configDir)(),(e=>p.PosixFile.for(e).join(T().s+"-v"+f.version).mkdirp_()));for(const r of t){if((0,n.blank)(r.s)||null==r.l||ie.startsWith("cu:")));if(null!=t){if(await(s?.join((0,h.shortFsStringSha)(r.s,14)+".txt").applyIfEmpty_({fn_:async i=>{await M(t),await i.writeJson_({l:r.l,at:Date.now()}),_().warn(e+"requested",r)},timeoutMs:(0,v.commandTimeoutMs)()})),await(0,b.p)())break}else _().debug(e+"skipping (no cu)",r)}}catch(t){_().warn(e+"failed",t)}}),15*a.minuteMs)},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},42042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(22573),s=i(28874),n=i(81674);t.getEmail=async function(){const e=s.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),v=i(50213),w=i(56519),b=i(76596),S=i(46292),P=i(87290),_=i(77740),T=i(34102),M=i(83278),E=i(28874),k=i(37692),D=i(71706),x=i(83950),C=i(72042),A=i(33603),F=i(48132);t.k=(0,y.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,C.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,_.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function L(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:x.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,A.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await L((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function B(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=L,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await L(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof x.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,_.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,A.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),(e=>M.BaseFile.for(e))),s=(n=(0,l.flatten)((await(0,w.someOrTimeout)([()=>function(e){return L(E.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,f.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l))),(e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,o.later)((()=>{(0,T.ee)().on("clearCache",(()=>t.m.unset())),(0,T.ee)().on((0,t.k)().c,(()=>t.m.unset())),k.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=B,t.l=async function(){try{return await B()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await B()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},84194:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(40958),a=i(76790),o=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),h=i(19851),f=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(45599),o=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),h=i(50213),f=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),v=i(45879),w=i(70854),b=i(57902),S=i(72308),P=i(43334),_=i(24399),T=i(7014),M=i(30933),E=i(71706),k=i(84194);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const D=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,k.toUID)(k.S.lc,e.join(",")))))),A=/o\.e\.m\./i;async function F(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(A)))}async function I(){return P.isLinux?(await F("lm")).map((e=>(0,k.toUID)(k.S.lm,e))):void 0}async function O(){return P.isLinux?(await F("lp")).map((e=>(0,k.toUID)(k.S.lp,e))):void 0}async function L(){return P.isLinux?(await F("lb")).map((e=>(0,k.toUID)(k.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,k.toUID)(e,t)))}catch(e){return void D().warn((0,t.k)().i+" failed",e)}}async function N(){return(await _.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,k.toUID)(k.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,k.toUID)(k.S.cm,(0,M.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,k.toUID)(k.S.bm,(0,r.compactBlanks)(await F("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,k.toUID)(k.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,k.toUID)(k.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,k.toUID)(k.S.nm,e)))}async function q(){return(0,c.toA)(await(0,T.volumes)()).map((e=>(0,k.toUID)(k.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,I,O,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return D().tap({msg:"sids()",result:(0,k.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,f.isTest)())for(const t of e)H.add(t)},t.clearSids=function(){(0,f.isTest)()&&H.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},70114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveIfBetter=t.licensesInDirectory=t.writeLicense=void 0;const r=i(45599),s=i(55835),n=i(50213),a=i(23560),o=i(37628),l=i(56519),u=i(46292),c=i(87290),d=i(34102),h=i(83278),f=i(37692),m=i(83950),p=i(81674),g=(0,r.defer)((()=>(0,n.mkLogger)("writeLicense")));async function y(e,t){return(await(0,l.mapAsyncSerial)({name:"read",arr:e.childFiles(),f:async e=>(0,p.vok)(await e.readTextFile(),e.nativePath,t)})).filter((e=>e.ok&&e instanceof m.L))}async function v(e,t,i){if(null!=t)if((await y(t,i)).some((t=>t.cmp(e)>=0)))g().info("saveIfBetter(): no-op for "+t);else{const i=t.join((0,o.shortFsStringSha)(e.s)+".txt");try{return await i.writeFile_(e.s),(0,d.ee)().emit("reloadLicenses"),(0,a.isWebService)()&&(0,f.addStateEvent)("reloadLicenses"),g().info("saveIfBetter(): wrote to "+i),i}catch(e){return void g().error("saveIfBetter(): failed to save license to "+t,e)}}}t.writeLicense=async function(e,t){const i=await(0,p.vok)(e,"candidate",t);if(null==i)return g().error("!ok",e);await v(i,(0,c.libraryDataDirPosixFile)()?.join((0,p.k)().d),t),await v(i,(0,s.map)((0,u.configDir)(),(e=>h.BaseFile.for(e).join((0,p.k)().d))),t),await p.m.refresh()},t.licensesInDirectory=y,t.saveIfBetter=v},34474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(40958),s=i(42659),n=i(41400),a=i(96249),o=i(68708),l=i(34666),u=i(20214),c=i(71371),d=i(50213),h=i(42638),f=i(31562),m=i(98314),p=i(89968),g=i(28874),y=i(4904),v=i(57902),w=i(89241),b=i(83954);function S(e=10*s.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-s.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new w.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*s.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-s.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),s=i(23560),n=i(66184),a=i(72210);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),s=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),s=i(42659),n=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},12495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(19851),s=i(42659),n=i(23560),a=i(79267),o=i(32144),l=i(28874);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isLogExt)(e.ext)})))},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),s=i(31586),n=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),s=i(57902);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,s.set(this,[]),n.set(this,(0,l.lazy)((()=>{o(this,s,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,s,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,n,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,r,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,r,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){if(null==e||0===o(this,s,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,s,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),s=i(50989),n=i(28874);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=n.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},89241:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),h=i(38522),f=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),v=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),s.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,s,!0,"f")})),this.stream.on("end",(()=>{u(this,s,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,s,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,s,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,s,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),s=i(76760),n=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),b=i(38836),S=i(99331),P=i(42638),_=i(76596),T=i(98314),M=i(89968),E=i(29882),k=i(28874),D=i(28981),x=i(20839),C=i(21727),A=i(66184),F=i(57902),I=i(72210),O=i(98192);function L(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,k.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await M.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,A.ifLog)(F.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,A.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,T.errorToS)(t))))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,_.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,A.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,T.errorToS)(e))))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await M.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,A.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,T.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),s=i(82328),n=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),b=i(23560),S=i(81168),P=i(78406),_=i(25764),T=i(20197),M=i(14977),E=i(36868),k=i(28874),D=i(32105),x=i(20839),C=i(21727),A=i(66184),F=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:_.EndableRanks.logger,unref:!0,onEnd:()=>c(this,s,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:A.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,F.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,T.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),k.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,M.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),s=i(84542),n=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),s=i(76790),n=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),s=i(41400),n=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),b=i(24068),S=i(43705),P=i(51879);function _(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),T();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new S.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,n.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&b.LogTail.instance()}function T(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=_,t.setupLogFormatter=T,(0,s.later)((()=>{h.Settings.logStdout.watchLater(_),h.Settings.logDir.watchLater(_),h.Settings.tailLogs.watchLater(_),h.Settings.logColor.watchLater(T),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},83954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(89179);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},82647:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p69(){return n(this,r,"m",s).call(this,.5)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,s=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},76752:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtEstimate=t.ETA=void 0;const r=i(42659),s=i(75240),n=i(31586),a=i(97352),o=i(82647);function l(e){return(0,n.gt0)(e)?e<=r.minuteMs?"less than a minute remains":"about "+(0,s.fmtDuration)(e,1,{plural:"remains",singular:"remain"}):void 0}t.ETA=class{constructor(){this.taskMillis=new o.Average(10)}push(e){(0,a.mapGt0)(e,(e=>this.taskMillis.push(e)))}clear(){this.taskMillis.clear()}avg(){return this.taskMillis.p69}etaMs(e){const t=this.avg();if(null==t)return;const i=t*e;return i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(76790),s=i(93973);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},36372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(76790),s=i(42659),n=i(31586),a=i(97238),o=i(50597),l=i(9103),u=i(55222);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},38812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(21605);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}×${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),s=i(65713);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),s=v(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(38522),s=i(22573),n=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},39471:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableServer=void 0;const r=i(27395),s=i(25764),n=i(36868);t.EndableServer=class{constructor(e,t){this.name=e,this.server=t,this._ended=!1,(0,r.addEndable)(s.EndableRanks.service,this)}get ended(){return this._ended}end(){return this._ended=!0,(0,n.closeStream)(this.server)}}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(48161)),n=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},93756:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.request=void 0;const s=r(i(44708)),n=i(22573),a=i(55835),o=i(97352),l=i(57159),u=i(63870),c=i(43205);t.request=async function(e,t={}){return null==t.headers&&(t.headers={}),(0,n.blank)(t.headers["user-agent"])&&(t.headers["user-agent"]=await(0,c.userAgent)()),new Promise(((i,r)=>{const n=s.default.request(e.toString(),t);n.setTimeout((0,a.orElse)(t.timeout,(0,u.commandTimeoutMs)()),(()=>{r(new l.WrappedError("Timeout fetching <"+e+">",{doNotSend:!0,retriable:!0}))})),n.on("response",(e=>{const t=[];e.setEncoding("utf8"),e.on("data",(e=>t.push(e))),e.on("end",(()=>{i({ok:(0,o.within)(200,399,e.statusCode),headers:e.headers,body:t.join(""),statusCode:e.statusCode,statusMessage:e.statusMessage})}))})).on("error",(e=>{r(e)})),(0,a.map)(t.body,(e=>n.write(e))),n.end()}))}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),b=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==b.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=S.exec(e)}function _(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=_,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=_(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void T().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const T=(0,s.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=_(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return T().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(T().warn("No name found for "+e),e):i}catch(t){return T().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),s=i(19851),n=i(54993);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(22573),s=i(51926),n=i(83556);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),s=i(59455),n=i(31562);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),b=i(54993),S=i(54557),P=i(19851),_=i(50213),T=i(88158),M=i(409),E=i(78406),k=i(25764),D=i(99331),x=i(56519),C=i(46292),A=i(8769),F=i(83278),I=i(32144),O=i(29882),L=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),j=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,O.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??L.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,f.isEmpty)(s))return B().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,N.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){B().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!z(r,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:r}),a.push(W(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,A.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,s,"f").delete(l),o(this,s,"f").getOrSet(l,(async()=>{const i=o(this,r,"m",n).call(this,e.pid),s=(0,v.opt)((0,T.Try)((()=>(0,O.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:s,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,s,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,r,"m",n).call(this,e);return(0,x.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new E.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:k.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=U,s=new WeakMap,a=new WeakMap,r=new WeakSet,n=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new U(F.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const s=i(31421),n=i(48161),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),b=i(56519),S=i(84777),P=i(8103),_=i(45879),T=i(43334),M=i(24399),E=i(45643),k=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){if(T.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,_.readFileMaybe)("/proc/"+i+"/stat")));return k().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,E.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,T.isWin?I:N)).filter((e=>D(e)&&t.includes(e.pid)));return k().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=D,t.pidInfo=async function(e){return(0,b.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,b.thenMap)((0,E.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const C="Get-Process",A="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return R(e);const t=[C,"-Id",F(e),"-ErrorAction SilentlyContinue",A].join(" ");return(0,b.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===a.default.pid))||r.push({pid:a.default.pid,start:new Date(v.StartTs),cmd:"node "+a.default.title}),r}async function N(e){return t=(await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(T.isLinux)return(0,c.toGt0)((0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){k().warn("clk_tck failed",{error:e})}return 100})),j=(0,g.lazy)((()=>Date.now()-(0,n.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,s=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(s)?{pid:i,cmd:r,start:new Date(j()+s/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),s=i(42659),n=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),b=i(31562),S=i(84777),P=i(34102),_=i(43334),T=i(28874),M=i(63870),E="{ready}",k=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",T.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(T.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:T.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),T.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(T.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,k),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,k),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),s=i(91655),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874),l=(0,n.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,s.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,s.pick)(e??{},"retries","halt","path"),...(0,s.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},86941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(19851),s=i(59455),n=i(72993),a=i(46292),o=i(95696),l=i(50213),u=i(83179),c=i(28874),d=i(2858),h=i(84438),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),n=await t.resolve_();if(null==r||null==n||n.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=n.join("licenses");for(const r of(0,s.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=n.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),s=i(22573),n=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){_(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&T()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(m.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const b=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],S={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function _(e){for(const t of b)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:S;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function T(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=_,t.disableExternalNetworkRequests=T},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),s=i(53265),n=i(87652);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},4936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(55835),l=i(51926),u=i(50213),c=i(81168),d=i(79842),h=i(21330),f=i(51275),m=i(29882),p=i(28874),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+e.replace(/'/g,"′")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),s=i(83556);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),b=i(44198),S=i(96706),P=i(34102),_=i(28283),T=i(81075),M=i(98778),E=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?n(this,r,"m",s).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?n(this,r,"m",s).call(this,e??t)+": "+i:null==this.fromEnv(e)?n(this,r,"m",s).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,S.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,b.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return T.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,b.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&S.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,b.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&S.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,S.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],E.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],E.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+r],E.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,s=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),s=i(51168),n=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),b=i(7282),S=i(12801),P=i(4328),_=i(70488),T=i(84248),M=i(5531),E=i(99315),k=i(34365),D=i(34580),x=i(96706),C=i(50274),A=i(33866),F=i(52086),I=i(48584),O=i(45969),L=i(43334),R=i(24540),N=i(70379),B=i(71300),j=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),q=i(30577),H=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Y=i(71988),X=i(38483),Z=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),se=i(57039),ne=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(b.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function be(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new X.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new X.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new X.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:be}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new X.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:be}),useFsWatch:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new se.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>H.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:H.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>H.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new X.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new X.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new X.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new X.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new X.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),minDelayBetweenSpawnMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ne.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new X.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:T.AutoVacuumModes,defaultValue:T.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:k.SynchronousModes,defaultValue:k.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new Z.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new X.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new X.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,O.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:A.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new X.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new X.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new X.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:q.UpdateChannels}),autoUpdateCheck:new X.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new X.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new X.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new X.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new X.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new X.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new X.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new X.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":s.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new X.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new X.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new ne.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new X.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new X.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:F.CropStrategies.attention,strEnum:F.CropStrategies}),videoFrameAtSec:new ne.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new X.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new X.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new Z.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new X.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>j.DefaultIncludedPreviewTags}),disableAllFilters:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new X.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new se.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ne.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new X.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new ne.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new X.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new X.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function Se(e){const i=((0,u.blank)(e)?"":e).split(n.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(n.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=Se,t.pathWithDefaults=(0,a.lazy)((()=>Se((0,x.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(31586),n=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{w.Settings.configDir.opts.defaultValue=o.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,n.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,n.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,s.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),b=i(81168),S=i(83556),P=i(87290),_=i(98314),T=i(34102),M=i(83278),E=i(95696),k=i(60865),D=i(4175),x=i(83179),C=i(81075),A=i(28874),F=i(41692),I=i(84438),O=i(32707),L=i(6707),R=i(98778),N=i(55018),B=i(10357),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,O.systemSettingsFile)()){if(null!=e)return Z(M.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,L.readTomlFile_)((0,O.systemSettingsFile)()))?.[A.Settings.libraryDir.name])}catch{return}}function U(e){return(0,L.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function q(){return U((0,O.systemSettingsFile)())}function H(e){return U(z(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:A.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,T.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,x.settingsToObj)(i),wip:r}),r){const t=await(0,L.readTomlFile_)(s),i=await(0,L.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function K(e=(0,O.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,A.persistedSystemSettings)()),t}function Y(e){return Z(z(e))}async function X(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,A.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,A.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Z(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function Q(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,L.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,A.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,A.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}})));return t.info("loaded",{settings:(0,x.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,D.handleDeprecatedSettings)(),(0,D.handleMetaSettings)(a),{settings:a,warnings:n}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Y()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return A.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=q,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await q()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await H()&&await X()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,T.ee)().on("clearCache",G),(0,T.ee)().on("settingsChanged",G),A.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,k.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(E.PosixFile.for(e),(0,A.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=X,t._readSettings=Z,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([A.Settings.noNetwork,A.Settings.httpPort,A.Settings.license,A.Settings.logStdout,A.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(A.Settings))ee().has(e.key)||e.unset();(0,T.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),A.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(E.PosixFile.forMaybe((0,O.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,T.ee)().emit("clearCache"),F.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${(0,k.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>function(e,t){return(0,r.compact)((0,a.splitStringArray)(e)?.map((e=>t.getCI(e))))}(t,e.strEnum),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),s=i(55835),n=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),s=i(44652),n=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},63225:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=void 0;const r=i(68708),s=i(81168),n=i(44198),a=i(59958),o=i(28874);t.verifyPsEnvSettings=function(e=(0,n.env)(),t=.25){const i=[];for(const n of(0,r.keys)(e).filter((e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!a.IgnorableEnvKeys.includes(t)}))){const r=e[n],a=(0,o.ciSettings)().lookup(n);if(null!=a){const e=a.value.whyInvalidEnvValue(r);null!=e&&i.push({envKey:n,msg:e})}else{const e=(0,o.ciSettings)().lookupNearest(n,t);null==e?i.push({envKey:n,msg:`No setting was found like "${n}"`}):(0,s.equalsIgnoreCase)(e.key,n)||i.push({envKey:n,msg:`Did you mean setting "${e.value.key}"?`})}}return i}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),s=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),s=i(81168);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),v=i(81168),w=i(76596),b=i(79842),S=i(66649),P=i(21330),_=i(98725),T=i(928),M=i(54261),E=i(89724),k=i(17415),D=i(88600),x=i(51275),C=i(29882),A=i(17217),F=i(68284),I=i(57902),O=i(28874),L=i(65162),R=i(71300),N=i(14036),B=i(61424),j=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,b.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,A.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,b.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,_.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,k.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,k.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,w.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,x.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,M.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,T.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,x.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,k.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,b.datedToStartDateTime)(this.date)??(0,b.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,b.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function q(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],s=r;if((0,D.isValidDate)(t)){if((0,k.isValidZone)(e.tz)&&(!(0,x.hasZone)(t)||R.OverrideUTCZoneTags.includes(s))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,v.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,b.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,b.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,b.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,x.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function H(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,_.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,b.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,_.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,v.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",q(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??s("tags",q(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("stat+bname",await(0,B.extractStatBname)(e)))??(n?void 0:s("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",H(e,t)))??(n?void 0:s("path",G(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await $(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return q(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),s=i(97352),n=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(77988),n=r(i(76760)),a=r(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),v=i(12168),w=i(56038),b=i(4867),S=i(36557),P=i(98247),_=i(21330),T=i(98725),M=i(23467),E=i(88561),k=i(95696),D=i(17217),x=i(16287),C=i(50213),A=i(17921),F=i(7282),I=i(88158),O=i(23560),L=i(28874),R=i(12089),N=i(45255),B=i(81168),j=i(63870),z=i(15674),V=i(28544),W=i(43207),U=i(72180),q=i(75767),H=i(12788),G=i(80495),$=i(14036),J=i(67083),K=i(3432),Y=i(28630),X=i(15912),Z=i(30748),Q=i(16170),ee=i(95141),te=i(7330),ie=i(54979),re=i(1078),se=i(61424),ne=i(8791),ae=(0,o.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ce()};const le=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,S.batchClusterOptions)((0,F.isTest)()?8:(0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function ue(){const e=le();return e.ended?le.refresh():e}function ce(e=!1){return(0,d.map)(le.clear(),(t=>t.end(e)))}t.exiftool=ue,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeoutError)({p:ue().version(),timeoutMs:N.ShortCommandTimeoutMs})},t.exiftoolVersionMaybe=function(){return(0,d.map)(le.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,j.commandTimeoutMs)()})))},t.shutdownExiftool=ce,t.extractBinaryTag=function(e,t,i){return ue().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),ie.mimetypeCache.prior()?.clear()};async function de(e){return(0,f.omit)(await ge(e,!1),...t.IgnoredSidecarFields)}function he(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function fe(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function me(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function pe(e,t,i){if((0,B.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ae().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,ie.readMimeType)(e),s=await e.sidecar(),n=(0,Q.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Q.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ae().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function ge(e,i=!0){const r=k.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void ae().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ae().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,Y.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,Q.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ae().debug("readRawTags() sidecar had values",{sidecar:e.base})):ae().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,J.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,ee.orientationToRotation)(a.Rotation),ae().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ye(e,t){return null==t?void 0:(0,w.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Q.normalizeMimetype);if((0,u.blank)(r))return void ae().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,T.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ae().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,se.canInferForDir)(e.parent()),l=await(0,K.maybeInferTimezone)(e,n,o);if(ae().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values])if(!(0,U.isUtcTagName)(t)){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,_.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l)}const c=o?(0,Z.extractMakeAndModel)(n):await(0,se.inferMakeAndModel)(e,n);c.Make!==(0,Z.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,Z.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,H.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,X.extractLensMakeModel)(n),h=await(0,V.extractCapturedAt)(e,n,o);if(null==h)return void ae().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,G.extractExposureSettings)(n),g=await(0,re.extractSizeInfoFromFile)(e,n);if(null==g)return void ae().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,ne.extractTitleDescription)(n),...d,cameraId:(0,q.cameraIdFromTags)(n),imageId:(0,q.imageIdFromTags)(n),lensId:(0,q.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(n),tz:n.tz,rating:(0,te.extractRating)(n)};(0,F.isTest)()&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ae().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ae().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,M.eqlAsync)(e.sha(),t.sha())||await(0,M.eqlAsync)(de(e),de(t))},t.readTags=he,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=k.PosixFile.for(e);return ye(t,await ge(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await he(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await ue().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ae().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,ee.extractRotation)(await ge(e,!0))},t.moveOriginal=fe,t.overwriteTags_=async function(e,t){try{await(0,w.time)("exiftool.overwriteTags:"+e,(async()=>{await ue().write(e.nativePath,t,await me(e)),e.clearThisAndParent()}))}catch(i){ae().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await ue().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=me,t.writeTagDest=pe,t.writeTags_=function(e,t,i){return(0,w.time)("exiftool.writeTags:"+e,(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await pe(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=k.PosixFile.for(t),s=(0,f.fromEntries)(i);ae().info("writeTags()",{src:e,dest:t,t:s}),await ue().write(r.nativePath,s,await me(r)),L.Settings.overwriteOriginal.valueOrDefault||await fe(r),r.clearThisAndParent()}}))},t.readRawTags=ge,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ae().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ae().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...L.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,$.isVideoExt)(n.default.extname(e))?[]:["-fast"]],r=await(0,w.time)("exiftool.read()",(()=>ue().read(e,i).catch((t=>{ae().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ae().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,Q.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),oe&&(r.__instance=(0,A.safeUUID)()),r}}),t.parseTags=ye},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function _(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function T(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([_(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(_)):(0,u.compactBlankValues)(t)}function M({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=T,t.findInequalFields=function(e,i){const r=T(e),n=T(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>M({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>M({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>M({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>M({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),s=i(40958),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),s=i(45599),n=i(68708),a=i(50213),o=(0,s.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,n.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:s}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[s])&&(t[i]=t[s]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,n.pick)(e,"Directory","FileName"));for(const t of(0,n.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),v=i(50213),w=i(81168),b=i(66649),S=i(17415),P=i(29882),_=i(95696),T=i(17217),M=i(28874),E=i(47783);function k(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=k,t.mkHistoryRecord=D,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function A(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function F(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,T.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=_.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=A(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=A,t.inferredToTags=F,t.ensureInferredHistoryRecords=async function(e,i,r){const s=k(t.Actions.infer,r),n=(M.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?F(r):void 0)??{};return M.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),I(i,s,n)},t.ensureHistoryRecords=I},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(53705)),n=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),w=i(14245),b=i(61424),S=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,w.omitInvalidGeolocationTags)(t);{const e=_(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=T(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function _(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return S().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function T(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,u.toDated)(t[r]);if(null==s||(0,f.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return S().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return S().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=_,t.inferTzOffsetMinutesFromFilename=T},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function _(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function T(e){return Array.isArray(e)&&e.every(T)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(T))}function M(e){if(null==e)return[];if(Array.isArray(e)&&e.every(T))return(0,h.flatMap)(e,M);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,M).map((t=>[e.Keyword,...t]))}t.parseCategories=_,t.isKeywordStruct=T,t.parseKeywordStruct=M,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=_(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(T(i)?t.push(...M(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},38010:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(50213),g=i(84885),y=i(66649),v=i(98725),w=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function _(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-_(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),s=i(54993),n=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},66039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(75020),u=i(59455),c=i(50213),d=i(68852),h=i(81168),f=i(70417),m=i(28874),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,v=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,w=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,v),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function _(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,w),null!=e&&(_(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const T=(0,s.compactBlanks)(t.split(/\s+/)),M=l.length,E=b.length;if(T.length>0)if(0===M&&E>0)l.push(...T);else if(0===E&&M>0&&1===T.length)b.push(...T);else if(1===T.length)l.push(...T);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?T.pop():T.shift()),l.push(...T)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function _(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function T(e,t,i){return _("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=_([t.modifier,t.lifespan]),r=_(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?_([r,e]):T(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),s=i(54993),n=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),s=i(40958),n=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,s.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},3127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(54993),s=i(42231);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),v=i(79842),w=i(21330),b=i(98725),S=i(51275),P=i(35280),_=i(19748),T=i(88561),M=i(95696),E=i(65238),k=i(17217),D=i(57902),x=i(28874),C=i(80496),A=i(65162),F=i(28544),I=i(47783),O=i(88840),L=i(30748),R=i(16170),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new T.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,_.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7,i=!0){if(!await j(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(r,(e=>(0,A.bname)(e))),n=(0,k.findFileIndex)(e,s);if(n<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),H(e,t,!1)):void 0;const l=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[s.slice(n-2*t,n),s.slice(n+1,n+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),s=i(22573),n=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),s=i(57975),n=i(90595),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return M(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(M(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=M(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function T(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?T:_;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:_(o,!1)),r}function k(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+k(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=M;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(D)?e.replace(D,(e=>k(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),s=i(40958),n=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),s=i(22573),n=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(9103),a=i(37628);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},50036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=void 0;const r=i(46292),s=i(95696);t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")}},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),s=i(30577);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),s=i(22573),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},27274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.semverGte=t.semverLatest=void 0;const r=i(54993),s=i(48884),n=i(76280),a=i(30577);function o(e){const t=(0,n.toSemver)(e),i=a.UpdateChannels.ordinal((0,a.extractUpdateChannel)((0,r.toS)(e)));return null==t?void 0:[t.major,t.minor,t.patch,i,...t.prerelease.slice(1)]}function l(...e){return(0,s.greatestBy)(e,o)}t.semverLatest=l,t.semverGte=function(e,t){return l(e,t)===e}},38244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateChannelVersion=void 0;const r=i(68708),s=i(51926),n=i(30577);t.isUpdateChannelVersion=function(e){return(0,r.isObject)(e)&&n.UpdateChannels.has(e.channel)&&(0,s.isString)(e.version)}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},63335:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=void 0;const r=i(22573);t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v|ver|version)?\s*/,"version ")}},40044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=t.checkVersion_=t.currentChannel=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(75240),l=i(17344),u=i(50213),c=i(37805),d=i(5916),h=i(46292),f=i(16287),m=i(43205),p=i(28874),g=i(63870),y=i(89372),v=i(50036),w=i(60865),b=i(27274),S=i(38244),P=i(30577),_=i(63335),T=(0,a.defer)((()=>(0,u.mkLogger)("VersionCheck")));t.currentChannel=function(){const e=[p.Settings.updateChannel.valueOrDefault,(0,w.channel)()].map((e=>P.UpdateChannels.ordinal(e))).sort()[0];return P.UpdateChannels.values[e]??p.Settings.updateChannel.valueOrDefault},t.checkVersion_=async function(e){if(p.Settings.noNetwork.valueOrDefault)return{level:"disabled",msg:["PhotoStructure version checking is disabled","Set "+(0,s.tt)(p.Settings.noNetwork.toEnvLine(!1))+" to enable."]};if(!p.Settings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===p.Settings.optOut.value?e.push("Set "+(0,s.tt)(p.Settings.optOut.toEnvLine(!1))+" to enable."):!1===p.Settings.autoUpdateCheck.value?e.push("Set "+(0,s.tt)(p.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.tt)(p.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,h.configDir)();if(null==i||!await(0,f.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const u=e?.installedVersion??c.version,d=(0,P.extractUpdateChannel)(u),m=(0,P.eligibleForChannel)(d),g=a.versions.filter((e=>m.includes(e.channel))).map((e=>e.version)),y=e?.latestVersion??(0,b.semverLatest)(...g);if(null==y)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+p.Settings.updateChannel.toEnvLine()]};const v=(0,P.extractUpdateChannel)(y),w="You are running "+(0,l.EditionName)()+" "+(0,_.ver)(u),S="The latest published "+(0,s.tt)(v)+" build is "+(0,_.ver)(y),T=v===d?void 0:"You should consider switching to the "+(0,s.tt)(v)+" channel.",M=Date.now()-a.updatedAt,E="Last checked "+(M{const e=(0,v.channelVersionsCache)(),i=await(0,y.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",headers:{"User-Agent":await(0,m.userAgent)()},cache:e,ttlMs:n.dayMs,preCacheTransform:e=>({versions:e,updatedAt:Date.now(),updatedByVersion:c.version})}),r=i.data;if(null==r||!Array.isArray(r.versions)||0===r.versions.length||r.versions.some((e=>!(0,S.isUpdateChannelVersion)(e)))||r.updatedByVersion!==c.version){if(i.fromCache)return T().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();T().throw("getChannelVersions_(): Invalid response",{result:r})}return T().tap({msg:"getChannelVersions_()",result:r})}})},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),s=i(9595),n=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},42233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(45200),s=i(98770),n=i(7014);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),s=i(22573),n=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),b=i(24541),S=i(60224),P=i(63870),_=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const T=/([a-z]+)(?::\\)?/i;function M(e){return e?.match(T)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(M(e),(e=>e+":\\"))}function k(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(M(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(M(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=k,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function A(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function F(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([A(e.HealthStatus,"healthy"),A(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function I(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(D)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(F)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=F,t.volumeInfoWin=I},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),b=i(16287),S=i(45969),P=i(43334),_=i(69108),T=i(98770),M=i(44224),E=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const k=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?k().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,M.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):k().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(k().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void k().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await D(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,E.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,T.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void k().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),s=i(5233),n=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),_=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),s=i(19851),n=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),b=i(8769),S=i(34102),P=i(17217),_=i(16287),T=i(43334),M=i(28874),E=i(8540),k=i(68884),D=i(44224),x=i(24541),C=i(69375),A=i(63870),F=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function O(e=(0,A.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function L(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{M.Settings.libraryDir.watchLater(I),M.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&M.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(T.isMac&&(e.info("Setting up Mac diskutil activity watcher"),O((0,A.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),T.isLinux){const i=(0,D.maybeWatchProcMounts)();await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),O((0,A.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),O((0,A.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=M.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",T.isWin?x.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,A.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||M.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(T.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return T.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,S.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),I()})),M.Settings.mountpointsTtlMs.watch(O)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>L(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),L()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!T.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,A.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>L(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),b=i(68884),S=i(59107),P=i(69375),_=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await k()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,b.isGioSupported)())try{await(0,c.thenMap)((0,b.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){_().warn("Failed to fetch gio volumes",e)}return e};const T="/proc/mounts";function M(e){return!v.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function k(e=T,t=M,i=E){if(y.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return _().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return _().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void _().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=k,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(T)?new h.FileWatcher(T,{recursive:!1,persistent:!1},(()=>{_().info("detected change in "+T),(0,d.setUnrefTimeout)((()=>S.mountpoints.refresh()),n.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),s=i(42659),n=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await M()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function T(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,u.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=T;const M=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?T():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(_(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),s=i(12168),n=i(28874);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),b=i(28874),S=i(59107),P=i(63870),_=i(68995),T=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function E(e){return(0,a.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function k(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=k(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(b.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of b.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),r=await D(i).catch((e=>T().info("Failed to read "+i,{error:e})));if(null!=r)return T().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,_.volumeUuidSubpath)());if("/"===e.mountpoint)return T().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(b.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return T().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(b.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,_.writeVolumeUuid)(e);if(!(0,n.blank)(t))return T().tap({msg:"readVolumeUUID(): wrote new "+(0,_.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return T().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),S.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(E(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>T().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=E,t.toVolumeUUID=k,t.readUuidFile_=D,t.readVolumeUUID=x},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),b=i(50213),S=i(7282),P=i(23560),_=i(28850),T=i(45255),M=i(81168),E=i(56519),k=i(4867),D=i(49776),x=i(9595),C=i(77740),A=i(44198),F=i(96706),I=i(8769),O=i(57159),L=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),j=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),q=i(43334),H=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Y=i(27461),X=i(66840),Z=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=s.default.platform(),ne=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,ne),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,x.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ne.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,M.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:se}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))n.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:T.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,Z.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function me(e,i){const r=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(r))return;const s=await(0,L.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function pe(e,t,i){const r=i.filter((e=>(0,M.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,M.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,W.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,M.equalsIgnoreCase)(n,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,S.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,v.toA)(await(0,Z.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,k.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,O.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if((0,S.isTest)()){const e=(0,p.toInt)((0,A.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeoutError)({p:q.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeoutError)({p:q.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,M.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},72901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkEventStream=void 0;const r=i(22573),s=i(98553),n=i(65211);t.mkEventStream=function(...e){let t="";for(const i of e)null!=i&&((0,r.blank)(i.event)||(t+="event: "+i.event+"\n"),t+="id: "+(i.id??(0,n.uid)())+"\n",t+="data: "+(0,s.stringify)(i.data)+"\n",t+="\n");return t}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},89372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=void 0;const r=i(45599),s=i(98553),n=i(31586),a=i(50213),o=i(51140),l=i(4988),u=(0,r.defer)((()=>(0,a.mkLogger)("web.HttpGet")));t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,n.gt0)(await t.size())&&(0,n.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await(0,l.get_)(e.url,{headers:e.headers});o.HttpStatusIs.success(r.statusCode)||u().throw("Failed",{url:e.url,response:r});const a=(0,s.parseJSON_)(r.data),c=e.preCacheTransform?.(a)??a;return u().info("Fetch success. Caching",{args:e,json:c,cache:t}),await t.writeJson_(c),{data:c,updatedAt:Date.now(),fromCache:!1}}},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAjaxRequest=t.isHttpsRequest=t.parseForwarded=void 0;const r=i(22573),s=i(59455),n=i(81168),a=i(28874);function o(e){if((0,r.blank)(e))return{};let t=(0,s.toA)(e).join(";").trim().replace(/^[,;]/,"").replace(/[,;]$/,"");const i={};for(;t.length>0;){const e=t.indexOf("=");if(e<0)break;const r=(0,n.stripQuotes)(t.slice(0,e).trim().toLowerCase());if(t=t.slice(e+1).trim(),/^["']/.test(t)){const e=/['"]\s*(?:[;,]|$)/.exec(t.slice(1))?.index;if(null==e)break;const s=(0,n.stripQuotes)(t.slice(0,e+2).trim());i[r]=s,console.log("quoted",{k:r,v:s,s:t,vIdx:e}),t=t.slice(e+3).trim()}else{const e=/[;,]|$/.exec(t)?.index;if(null==e)break;const s=t.slice(0,e).trim();i[r]=s,console.log("unquoted",{k:r,v:s,s:t,vIdx:e}),t=t.slice(e+2).trim()}}return i}function l(e){return(0,r.blank)(e)||function(e){return Array.isArray(e)&&0===e.length}(e)?void 0:(0,s.toA)(e).join(";")}t.parseForwarded=o,t.isHttpsRequest=function(e){return null!=e&&"false"!==a.Settings.trustProxy.valueOrDefault&&((0,n.equalsIgnoreCase)("https",o(e.forwarded).proto??l(e["x-forwarded-protocol"])??l(e["x-url-scheme"]))||"on"===l(e["front-end-https"])||"on"===l(e["x-forwarded-ssl"]))},t.isAjaxRequest=function(e){return"application/json"===e?.["content-type"]}},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),h=i(34238),f=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const a=n(i(37067)),o=n(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),h=i(50213),f=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),v=(0,u.defer)((()=>(0,h.mkLogger)("net.get")));async function w(e,t){return b({...t,url:e})}async function b(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?a.request:"https"===t.scheme?o.request:v().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??f.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",h=e?.agent??!1,b=r(t.toString(),{method:c,headers:u,timeout:n,agent:h},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const a={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&y.HttpStatusIs.redirect(a.statusCode)&&!(0,l.blank)(e.headers.location)?(v().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(w(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(v().debug("complete",{...a,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(a))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||b.write(e.body),b.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=w,t.httpRequest_=b},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},14854:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(48161)),h=i(42659),f=i(45599),m=i(55835),p=i(31586),g=i(68708),y=i(19851),v=i(50213),w=i(7282),b=i(78406),S=i(25764),P=i(38835),_=i(74128),T=i(82647),M=i(43334),E=i(28874),k=i(30933),D=i(15674),x=(0,y.lazy)((()=>(0,v.mkLogger)("work.CpuUsage"))),C=(0,y.lazy)((()=>{const e=A.instance().busyPct();(0,_.syncReport)().maybeSystemData({from:"cpuUsage",state:"note",details:"Current system load is too high to schedule more work",meta:(0,g.compactValues)({loadCpuPct:I(),cpuBusyPct:e})}),x().warn("Current system load is too high to schedule more work",{cpuBusyPct:e,max:E.Settings.cpuBusyPercent.valueOrDefault})}),((0,w.isTest)()?15:60)*h.secondMs);t.isTooBusy=function(){if(E.Settings.cpuBusyPercent.valueOrDefault<=0)return!1;const e=A.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(4*E.Settings.cpuBusyPercent.valueOrDefault/3));return(0,p.gte)(e,t)?(C(),!0):(C.unset(),!1)};class A extends b.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,D.singleThreadedMode)()?60:M.isWin?20:10)*h.secondMs,rank:S.EndableRanks.first}),r.add(this),s.set(this,new T.Average(5)),n.set(this,new F),(0,p.mapFinite)(I(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??I()}}t.CpuUsage=A,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,I());const e=new F;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},A.instance=(0,f.defer)((()=>new A));class F{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?(0,p.sigFigs)(t/r*100,3):void x().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+P.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function I(){return M.isWin?void 0:(0,p.sigFigs)(d.default.loadavg()[0]/(0,k.cpuInfo)().length*100,3)}},73328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyDoNotRun=t.doNotRun=void 0;const r=i(68708),s=i(99331),n=i(74128),a=i(63664),o=i(14854);t.doNotRun=function(e){return null!=u(e)};const l=["error","no-library","stop-sync"];function u(e){if(!0===e?.ended)return"endable ended";if((0,s.ending)())return"service is ending";if((0,o.isTooBusy)())return"system is too busy";const t=(0,a.getRemoteOrLocalHealthSummarySync)();if(null==t||!l.includes(t.level))return;const i=t.level+": "+t.msg.join("\n");return(0,n.syncReport)().maybeSystemData({from:"whyDoNotRun",state:"note",details:t.level,meta:(0,r.omit)(t,"links","buttons")}),i}t.whyDoNotRun=u},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),s=i(37692);let n=!1;function a(){return n}function o(e=!0){l(e),(0,s.writeStateFile)({paused:e})}function l(e){e!==n&&(n=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=a,t.pause=o,t.resume=function(){return o(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return a()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),s.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=b,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(b()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(b()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=w();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,v());return t=(0,a.clamp)(1,s,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const s=r(i(78474)),n=i(40958),a=i(76790),o=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),h=i(87290),f=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),v=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let w;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new s.default;let b=0;function S(){const e=(0,h.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-b>o.minuteMs;i&&(b=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(w?.nativePath)||(w?.close(),w=void 0),r&&null!=e&&(w??(w=new f.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=S()?.readJsonSync();for(const i of e?.events??[])_.get(i.e)!==i.ts&&(v().info("emitting event "+i.e),t.stateEvents.emit(i.e),_.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const _=new Map;function T(e){const i=S();if(null==i)v().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),s=function(e){const t=Date.now()-10*o.minuteMs;return(0,n.uniqByLast)((0,a.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:s};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=T,t.addStateEvent=function(e){const t=Date.now();_.set(e,t),T({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),s=i(87997),n=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},83600:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.RequestTask=void 0;const a=i(58587),o=i(80875),l=i(19851),u=i(50213),c=i(34102),d=i(84542),h=i(87445),f=i(40958),m=i(26905),p=i(98553),g=i(31586),y=(0,l.lazy)((()=>(0,u.mkLogger)("worker.RequestTask")));class v extends a.Task{constructor(e){super((0,p.stringify)(e),(e=>n(this,r,"m",s).call(this,e))),r.add(this),this.request=e}}t.RequestTask=v,r=new WeakSet,s=function(e){for(const t of(0,f.compactBlanks)((0,d.splitLines)(e))){const e=(0,o.parseJSON)(t);if(null==e)y().warn("ignoring non-json line from worker",{line:t});else{if(null!=e.error)throw y().warn("worker threw error",{response:e}),(0,m.errorFromJson)(e.error);if((0,g.isNumber)(e.id))return e.id!==this.request.id?y().throw(`bad request: #parse given mismatching requests (${e.id} != ${this.request.id})`,{response:e,request:this.request}):e.response;(0,h.isProgressEvt)(e)?(0,c.ee)().emit("progress",e):y().warn("ignoring json line from worker",{response:e})}}return y().throw("bad request: #parse missing valid response")}},93493:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearShims=t.setupShimDelegates=void 0;const r=i(19851),s=i(5233),n=i(68708),a=i(13538),o=i(57206),l=i(50213),u=i(23560),c=i(70025),d=i(28874),h=i(15674),f=i(22751),m=i(83600),p=i(58800),g=i(24817),y=(0,r.lazy)((()=>(0,l.mkLogger)("worker.ShimDelegation")));let v=0;async function w(e,t){const i=d.Settings.taskTimeoutMs.valueOrDefault;return(0,s.retryOnReject_)((async()=>{y().throwIfAborted_();const r={id:v++,fn:e,args:t},s=new m.RequestTask(r),n=await(0,p.workerCluster)(),o=n?.t,l=null==n||null==o?g.WorkerFunctions[e](...t):n.awaitOrAbort(o.enqueueTask(s));return(0,a.thenOrOnTimeout)(l,i/3,(()=>{y().warn("soft timeout servicing work request",{request:r,timeoutMs:i}),(0,f.onTimeout)()})),(0,a.thenOrTimeoutError)(l,i)}),{maxRetries:d.Settings.maxRetries.valueOrDefault,timeoutMs:i,retryDelay:d.Settings.minDelayBetweenRetriesMs.valueOrDefault,errorIsRetriable:e=>!1!==(0,c.isRetriableError)(e)})}function b(){for(const e of(0,n.values)(g.WorkerFunctions))(0,n.maybeCall)(e,"clearShim")}t.setupShimDelegates=async function(){if((0,o.addDefaultJsonRevivers)(),(0,u.isWorkerService)())b(),y().warn("setupShimDelegates(): in worker service, skipping");else if((0,h.singleThreadedMode)())y().warn("setupShimDelegates(): single-threaded mode, clearing shims"),b(),await(0,p.endWorkerCluster)();else for(const[e,t]of(0,n.entries)(g.WorkerFunctions))t.setShim((t=>w(e,t)))},t.clearShims=b},24817:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequest_=t.isWorkRequest=t.mkWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=t.AllWorkerFunctionCandidates=void 0;const r=i(98553),s=i(31586),n=i(68708),a=i(50989),o=i(32639),l=i(13991),u=i(50597),c=i(48368),d=i(52121),h=i(48604),f=i(181),m=i(66106),p=i(47783),g=i(83966);t.AllWorkerFunctionCandidates={_extractVideoFrame_:m._extractVideoFrame_,_readRawTags:p._readRawTags,_readTags:p._readTags,assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkerFunctions={assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkRequestMethods=(0,a.strEnum)(...(0,n.keys)(t.WorkerFunctions));let y=0;t.mkWorkRequest=function(e,t){return{id:++y,fn:e,args:t}},t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,s.isNumber)(e.id)},t.handleWorkRequest_=async function(e){const i=t.WorkerFunctions[e?.fn];if((0,o.isFunction)(i))return i(e?.args);throw new Error("invalid method "+(0,r.stringify)(e))}},58800:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerCluster=t.endWorkerCluster=t.workerClusterPriorEnd=void 0;const r=i(58587),s=i(36557),n=i(19851),a=i(50213),o=i(71567),l=i(25764),u=i(84777),c=i(86335),d=i(38835),h=i(84542),f=i(87445),m=i(41944),p=i(15674),g=i(42659),y=i(98553),v=i(31586),w=i(67478),b=i(54993),S=i(27395),P=i(5916),_=i(55534),T=i(29325),M=i(28874),E=i(30933),k=i(41657),D=(0,n.lazy)((()=>(0,a.mkLogger)("worker.cluster")));t.workerClusterPriorEnd=async function(){return(await t.workerCluster.prior())?.t.closeChildProcesses()},t.endWorkerCluster=function(){return(0,S.end)(t.workerCluster.prior())},t.workerCluster=(0,P.lazyAsync)({desc:"worker.workerCluster",later:async()=>{const e=await(0,c.pathToService)("worker");if(null==e)return D().throw("Could not find worker.js"+d.FatalErrorFlag);D().info("worker.js found at "+e);const t={id:-1,fn:"ping",args:{}},i=new r.BatchCluster({processFactory:async()=>(D().info("Spawning new worker",{execPath:process.execPath,worker:e.nativePath,maxProcs:(0,p.maxCpus)()}),(0,u.spawn)(process.execPath,[e.nativePath],0,{env:await(0,k.workerEnv)()})),...(0,s.batchClusterOptions)((0,p.maxCpus)(),"worker.BatchCluster"),streamFlushMillis:0,versionCommand:(0,y.stringify)(t),healthCheckCommand:(0,y.stringify)(t),taskTimeoutMillis:M.Settings.taskTimeoutMs.valueOrDefault,maxProcAgeMillis:4*M.Settings.taskTimeoutMs.valueOrDefault,minDelayBetweenSpawnMillis:(0,T.isPacked)()?g.secondMs:1,pass:o.ReadyStr,fail:d.FatalErrorRe,exitCommand:_.ServiceExitCommand});return i.on("taskData",(e=>{for(const t of(0,h.splitLines)((0,b.toS)(e))){const e=(0,w.parseJSON)(t);(0,f.isProgressEvt)(e)&&(0,m.emitProgressEvt)(e)}})),p.maxCpus.watchLater((e=>{const t=(0,v.clamp)(1,(0,E.cpuCount)(),e??(0,p.maxCpus)());return D().warn("maxConcurrentImports changed",{maxProcs:t,newValue:e}),i.setMaxProcs(t)})),new s.BatchClusterObserver("worker",i,l.EndableRanks.first)}})},41657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerEnv=void 0;const r=i(9727),s=i(28874),n=i(59107);t.workerEnv=async function(){const e={};return s.Settings.libraryDir.addToEnv(e),s.Settings.mountpoints.addToEnv(e,await(0,n.mountpoints)()),(0,r.childEnv)({overrides:e,forWorker:!0})}},83966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const s=r(i(1708)),n=i(41400),a=i(31586),o=i(7282),l=i(12089),u=i(45608),c=i(57159),d=i(89035);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),(0,o.isTest)()&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:s.default.pid,input:e?.input??"(no input)"}}})},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},75761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),s=i(31586),n=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),s=i(22573),n=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),s=i(73872);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s.hasPrior=()=>r,s}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),s=i(21605),n=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},87562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExampleDomain=void 0;const r=i(40958),s=i(51926),n=["example.com","example.net","example.org","example.edu",".example",".local"].map((e=>(0,s.stripPrefix)(e,".").split(".")));t.isExampleDomain=function(e){const t=e.toLowerCase().split(".");return n.some((e=>(0,r.arrayEndsWith)(t,e)))}},25763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEmail=t.isEmailMaybe=void 0;const r=i(22573),s=i(87562),n=i(54993);t.isEmailMaybe=function(e){return null!=o(e)};const a=/^(?.+)@(?.[^@\n\r.\u2028\u2029]*\..+)$/;function o(e){const t=a.exec((0,n.toS)(e).trim());if(null==t?.groups)return;const{local:i,domain:o}=t.groups;return(0,r.blank)(i)||(0,r.blank)(o)||(0,s.isExampleDomain)(o)?void 0:{local:i,domain:o}}t.parseEmail=o},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),s=i(68708),n=i(34666),a=i(32639);function o(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,n.isPrimitive)(e)||(0,n.isPrimitive)(t))return e===t;if(!(0,s.isObject)(e)||!(0,s.isObject)(t))return!1;for(const i of(0,s.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),s=i(42659),n=i(55835),a=i(31586),o=i(12168),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),s=i(50357),n=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class s extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=s},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,(t=>!e(i,t,s)));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),s=i(22573),n=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,s){return!(null==s||!o(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,s.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return o(e)&&e>0}function b(e){return o(e)&&e>=0}function S(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function T(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=S,t.map2Numeric=function(e,t,i){return S(e,(e=>S(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,n.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return S(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=T,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return T(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),s=i(30976),n=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),s=i(54993),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),s=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),s=i(68708),n=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let s=!0;const n=setTimeout((()=>{s&&(s=!1,i(a.Timeout))}),t);try{n.unref?.();const t=await e;s&&(s=!1,i(t))}catch(e){s&&(s=!1,r(e))}finally{clearTimeout(n)}}))}async function c(e,t,i=!0){const s=await u(e,t,i);if(s===a.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return s}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?a.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return c(e,s,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,n.tot)(i);const s=await u(e,t,r);return s===a.Timeout?(0,n.tot)(i):s}},99036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ThumbFits=void 0;const r=i(50989);t.ThumbFits=(0,r.strEnum)("aspect","square")},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),s=i(30301),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(30301),s=i(54993);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},32790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeQuote=t.AssetQueryOrderByColumns=void 0;const r=i(50989),s=i(54993);t.AssetQueryOrderByColumns=(0,r.strEnum)("capturedAt","updatedAt"),t.maybeQuote=function(e){return null!=(e=(0,s.toS)(e).trim()).match(/\s/)?`"${e}"`:e}},58939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(55835),s=i(31586);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},12236:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.noRecentAssetIdsProgress=t.isRebuildProgress=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0;const r=i(50989);t.SyncStatuses=(0,r.strEnum)("processing","paused","done"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI].includes(e?.uri)},t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},41942:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkReplace=t.XLocationReplace=t.mkRedirect=t.XLocationRedirect=void 0,t.XLocationRedirect="X-Location-Redirect",t.mkRedirect=function(e,i){return{[t.XLocationRedirect]:e,toast:i}},t.XLocationReplace="X-Location-Replace",t.mkReplace=function(e,i){return{[t.XLocationReplace]:e,toast:i}}},71050:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isServerToast=t.DismissAnchor=t.isToastPlusOnly=void 0;const r=i(22573);t.isToastPlusOnly=function(e){return!0===e?.toastPlusOnly},t.DismissAnchor="#dismiss",t.isServerToast=function(e){return(0,r.notBlank)(e?.text)}},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},94383:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPath=void 0,t.ApiProgressPath="/sse/progress"},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),s=i(30301),n=i(31586),a=i(97238),o=i(29652);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return n(e)??[]},t.optToA=n},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),s=i(23541),n=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},98401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cancelFileAndProcCleanups=t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=t.maybeCleanup_=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(56519),o=i(76187),l=i(87290),u=i(79267),c=i(32144),d=i(13829),h=i(69734),f=i(95696),m=i(65238),p=i(70257),g=i(13940),y=i(12495),v=i(95402),w=i(28874),b=i(40958),S=i(42659),P=i(31586),_=i(64526),T=i(22526),M=i(69032),E=(0,r.lazy)((()=>(0,s.mkLogger)("library.Cleanup")));async function k(){const e=_.Library.instance();if(null==e)E().info("No library to vacuum.");else{E().info("Running tag and search maintenance...");try{await(0,M.runTagMaintenance)()}catch(e){E().warn("Failed to run tag maintenance",{error:e})}E().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,n.isDbJanitorService)()&&(E().info("Running database maintenance..."),await e.runDbBackup_())}E().info("Cleaning child processes..."),await(v.Pids.instance()?.killOldProcs()),E().info("Cleaning stale and temp files..."),await D(),await(0,a.mapAsync)({name:"fileCleanup",arr:j(),f:e=>e.cleanup()})}t.maybeCleanup_=(0,r.lazy)(k,5*S.minuteMs),t.cleanup_=k;const D=(0,r.lazy)((()=>(0,l.libraryDataDirPosixFile)()?.join("shared-state").rmrf())),x=(0,r.lazy)((()=>u.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:g.imageCacheDir_,staleMs:w.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ImageCacheName)}))),C=(0,r.lazy)((()=>u.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>f.PosixFile.for((0,m.readdirCacheDir)()),staleMs:w.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(m.ReadDirCacheName)}))),A=(0,r.lazy)((()=>u.FileCleanup.for({name:"previewWipCleanup",rootNativePath:l.libraryPreviewsDirPosixFile,staleMs:S.hourMs,isPrunable:e=>(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)}))),F=(0,r.lazy)((()=>u.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:d.defaultFsAdvisoryLockDir,staleMs:S.hourMs,isPrunable:h.isPsLockFileOrDir}))),I=(0,r.lazy)((()=>u.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,P.gt0)(w.Settings.syncReportRetentionCount.valueOrDefault)?(0,l.librarySyncReportsDir)():void 0,staleMs:S.hourMs,isPrunable:e=>(0,p.isWip)(e)||(0,c.isCsvExt)(e)})));function O(e){return(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)||(0,o.isSqliteFile)(e)}const L=(0,r.lazy)((()=>u.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,T.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:S.hourMs,isPrunable:O}))),R=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,T.libraryDbObjects_)().libraryDbBackupDir,staleMs:S.hourMs,minRetained:w.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:O})));async function N(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const B=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:N,staleMs:S.hourMs,minRetained:1,isPrunable:O})));function j(){return(0,b.compact)([x(),C(),A(),F(),(0,y.LogDirCleanup)(),I(),L(),R(),B()])}t.fileCleanups=j,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{v.Pids.instance()?.scheduleInterval();for(const e of j())e.scheduleInterval()})),t.cancelFileAndProcCleanups=function(){t.scheduleFileAndProcCleanups.unset(),v.Pids.instance()?.cancelInterval();for(const e of j())e.cancelInterval()}},64526:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(27395),u=i(25764),c=i(38836),d=i(99331),h=i(45608),f=i(15056),m=i(87290),p=i(38835),g=i(57159),y=i(61704),v=i(95696),w=i(18454),b=i(13940),S=i(48604),P=i(19851),_=i(23560),T=i(28874),M=i(2858),E=i(7014),k=i(63870),D=i(15674),x=i(22573),C=i(38639),A=i(42659),F=i(56409),I=i(68708),O=i(25470),L=i(22526),R=i(41844);class N extends c.EndableWrapper{static instance(){const e=T.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,_.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,M._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired_(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new F.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted_(),await(0,M.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted_();const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=T.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;T.Settings.maxConcurrentImports.hasValue()||(T.Settings.maxConcurrentImports.tmpValue=e,(0,D.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted_(),(0,_.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted_(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.previews=(0,P.lazy)((()=>(0,I.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new R.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,_.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.onEnd=(0,P.lazy)((async()=>{if(!(0,d.ending)())for(const{ea:e,t}of[{ea:this.dbModelJanitor.clear(),t:5*A.minuteMs},{ea:this.dbFsLock.clear(),t:(0,k.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise.then((()=>this))}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup_(){return(await this.dbModelJanitor())?.backup_()}}t.Library=N,r=N,n=new WeakMap,s={value:void 0}},19113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(62105),s=i(181),n=i(94448),a=i(39604);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},78339:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveLibrarySettings=t.importSettings=t.librarySettings=void 0;const r=i(19851),s=i(50213),n=i(71567),a=i(87290),o=i(98314),l=i(95696),u=i(28874),c=i(2858),d=i(32707),h=i(22573),f=i(50357),m=i(54993),p=i(14611),g=(0,s.mkLogger)("LibrarySettings");function y(e={}){return g.tap({msg:"librarySettings",level:"info",result:{scanAllDrives:u.Settings.scanAllDrives.valueOrDefault,scanPath:u.Settings.scanPaths.values,copyAssets:u.Settings.copyAssetsToLibrary.valueOrDefault,autoUpdateCheck:u.Settings.autoUpdateCheck.value,allowUserAgent:u.Settings.allowUserAgent.value,reportErrors:u.Settings.reportErrors.value,...e}})}function v(e){u.Settings.scanAllDrives.setValueIfDefined(e.scanAllDrives),u.Settings.scanPaths.setValueIfDefined(e.scanPath),u.Settings.copyAssetsToLibrary.setValueIfDefined(e.copyAssets),u.Settings.autoUpdateCheck.setValueIfDefined(e.autoUpdateCheck),u.Settings.allowUserAgent.setValueIfDefined(e.allowUserAgent),u.Settings.reportErrors.setValueIfDefined(e.reportErrors)}t.librarySettings=y,t.importSettings=v,t.saveLibrarySettings=async function(e,t){const i=l.PosixFile.forMaybe((0,m.toS)(e).trim())?.resolve(),s=y(),w=u.Settings.libraryDir.valueOrDefault,b=i??l.PosixFile.forMaybe(w);let S=Promise.resolve();const P=(0,r.lazy)((()=>{S=S.then((async()=>{try{v(s),u.Settings.libraryDir.value=w,await(0,c.writeSystemSettings_)(),(0,h.blank)(w)||await(0,c.writeLibrarySettings_)(w),await(0,p.restartLibrary_)()}catch(e){g.warn("Failed to roll back to prior settings",{priorSettings:s,priorLibraryDirValue:w,error:e})}}))}));if(null==b)return{error:"Please choose a directory for your library.",ready:S};const _=b?.nativePath!==w;if(_){try{await(0,a.setupLibraryDirs_)(b)}catch(e){return{error:"Failed to set up "+b+". Please choose a different directory for your library. "+(0,o.errorToS)(e)}}g.info("Library directory changed, asking sync to shut down",{prior:w,new:i?.nativePath}),n.StdoutWrite.shutdownSync()}try{v(t);const e=!(0,f.eql)(s,y());if(null==await(0,c.writeLibrarySettings_)(b.nativePath))return P(),{error:"Cannot write to "+b.nativePath+". Please choose a different directory for your library.",ready:S};u.Settings.libraryDir.value=b.nativePath;try{await(0,c.writeSystemSettings_)()}catch(e){return P(),g.warn("Failed to write system settings",e),{error:"Couldn't write your system settings to "+(0,d.systemSettingsFile)()+": "+(0,o.errorToS)(e),ready:S}}return g.info("saveLibrarySettings()",{libraryDirChanged:_,librarySettingsChanged:e,settings:t,priorSettings:s,currentSettings:y()}),(_||e)&&(S=S.then((()=>(0,p.restartLibrary_)({readSettings:!1})))),{msg:"Saved",ready:S}}catch(e){return P(),g.error("Failed to save settings",{error:e}),{error:"Failed to save settings: "+(0,o.errorToS)(e),ready:S}}}},14611:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartLibrary_=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(71567),o=i(34102),l=i(18454),u=i(28874),c=i(2858),d=i(64526),h=(0,r.lazy)((()=>(0,s.mkLogger)("library.RestartLibrary")));t.restartLibrary_=async function(e){if((0,n.isWebService)()&&a.StdoutWrite.shutdownSync(),e?.readSettings??1){for(const e of(0,u.persistedSettings)())e.unsetFileValue();await c.readSettings.refresh()}let t=Promise.resolve();h().warn("Shutting down prior library...");try{t=d.Library.endPriorInstance()}catch(e){h().warn("ending prior library failed:",{error:e})}(0,o.ee)().emit("clearCache"),null!=e?.libraryDir&&e.libraryDir!==u.Settings.libraryDir.valueOrDefault?u.Settings.libraryDir.value=e.libraryDir:u.Settings.libraryDir.broadcastChange(),l.HealthCheck.reset();const i=d.Library.instance();return t=t.then((()=>i?.ready)).then((()=>{})),(0,n.isWebService)()&&(t=t.then((async()=>{const e=await l.HealthCheck.awaitSettled();"ready"===e.state?a.StdoutWrite.restartSync():h().error("Restarted library, but health check summary was not ready",{summary:e})}))),{ready:t}}},18449:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(7282),s=i(96706),n=i(29325),a=i(28874);t.sentryEnabled=function(){return(0,s.isEnvTrue)("ENABLE_SENTRY")||(0,r.isProd)()&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},95629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(16436)),l=a(i(48161)),u=a(i(1708)),c=i(19851),d=i(19043),h=i(50213),f=i(31578),m=i(7282),p=i(96175),g=i(23560),y=i(84968),v=i(81168),w=i(37805),b=i(25764),S=i(38836),P=i(99331),_=i(85100),T=i(98314),M=i(68301),E=i(70025),k=i(8769),D=i(34102),x=i(34592),C=i(42042),A=i(34474),F=i(20839),I=i(57902),O=i(45969),L=i(43334),R=i(40958),N=i(22573),B=i(42659),j=i(41400),z=i(98553),V=i(55835),W=i(12168),U=i(59455),q=i(54993),H=i(18449),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,_.serviceExitTimeoutMs)(e.name),release:w.release,environment:(0,m.nodeEnv)(),maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,k.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(M.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await Z(e);return await(M.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,D.ee)().on("fatal",$),(0,D.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Y(e.exception?.values)),(0,T.errorToS)(t?.originalException)])).join(": ")}function Y(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(X))))}function X(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function Z(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,x.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*F.DefaultLogFlushMs);const e=await(0,A.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Y,t.sentryExceptionToS=X,t.annotateEvent=Z,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[I.LogLevels.fatal,"fatal"],[I.LogLevels.error,"error"],[I.LogLevels.warn,"warning"],[I.LogLevels.info,"info"],[I.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},37158:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const p=m(i(29907)),g=m(i(1708)),y=i(57206),v=i(19851),w=i(50213),b=i(59880),S=i(23560),P=i(19913),_=i(71567),T=i(37805),M=i(38836),E=i(99331),k=i(45608),D=i(56038),x=i(55534),C=i(42499),A=i(49776),F=i(96706),I=i(98314),O=i(38835),L=i(70025),R=i(8769),N=i(57159),B=i(34102),j=i(33456),z=i(87408),V=i(85021),W=i(17181),U=i(86941),q=i(28874),H=i(41692),G=i(2858),$=i(69385),J=i(22573),K=i(42659),Y=i(41400),X=i(56409),Z=i(55835),Q=i(41583),ee=i(54993),te=i(95629);t.setupEventHandlers=(0,v.lazy)((()=>{(0,B.ee)().on("resume",(()=>(0,$.resume)())),(0,B.ee)().on("pause",(()=>(0,$.pause)()))}));class ie extends M.EndableWrapper{constructor(e){super(e),r.add(this),s.set(this,void 0),n.set(this,new X.Latch),a.set(this,new Map),this.setup_=(0,v.lazy)((()=>(0,D.time)("Service.setup",(()=>f(this,r,"m",o).call(this))))),u.set(this,(0,v.lazy)((()=>{const e=g.default.stdin.pipe(new j.LineReader);return e.on("data",(e=>f(this,r,"m",d).call(this,(0,ee.toS)(e)))),e}))),(0,S.isBillingService)()||(0,H.setSettingsDefaults)(),h(this,s,(0,w.mkLogger)("Service("+this.name+")"),"f"),f(this,r,"m",c).call(this),this.setup_()}get name(){return super.name}get ready(){return f(this,n,"f").promise}get isReady(){return f(this,n,"f").isResolved()}setInputHandler(e,t){f(this,a,"f").set(e.trim().toLowerCase(),t)}}t.Service=ie,s=new WeakMap,n=new WeakMap,a=new WeakMap,u=new WeakMap,r=new WeakSet,o=async function(){try{(0,J.mapNotBlank)((0,F.getEnv)("PS_FATAL_"+this.name),(e=>{throw new N.WrappedError(e,{fatal:!0})})),(0,J.mapNotBlank)((0,F.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Y.later)((()=>{throw new N.WrappedError(e)}),5*K.secondMs)})),(0,P.setServiceName)(this.name),(0,b.setProcessTitle)(),(0,S.isMainService)()&&await(0,U.mergeUserDataDirs_)(),await(0,G.readSettings)(),await f(this,r,"m",l).call(this),(0,W.setupLogger)(),(0,y.addDefaultJsonRevivers)(),(0,A.cacheDir)(),(0,t.setupEventHandlers)(),f(this,u,"f").call(this),await(0,C.setupLuxon)(),q.Settings.startPaused.valueOrDefault&&(0,$.pause)(),(0,E.ending)()?f(this,n,"f").reject():f(this,n,"f").resolve()}catch(e){console.error((0,I.errorToS)(e)),f(this,n,"f").reject((0,Q.toErr)(e)),(0,k.exit)({reason:(0,L.addErrorFlags)(this.name+" setup failed: "+(0,I.errorToS)(e),O.FatalErrorFlag),status:14})}},l=async function(){(0,S.isPermaService)()||(0,B.ee)().on("fatal",(e=>(0,k.exit)({error:e,status:12}))),g.default.on("unhandledRejection",(e=>(0,Z.map)(e,(e=>(0,R.onError)("unhandledRejection",e))))),g.default.on("uncaughtException",(e=>(0,Z.map)(e,(e=>(0,R.onError)("uncaughtException",e))))),g.default.on("SIGINT",(()=>(0,k.exit)({reason:"SIGINT",status:0}))),g.default.on("SIGHUP",(()=>(0,k.exit)({reason:"SIGHUP",status:0}))),g.default.on("SIGTERM",(()=>(0,k.exit)({reason:"SIGTERM",status:0}))),p.default.isWorker&&g.default.on("disconnect",(()=>(0,k.exit)({reason:"disconnect",status:0}))),await(0,te.installSentry)(this)},c=function(){this.setInputHandler("--version",(()=>(0,_.stdoutWrite)({version:T.version}))),this.setInputHandler(x.ServiceExitCommand,(()=>(0,Y.later)((()=>(0,k.exit)({reason:x.ServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,_.stdoutWrite)(D.PromiseTimer.instance().report()))),this.setInputHandler(V.HealthCheckCommand,(async()=>(0,_.stdoutWrite)(await(0,z.getStatusSummary)({refresh:!0}))))},d=async function(e){if(f(this,s,"f").debug("onLine()",{line:e,ending:this.ended||(0,E.ending)()}),await this.setup_(),e.startsWith("--")){const t=e.split(/\s+/,1)[0],i=f(this,a,"f").get(t);null==i?(f(this,s,"f").error("onLine(): unknown command",{line:e,knownCommands:[...f(this,a,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else f(this,s,"f").error("onLine(): failed to process",{line:e})}},53791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shutdown=void 0;const r=i(19851),s=i(50213),n=i(71567),a=i(99331),o=i(45608),l=i(65812);let u="unspecified";t.shutdown=function(e){return(0,s.mkLogger)("Shutdown").warn("shutdown()",{reason:e}),u=e,c()};const c=(0,r.lazy)((async()=>{n.StdoutWrite.shutdown(),(0,l.setUnrefTimeout)((()=>(0,a.ending)()?void 0:(0,o.exit)({reason:u,status:0})),3e3)}))},57064:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t._suggestedLibraryDirs=t.suggestedLibraryDirs=t.SuggestedLibraryDir=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(72993),o=i(19851),l=i(50213),u=i(7282),c=i(45255),d=i(81168),h=i(5916),f=i(56519),m=i(32551),p=i(48195),g=i(55939),y=i(44198),v=i(64660),w=i(83278),b=i(92423),S=i(29882),P=i(65238),_=i(16287),T=i(45969),M=i(28874),E=i(7014),k=i(40958),D=i(76790),x=i(22573),C=i(31586),A=i(13538),F=i(12168),I=(0,o.lazy)((()=>(0,l.mkLogger)("library.SuggestedLibraryDir")));class O{static async for(e,t){if((0,x.blank)(e))return;const i=await(0,E.bestVolumeForPath)(e,t);if(null==i)return void I().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:e});const r=await(0,p.isLibraryDir)(e);return new O(e,r,i)}constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=M.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=M.Settings.minDiskFreeGb.valueOrDefault*F.GB){if(this.isLibrary)return;const t=await(0,_.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,S.containsHiddenPathname)(this.nativePath))return I().tap({...i,result:"contains hidden path"});{const e=await(0,b.whyExcludedDirectoryRecursive)(w.BaseFile.for(this.nativePath));if(null!=e)return I().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,v.canRWXFirstExistingAncestor)(this.nativePath)?(0,C.gt0)(e)&&this.availableBytesnew O(e,!1,{mountpoint:"/test",available:F.GB})))});const l=[],d=[],h=await(0,A.thenOrTimeoutMaybe)(i,M.Settings.statTimeoutMs.valueOrDefault)??await(0,A.thenOrTimeoutMaybe)((0,E.volumes)(),M.Settings.statTimeoutMs.valueOrDefault);if(null==h||(0,k.isEmpty)(h))return I().warn("volumes() is empty: they don't get any suggestions."),[];async function v(t){const i=await O.for(t,h);if(null!=i)return i.isLibrary||i.isCurrentLibrary?(I().info("addSuggestion(): path is a library",i),void l.push(i)):void(null==await i.whyExcluded(e)&&d.push(i))}if(await v(M.Settings.libraryDir.value),(0,T.isDocker)())return[...l,...d];await v(await(0,g.picturesDir)());const w=[n.default.cwd(),...await(0,P.childDirectories_)(n.default.cwd())];(0,T.isDocker)()||w.push(...await(0,P.childDirectories_)((0,m.homeDir)())),(0,k.filterInPlace)(w,(e=>(0,S.isNotHiddenPosixPath)(e)));for(const e of w)await(0,p.isLibraryDir)(e)&&(I().info("current working dir is a library",e),await v(e));function b(){return Date.now()-r>c.ShortCommandTimeoutMs-500&&(I().debug("...ran out of time, stopping."),!0)}(0,T.isDocker)()||await v(s.default.join((0,m.homeDir)(),(0,a.AppName)())),await(0,f.mapAsync)({name:"suggestedLibraryDirs.addVolume",arr:h,f:e=>async function(e){try{if(await(0,p.isLibraryDir)(e.mountpoint))return I().info("addVolume(): vol.mountpoint is a library",e.mountpoint),void await v(e.mountpoint);for(const t of await(0,P.childDirectories_)(e.mountpoint)){if(b())break;if(await(0,p.isLibraryDir)(t))I().info("addVolume(): dir is a library",t),await v(e.mountpoint);else for(const i of await(0,P.childDirectories_)(t)){if(b())break;await(0,p.isLibraryDir)(i)&&(I().info("addVolume(): dir is a library",t),await v(e.mountpoint))}}const t=s.default.join(e.mountpoint,(0,a.AppName)());I().info("addVolume(): adding default suggestion",t),await v(t)}catch(t){I().warn("addVolume(): Failed to add suggestion",{err:t,vol:e})}}(e),timeoutMs:c.ShortCommandTimeoutMs}),I().debug("Finished gathering suggestions. Filtering...",{priorLibraries:l,suggestions:d});const _=l;for(const e of(0,D.sortBy)(d,(e=>[-e.availableBytes,-e.nativePath.length]))){if(_.length>=t)break;_.some((t=>t.nativePath===e.nativePath||t.mountpoint===e.mountpoint))||(I().debug("adding new path",e),_.push(e))}return(0,k.uniqBy)((0,D.sortBy)(_,(e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath])),(e=>e.nativePath))}t.SuggestedLibraryDir=O,t.suggestedLibraryDirs=(0,h.lazyAsync)({desc:"library.suggestedLibraryDirs",later:()=>L()}),t._suggestedLibraryDirs=L},77948:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemInformation=t.libraryMetrics=void 0;const r=i(21330),s=i(46296),n=i(17344),a=i(18454),o=i(81674),l=i(66184),u=i(96175),c=i(24540),d=i(23560),h=i(28874),f=i(2858),m=i(84968),p=i(94174),g=i(37805),y=i(14854),v=i(15674),w=i(40958),b=i(22573),S=i(38639),P=i(75240),_=i(55835),T=i(31586),M=i(20214),E=i(51926),k=i(12168),D=i(43487),x=i(54017),C=i(48723);async function A(){if(null==D.Asset.db())return;const e=[];e.push((0,k.plurMetric)(D.Asset.shownCount(),"asset"));const t=x.AssetFile.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,E.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,k.plurMetric)(i.assetFileCount,t+" file"))}return e.push((0,k.plurMetric)(C.Tag.rows(),"tag")),e}t.libraryMetrics=A;const F={pending:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"};t.systemInformation=async function(){const e=await(0,o.b)(),t=e?.l?.tier??"lite",i=a.HealthCheck.summary();return(0,w.compact)([{term:"Version",defn:g.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:F[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,S.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,_.mapOr)(e?.l?.exp,(e=>(0,r.toIsoDate)(e)),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,u.osFullName)()},{term:"CPUs",defn:(0,u.CPUs)()},{term:"System load",defn:(0,_.map)(y.CpuUsage.instance().busyPct(),(e=>(0,T.fmtPct)(e)+" busy"))??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(h.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,v.maxConcurrentImports)()} concurrent imports, ${(0,v.sharpThreadsPerProcess)()} gfx/process)`},(0,d.isWebService)()?{term:"Web uptime",defn:(0,P.fmtDuration)((0,m.runtimeMs)())}:void 0,(0,b.mapNotBlank)((0,c.procDeviceModel)(),(e=>({term:"Device",defn:e}))),{term:"Current user",defn:await(0,p.username)()+((0,T.gte0)((0,p.userid)())?"":" (userid: "+(0,p.userid)()+", groupid: "+(0,p.groupid)()+")")},(0,f.libraryHasSettings)()?{term:"Library path",defn:h.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,await(0,M.thenMap)(A(),(e=>({term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:e}))),{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,l.defaultLogLevel)()}]).filter((({term:e,defn:t})=>(0,b.notBlank)(e)&&(0,b.notBlank)(t)))}},35580:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TaskList=t.TaskListRunLaterMs=void 0;const w=i(19851),b=i(7282),S=i(23560),P=i(88264),_=i(73568),T=i(78406),M=i(25764),E=i(99331),k=i(56038),D=i(42638),x=i(34102),C=i(70417),A=i(28874),F=i(14854),I=i(73328),O=i(69385),L=i(15674),R=i(40958),N=i(42659),B=i(45599),j=i(26905),z=i(56409),V=i(31586),W=i(94710);t.TaskListRunLaterMs=8;class U extends T.EndableInterval{constructor(){const e="TaskList()";super({name:e,callback:()=>this.maybeRunChunk(),intervalMs:7*N.secondMs,onEnd:()=>v(this,r,"m",a).call(this),rank:M.EndableRanks.first,endTimeoutMs:A.Settings.taskTimeoutMs.valueOrDefault}),r.add(this),this.recentlyProcessed=new P.TTLArray(N.minuteMs),s.set(this,[]),this.taskCount=(0,w.lazy)((()=>W.Task.count())),d.set(this,(0,w.lazy)((()=>{this.logger.debug("status",this.state())}),((0,b.isTest)()?1:30)*N.secondMs)),f.set(this,(()=>this.maybeRunChunk())),m.set(this,(0,w.lazy)((()=>this.logger.info("runChunk(): no-op",{isPaused:(0,O.isPaused)(),isFull:this.p.isFull(),isTooBusy:(0,F.isTooBusy)(),whyDoNotRun:(0,I.whyDoNotRun)(this),pendingWorkCount:this.pendingWorkCount(),queueItemCount:this.taskCount(),freeSlots:this.p.freeSlots()})),((0,b.isTest)()?1:30)*N.secondMs)),this.maybeRunChunk=(0,w.lazy)((()=>{setTimeout((()=>{this.ended||(0,E.ending)()||(v(this,r,"m",g).call(this),this.maybeRunChunk.unset())}),t.TaskListRunLaterMs)})),p.set(this,(0,w.lazy)((()=>{const e=A.Settings.minBusyPct.valueOrDefault,t=A.Settings.stuckCheckIntervalMs.valueOrDefault;if(e<=0||this.p.isIdle()||t<=0)return;const i=F.CpuUsage.instance().busyPct();if(this.logger.debug("maybeCheckForStuckTasks()",{cpuBusyPct:i,minBusyPct:e,stuckCheckIntervalMs:t}),!(0,V.gte)(i,e))for(const e of this.p.running)if(e.elapsedMs>t){const t=e.payload;this.logger.error("Stuck serial task. Aborting.",{task:t,elapsedMs:e.elapsedMs});const i="stuck after "+e.elapsedMs+"ms";t.abort(i),e.reject(new _.AbortError(i))}}),A.Settings.stuckCheckIntervalMs.valueOrDefault)),this.p=new D.Promises(e,L.maxConcurrentImports),this.p.ee.on("vacancy",this.maybeRunChunk),this.p.ee.on("drain",(()=>v(this,r,"m",l).call(this))),(0,x.ee)().on("resume",v(this,f,"f")),W.Task.ee.on("added",this.maybeRunChunk)}async awaitDrain(e=[],t=0){(0,R.isEmpty)(e)&&(e=W.TaskNames.values);const i=new z.Latch;return v(this,s,"f").push({l:i,taskNames:e,maxRemaining:t,who:(0,j.shortStack)()}),this.maybeRunChunk(),i}isRunnable(){return!this.p.isFull()}currentWorkCount(){return this.p.unsettledCount()}pendingWorkCount(){return this.taskCount()-this.currentWorkCount()}hasCapacity(e=A.Settings.taskListCap.valueOrDefault){return e<=0||this.taskCount()e.payload))}currentTasksByFn(e){return this.currentTasks().filter((t=>t.fn===e))}state(){return{...this.p.stats(),isDone:v(this,r,"m",l).call(this),freeSlots:this.p.freeSlots(),pendingWork:this.taskCount(),next10:v(this,r,"m",h).call(this,10).map((e=>e.toString())),recentlyProcessedLast10:this.recentlyProcessed.slice(-10).map((e=>e.toString())),isRunnable:this.isRunnable()}}doNotStartMoreWork(){return(0,E.ending)()||this.ended||(0,O.isPaused)()||this.p.isFull()||(0,F.isTooBusy)()||(0,I.doNotRun)(this)||0===this.pendingWorkCount()}}t.TaskList=U,s=new WeakMap,d=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,r=new WeakSet,n=function(){this.taskCount.unset()},a=async function(){(0,x.ee)().off("resume",v(this,f,"f"));const e=new _.AbortError((0,E.ending)()?"service ending":"TaskList ended");for(const t of v(this,s,"f"))t.l.reject(e);await this.p.awaitAll()},o=function(){(0,R.filterInPlace)(v(this,s,"f"),(e=>e.l.isPending())),W.Task.dbl.runf((e=>e.delete().where("retries","<",0))),v(this,r,"m",n).call(this)},l=function(){if(this.ended)return;if(v(this,r,"m",o).call(this),(0,R.isEmpty)(v(this,s,"f")))return;const e=W.Task.countTaskNames();for(const t of this.p.deferreds){const i=t.name;e[i]=(e[i]??0)+1}for(const t of v(this,s,"f"))(0,C.sum)(t.taskNames.map((t=>e[t]??0)))<=t.maxRemaining&&t.l.resolve()},u=function(){return(0,R.uniq)(this.currentTasks().filter((e=>e.isSerial)).map((e=>e.fn)))},c=function(){return this.currentTasks().map((e=>e.id))},h=function(e){return 0===e?[]:W.Task.ops().allf((t=>(t=W.Task.orderBy(t.distinct().whereNotIn("id",v(this,r,"m",c).call(this)).whereNotIn("fn",v(this,r,"m",u).call(this))),(0,V.gt0)(e)&&(t=t.limit(e)),t)))},g=function(){if(v(this,r,"m",n).call(this),v(this,p,"f").call(this),this.doNotStartMoreWork())v(this,m,"f").call(this);else{v(this,d,"f").call(this);const e=this.p.freeSlots(),t=v(this,r,"m",h).call(this,e);this.logger.debug("runChunk():",{freeSlots:e,next:t});for(const e of t)this.p.enqueue({name:this.name,payload:e,l:()=>v(this,r,"m",y).call(this,e),serialId:e.isSerial?e.fn:void 0})}v(this,r,"m",l).call(this)},y=async function(e){try{await(0,k.time)("task."+e.fn,e._run())}catch(t){this.logger.warn("Failed to run task",{task:e,error:t})}finally{this.maybeRunChunk()}},U.instance=(0,B.defer)((()=>(0,S.isTaskListManager)()?new U:void 0))},98392:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExposeArg=void 0;const r=i(28874),s=i(38639);t.ExposeArg={beforeParse:e=>e.option("--expose","The web service is only accessible to the computer running PhotoStructure by default. Providing this option will expose your library to all computers on your network. See https://photostructure.com/faq/remote-access/ ."),afterParse:e=>{(0,s.isTrue)(e.expose)&&(r.Settings.exposeNetworkWithoutAuth.envValue=!0)}}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},46628:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(47783),c=i(97573),d=i(42231),h=i(40958),f=i(22573),m=i(68708),p=i(75020),g=i(54993),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function v(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(v));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w},88224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(28874),o=i(42231),l=i(40958),u=i(20214),c=i(43487),d=i(46628),h=i(63175),f=i(4407),m=i(58886),p=i(32646),g=i(48144),y=i(60047),v=i(6186),w=i(42003),b=i(43723),S=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function P({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];if(t=(0,l.uniqBy)([e,...t],(e=>e.nativePath)),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,y.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),a.Settings.tagGeo.valueOrDefault)for(const e of t){const t=await(0,p.geoTagFile)(e);if(null!=t){u.push(t);break}}await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,b.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,g.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,w.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{S().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const P=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(v.normalizeTagRoot),o.joinTagPath)),_=await(0,v.tagDeltas)(i,P);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:P,result:_}),_}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await P({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=P},63175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(47783),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},4407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(47783),h=i(40958),f=i(55835),m=i(31586),p=i(75020),g=i(54993),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function _(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function T(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function M(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),_);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),T);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=_,t.dayTagRef=T,t.dateTag=M,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:M(r.date)}},58886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(19851),s=i(50213),n=i(42231),a=i(21404),o=i(40958),l=i(89937),u=i(75020),c=i(54017),d=i(94448),h=i(69032),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},32646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTagFile=t.geoTag=void 0;const r=i(48884),s=i(56519),n=i(50213),a=i(28874),o=i(47783),l=i(14245),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)((()=>(0,n.mkLogger)("curators.GeoTagger")));function p(e){const t=a.Settings.tagGeoMaxDistanceKm.valueOrDefault;if(t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t))return void m().warn("geoTag(): GeolocationDistance too large, skipping geo tag",(0,f.pickDeep)(e,...l.GeolocationFields));const i=a.Settings.tagGeoSynonyms.synonymMap(),s=a.Settings.tagGeoTemplate.valueOrDefault.map((t=>(0,r.first)(i.get(t)??[t],(t=>(0,f.pluckDeep)(e,t)?.value)))),n=(0,c.compactBlanks)(s);return m().tap({msg:"geoTag",result:0===n.length?void 0:(0,c.compact)([u.TagRoots.Where,...n]),meta:{picked:s}})}t.geoTag=p,t.geoTagFile=function(e){return(0,s.thenMap)((0,o.readTags)(e),p)}},48144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(47783),h=i(97573),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),v=i(96249),w=i(55835),b=i(75020),S=i(54993),P=i(6186),_=i(43723),T=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),M=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return T().tap({msg:"extractDashDashTags()",result:(0,w.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,w.mapOr)(M(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function k(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>M.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=k;const D=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(D,(e=>(i.push(e),"")));s.push(...(0,w.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function A(e,t){const[i,s]=(0,r.partition)(x(e),_.isWhoTag),n=(0,v.flatten)(i.map(_.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return T().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=C,t.processKeywords=A,t.keywordTagFiles=async function(e,t){return A([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(k)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},60047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(56519),s=i(28874),n=i(47783),a=i(75020),o=i(40958),l=i(22573),u=i(55835);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},6186:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhereRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(50213),s=i(28874),n=i(42231),a=i(75020),o=i(40958),l=i(22573),u=i(45599);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.WhereRoot={name:a.TagRoots.Where,ordinal:5},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,t.WhereRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Where,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase()))),g=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhereRoot,...e.slice(1)]:g.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},42003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}t.friendlySubtype=y,t.fixCase=v},43723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(19851),s=i(50213),n=i(28874),a=i(47783),o=i(28630),l=i(66039),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(w)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function v(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function w(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=v,t.nameTag=w},98348:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(48884),d=i(19851),h=i(23560),f=i(25764),m=i(38836),p=i(99331),g=i(5916),y=i(12959),v=i(55332),w=i(91872),b=i(80632),S=i(51040),P=i(44955),_=i(15056),T=i(70025),M=i(57159),E=i(18454),k=i(28874),D=i(5233),x=i(42659),C=i(31586),A=i(68708),F=i(30976),I=i(17036),O=i(27134),L=i(35052);class R extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=x.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),k.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*x.secondMs),this.migrate_=(0,g.lazyAsync)({desc:"db.migrate",later:async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{await(0,O.verifyDb_)((()=>this.db))}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||k.Settings.dbForceRecover.valueOrDefault)&&(E.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new I.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e}}}),this.tableInfo_=(0,d.lazy)((()=>(0,L.localTableInfo)(this.db)))}toJSON(){return(0,A.pick)(this,"schema","dbFile")}get isOpen(){return!0===l(this,n,"f")?.open}get inTransaction(){return this.isOpen&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(t||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,b.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===k.Settings.dbAutoVacuumMode.valueOrDefault&&(0,C.gt0)(k.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%k.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&(this.logger.info("running incremental_vacuum..."),l(this,n,"f")?.pragma("incremental_vacuum")),l(this,n,"f")}async verify_(){await(0,O.verifyDb_)((()=>this.db))}assertHeartbeat_(){const e=(0,F.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{this.logger.info("closing db",l(this,n,"f")),await(0,D.retryOnReject_)((()=>{!0===l(this,n,"f")?.open&&l(this,n,"f")?.close()}),{timeoutMs:k.Settings.dbBusyTimeoutMs.valueOrDefault,maxRetries:5,errorIsRetriable:T.isSqliteBusyError,retryDelay:x.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,w.handleDbRetries_)("db.checkpoint",(()=>this.db),(()=>(0,O.checkpoint_)({db:this.db})),this.onRetry),await(0,w.handleDbRetries_)("db.optimize",(()=>this.db),(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,w.handleDbRetries_)("db.vacuum",(()=>this.db),(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,O.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,_.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,P.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,y.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,v.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=R,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,C.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},25470:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(66364),d=i(50213),h=i(23560),f=i(78406),m=i(25764),p=i(38836),g=i(99331),y=i(56038),v=i(12959),w=i(55332),b=i(76187),S=i(73209),P=i(28874),_=i(42659),T=i(75240),M=i(95700),E=i(22526),k=i(45648),D=5*_.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends f.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:_.minuteMs,rank:m.EndableRanks.db,endTimeoutMs:5*_.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new p.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),m.EndableRanks.postdb,D),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*_.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,k.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,k.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,M.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,y.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,v.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,w.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,T.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:D,endableRank:m.EndableRanks.postdb,noopIfContested:!1});(0,h.isDbManager)()&&await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,b.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),await this.db.closeDb()},o=function(){return this.ended||(0,g.ending)()||(0,c.isSuspended)()}},35758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelRepair=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(71567),o=i(98314),l=i(38835),u=i(18454),c=i(28874),d=i(63870),h=i(64526),f=i(14611),m=i(74085),p=i(22526),g=i(45648),y=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelRepair")));t.dbModelRepair=async function(){return{...await async function(){const e=h.Library.instance();if(null==e)throw new Error("No library set."+l.NoLibraryErrorFlag);const t=await e.dbModelJanitor();if(null==t)throw new Error("No library set (missing dbModelJanitor)."+l.NoLibraryErrorFlag);(0,g.clearDbSetupErrors)();const i=await(0,m.dbModelHealthCheck)().refresh();if(y().info("dbModelRepair: health check result: ",i),c.Settings.dbForceRecover.valueOrDefault)u.HealthCheck.addLoadingMsg("PS_DB_FORCE_REPAIR was set. Trying to repair.");else if("ok"!==i.level)u.HealthCheck.addLoadingMsg(`Database health check failed: ${i.msg}. Trying to repair.`),c.Settings.dbForceRecover.envValue=!0;else try{return u.HealthCheck.addLoadingMsg("Backing up the library database..."),await t.forceBackup_(),u.HealthCheck.addLoadingMsg("Validating the library database..."),await t.db.verify_(),u.HealthCheck.addLoadingMsg("No repair needed: maintenance tasks, backup, and integrity tests ran without error."),y().tap({msg:"dbModelRepair()",level:"info",result:{noop:!0,op:"validated"}})}catch(e){u.HealthCheck.addLoadingMsg(`Maintenance, backup, or integrity tasks failed: ${(0,o.errorToS)(e)}. Trying to repair.`),c.Settings.dbForceRecover.envValue=!0}(0,n.isWebService)()&&a.StdoutWrite.shutdownSync();const r=await e.dbFsLock();if(!await r.acquire_({timeoutMs:2*(0,d.commandTimeoutMs)(),releaseOnFailure:!1}))return y().throw("Failed to acquire exclusive lock on the library database. Shut down other processes before retrying.");try{await(0,p.assertValidDbInfo_)()}catch(e){u.HealthCheck.addLoadingMsg(`Library database setup was invalid: ${(0,o.errorToS)(e)}. Resetting and restarting.`),await(0,p.libraryDbInfoJsonFile)().unlink(),c.Settings.dbForceRecover.envValue=!0}await(0,f.restartLibrary_)();const s=c.Settings.dbForceRecover.valueOrDefault;return c.Settings.dbForceRecover.unset(),y().tap({msg:"dbModelRepair()",level:"info",result:{op:s?"repaired":"restarted",noop:!1}})}(),state:(await u.HealthCheck.rerunSetup()).state}}},22526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(19851),s=i(50213),n=i(92407),a=i(55332),o=i(44955),l=i(15056),u=i(87290),c=i(98314),d=i(38835),h=i(73209),f=i(95696),m=i(17217),p=i(18454),g=i(57902),y=i(28874),v=i(2858),w=i(40958),b=i(22573),S=i(42659),P=i(94448),_=i(98348),T=i(45648),M=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function k(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function D(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=D(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw M().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,T.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=k,t.libraryDbInfoJsonFile=D,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:k(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new _.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>M().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new _.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return M().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,T.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw M().error("Failed to set up model db",{error:e}),(0,T.addDbSetupError)(e),i.release(),e}return M().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},86859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(54557),s=i(50213),n=i(99331),a=i(56038),o=i(65753),l=i(66184),u=i(70417),c=i(28874),d=i(40958),h=i(22573),f=i(45599),m=i(96249),p=i(31586),g=i(51926),y=i(57038),v=i(21074),w=(0,f.defer)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,y.knex)()(this.tableName)}prep(e,t=!1){const i=(0,v.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return w().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&w().log((0,l.defaultLogLevel)(),i+"(): "+(0,v.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;w().throw(t,{method:i,...(0,v.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,a.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,g.replaceAll)((0,g.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,v.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,m.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}async batched(e){let t,i=0;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,o.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&(await e.onResults(t),i+=t.length)}while((0,d.isNotEmpty)(t)&&!(0,n.ending)()&&(null==e.maxResults||e.maxResults>i));return{resultCount:i,done:null==t||t.length<(0,o.maxBatchPluckSize)()}}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}async pluckBatched(e){let t=0;const i=(0,u.min)([e.limit??(0,o.maxBatchPluckSize)(),e.maxResults]);if(i<=0||(0,p.lte0)(e.maxResults))return{done:!1,resultCount:t};let r;for(;null==e.maxResults||e.maxResults<=0||t(0,o.mkLogger)("db.DbSchemaValid")));function y(e){return l.PosixFile.for(s.default.join(u.ProjectPath.Data(),e+"-schema.json"))}t.schemaJsonFile=y,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,p.localTableInfo)(e.db),i=t.map((e=>e.tableName)),r=(await y(e.schema).readJson_()).tableInfo;{const e=r.map((e=>e.tableName)),t=(0,c.diff)(e,i);(0,c.isNotEmpty)(t)&&g().throw("Db is missing "+(0,f.plur)(t.length,"table")+": "+(0,h.andList)(t))}for(const e of t){const t=r.find((t=>t.tableName===e.tableName));if(null==t)g().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,c.isNotEmpty)(i)&&g().throw("Db is missing "+(0,f.plur)(i.length,"column")+" from table "+e.tableName+": "+(0,h.andList)(i.map((e=>e.name))))}}g().info("Validated schema.",{from:(0,d.shortStack)()})}catch(e){throw(0,m.dbModelHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return y(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",tableInfo:(0,p.localTableInfo)(t)},{spaces:2})}},45648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},36908:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(42231),o=i(40958),l=i(76790),u=i(23838),c=i(31586),d=i(54993),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},57038:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(31832)),n=i(19851),a=i(56519),o=i(55835),l=i(68708);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},17036:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(77598),l=i(19851),u=i(50213),c=i(7282),d=i(37805),h=i(4867),f=i(51040),m=i(77740),p=i(38835),g=i(8769),y=i(57159),v=i(34102),w=i(73209),b=i(95696),S=i(43899),P=i(18454),_=i(28874),T=i(40958),M=i(42659),E=i(41400),k=i(98553),D=i(55835),x=i(34666),C=i(32639),A=i(45648),F=i(94715),I=i(27134);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,F.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,T.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,k.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:_.Settings.dbMaintenanceTimeoutMs.valueOrDefault},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=F.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(F.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.info("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),(0,c.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{if((0,m.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(M.secondMs,3*M.secondMs)),await(0,D.map)(e,(e=>e(r))),await(0,h.thenOrTimeoutError)({p:this.applyMigration_(r,i),timeoutMs:5*_.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch((e=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,A.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile(),r=(0,f.splitBatchSql)(i);if((0,T.isEmpty)(r))this.logger.info("No-op migration: "+e);else{t&&this.db.pragma("foreign_keys = OFF");for(const t of r)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,I.foreignKeyCheck_)(this.db)}}finally{t&&this.db.pragma("foreign_keys = ON")}}},94715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(97352),o=i(68852),l=i(81168),u=i(85810),c=i(42022),d=i(1971),h=i(79842),f=i(89724),m=i(17415),p=i(88600),g=i(20014),y=i(42231),v=i(87001),w=i(40958),b=i(55835),S=i(31586),P=i(97790),_=i(89937),T=i(54993),M=i(7656),E=i(36908),k=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),D=new RegExp(`^(${(0,o.escapeRegExp)(_.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function A(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())k().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>D.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=A,t.isoToPrecisionMs=F,t.Migrations={fix_root_tags:A,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,T.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();k().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));k().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:M.rebuildTagAssetCounts,create_tag_fts:e=>{e.exec("DROP TABLE IF EXISTS tag_fts"),e.exec("CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize=\"unicode61\");")},rebuild_null_island:e=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,y.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")}}},27134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(14121),s=i(19851),n=i(50213),a=i(84777),o=i(12959),l=i(5531),u=i(91872),c=i(99315),d=i(76187),h=i(51040),f=i(38835),m=i(57159),p=i(29882),g=i(95696),y=i(89966),v=i(38156),w=i(28874),b=i(63870),S=i(5233),P=i(42659),_=i(41400),T=i(50357),M=i(98553),E=i(56409),k=i(31586),D=i(20214),x=i(51926),C=i(12168),A=i(59455),F=i(54993),I=i(94448),O=i(9508),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){L().debug("pragmaOrThrow_()",{db:N(e),db_open:e?.open,pragma:t,okResult:i});const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,T.eql)(r,i)||L().throw(`${t} failed for ${N(e)}: ${(0,M.stringify)({result:r})}`)}function N(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}function B(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function j(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function z(e){const t=(0,A.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function V(e){await(0,u.handleDbRetries_)("db.quickCheck",e,B),await(0,_.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",e,j),await(0,_.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",e,z)}function W(e){return(0,O.withDbSync)(e,V,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,A.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,k.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,I.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=B,t.integrityCheck_=j,t.foreignKeyCheck_=z,t.verifyDb_=V,t.verifyDbFile_=W,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,A.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,k.gt0)(n?.busy)&&i>0?(await(0,_.delay)(250),e({db:t,retries:i-1})):n};const U=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,F.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,F.toS)(e);U.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),await W(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,D.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,D.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},21074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(48884),s=i(68852),n=i(81168),a=i(12943),o=i(96249),l=i(98553),u=i(31586),c=i(68708),d=i(32639),h=i(54993);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},35052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(22573),s=i(23838);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},9508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(80632),s=i(28874),n=i(30301),a=i(54993);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)((()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i})));try{return t((function(){const e=o();return e.open?e:o.refresh()}))}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const n=(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i});try{return await t(n)}finally{n.close()}}},74085:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelHealthCheck=void 0;const r=i(77740),s=i(98314),n=i(18454),a=i(28874),o=i(82950),l=i(42659),u=i(45599),c=i(64526),d=i(16185),h=i(45648),f=i(31687),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.dbModelHealthCheck=(0,u.defer)((()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library database…",settings:["libraryDir","forceLocalDbReplica"],timeoutMs:()=>10*a.Settings.dbMaintenanceTimeoutMs.valueOrDefault,ttlMs:l.minuteMs,onReset:()=>(0,h.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837"}],later:async()=>{const e=await(c.Library.instance()?.ready);if(null==e)return{level:"disabled",msg:["Library database tests disabled: no library is open"]};let t,i=!1;try{const s=Date.now();if(i=!1,(0,h.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,o.li)((0,h.dbSetupErrors)())],links:[m]};if(t=await e.modelDb(),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await(0,d.assertValidDbSchema_)(t),i=!0,await t.verify_(),await t.vacuum(),f.Heartbeat.assertPing_();const n=await e.dbModelSetup_();return{level:"ok",msg:["Library database is OK",(0,o.li)(["Schema validation, vacuum, optimize, and upsert round-trip took "+(Date.now()-s)+"ms","Live db is "+(0,o.tt)(t.dbFile.nativePath),"Local replica mode is "+(0,o.tt)(n.useReplica),n.useReplica?"Cold library db is "+(0,o.tt)(n.libraryDbFile):void 0])]}}catch(r){return{level:"error",msg:["Library database validation failed",(i?"":"Unrecoverable: ")+(0,s.errorToS)(r),null==t?void 0:"Live db is "+(0,o.tt)(t.dbFile.nativePath),null==e?void 0:"Local replica mode is "+(0,o.tt)(await e.useReplica())],links:i?[m]:void 0}}}});return(0,h.addDbSetupErrorListener)((()=>e.refresh())),e}))},8400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(19851),s=i(88625),n=i(2858),a=i(74085),o=i(1991),l=i(40549);t.libraryHealthCheckSetup=(0,r.lazy)((async()=>{await(0,n.readSettings)(),(0,s.healthCheckSetup)(),(0,o.syncHealthCheck)(),(0,a.dbModelHealthCheck)(),(0,l.volumeUuidHealthCheck)()}))},1991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncHealthCheck=void 0;const r=i(48884),s=i(50213),n=i(95696),a=i(62105),o=i(18454),l=i(2858),u=i(40958),c=i(82950),d=i(45599),h=i(94019),f=(0,d.defer)((()=>(0,s.mkLogger)("health.SyncHealthCheck")));t.syncHealthCheck=(0,d.defer)((()=>o.HealthCheck.for({section:"Library",id:"library-nothing-to-sync",ordinal:99,settings:["scanAllDrives","scanPaths","scanLibraryFirst","scanLibraryLast"],pendingMsg:"Checking synced directories…",later:async()=>{if(!(0,l.libraryHasSettings)())return{level:"disabled",msg:"Library sync paths test disabled: no library is open"};const e=(await(0,h.pathsToSync)()).map((e=>e.nativePath));if((0,u.isEmpty)(e))return{level:"warn",msg:"No paths are configured to scan\n"+(0,c.li)([(0,c.tt)("PS_SCAN_ALL_DRIVES")+" is false",(0,c.tt)("PS_SCAN_PATHS")+" is empty","both "+(0,c.tt)("PS_SCAN_LIBRARY_FIRST")+" and "+(0,c.tt)("PS_SCAN_LIBRARY_LAST")+" are false"]),links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]};{const t=e.map((e=>n.PosixFile.for(e)));return f().info("Checking if any paths are empty",{posixFiles:t}),null==await(0,r.findAsync)(t,(async e=>null!=await e.someDescendant((e=>e.isDirectorySync()||(0,a.acceptParentAndFileAndSimple)(e)),1)))?{level:"warn",msg:["No eligible files found in scanned paths","Checked paths:",(0,c.li)(e.map(c.tt))],links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]}:{level:"ok",msg:["At least one directory with eligible files is configured to be synced","Checked paths:",(0,c.li)(e.map(c.tt))]}}}})))},40549:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=void 0;const r=i(50213),s=i(56519),n=i(18454),a=i(28874),o=i(2858),l=i(85087),u=i(63870),c=i(86848),d=i(7014),h=i(40958),f=i(82950),m=i(45599),p=i(57924),g=i(23838),y=i(68708),v=i(94019),w=(0,m.defer)((()=>(0,r.mkLogger)("health.VolumeUUIDHealthCheck")));t.volumeUuidHealthCheck=(0,m.defer)((()=>n.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumes…",settings:["scanAllDrives"],links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],later:async()=>{if(!(0,o.libraryHasSettings)())return{level:"disabled",msg:"Volume UUID test disabled: no library is open"};const e=[],t=[];if(a.Settings.scanAllDrives.valueOrDefault)e.push(...await(0,d.volumes)());else{const i=await(0,v.scanPaths)(),r=await(0,s.mapAsyncSerial)({name:"scannedVolumes",arr:i.result.map((e=>e.nativePath)),f:e=>(0,d.bestVolumeForPath)(e),timeoutMs:(0,u.commandTimeoutMs)()});e.push(...(0,h.uniqBy)(r,(e=>e.mountpoint))),t.push(...i.noUriPaths)}const i=[...(0,g.groupBy)(e,(e=>e.uuid)).values()].filter((e=>e.length>1)),r=e.filter((e=>null==e.uuid&&!(0,c.volumeUuidNotExpected)(e))).map((e=>e.mountpoint)),n=(await(0,d.volumes)()).filter((e=>!1===e.ok)).map((e=>(0,h.compactBlanks)([e.mountpoint,e.status]).join(": ")));if(w().debug("volumeHealthCheck result",{missingUUIDs:r,noUriPaths:t,unhealthyVolumes:n,scannedVolumes:e.map((e=>(0,y.pick)(e,"uuid","mountpoint")))}),(0,h.isEmpty)(r)&&(0,h.isEmpty)(i)&&(0,h.isEmpty)(t)&&(0,h.isEmpty)(n))return(0,h.isEmpty)(e)?{msg:["No volumes need UUIDs",(0,f.tt)(a.Settings.scanAllDrives.key)+" is false, and no volumes other than the library are configured to be scanned."],level:"ok"}:{msg:["All scanned volume UUIDs are OK",(0,f.li)(e.map((e=>(0,f.tt)((0,l.volsha)(e.uuid)+" → "+e.mountpoint))))],level:"ok"};{const e=[];return(0,h.isEmpty)(n)||e.push("Some volumes are unhealthy",(0,f.li)(n.map((e=>(0,f.tt)(e))))+"PhotoStructure may crash or hang when accessing unhealthy volumes."),(0,h.isEmpty)(r)||e.push("Some volumes are missing UUIDs",(0,f.li)(r.map((e=>(0,f.tt)(e)))),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(i)||e.push("Some volumes have duplicate UUIDs",i.map((e=>(0,f.li)((0,p.andList)(e.map((e=>(0,f.tt)(e.mountpoint))))+" share UUID "+(0,f.tt)(e[0].uuid)))).join("\n---\n"),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(t)||e.push("Some paths failed to have URIs generated",(0,f.li)(t.map((e=>(0,f.tt)(e)))),"This will prevent these paths from being imported."),{level:"warn",msg:e.join("\n---\n"),links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}})))},43487:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(48884),c=i(19851),d=i(50213),h=i(88158),f=i(45393),m=i(56519),p=i(89724),g=i(38835),y=i(74128),v=i(79847),w=i(28874),b=i(47783),S=i(38010),P=i(40958),_=i(76790),T=i(75761),M=i(38639),E=i(11371),k=i(98553),D=i(55835),x=i(31586),C=i(20214),A=i(59455),F=i(64526),I=i(4407),O=i(54017),L=i(48722),R=i(37094),N=i(45295),B=i(39604),j=i(48723),z=i(41507),V=i(72761),W={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class U extends V.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,b.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,M.isTrue)(t.shown)})}const t=R.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(W):e.andWhere(W)}static findUnhiddenById(e){return(0,x.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{unlinkAssetFiles:i});const l=n.getAssetFiles({refresh:!0});if(t){(0,B.upsertToShaBlockslist)(...l.map((e=>e.sha)));for(const e of l)(0,y.syncReport)().onProgress({from:"Asset.remove",path:await e.getNativePath()??e.uri,state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}N.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),R.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&j.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,v.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(N.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,x.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,x.gte)(this.rating,w.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,L.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:j.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,P.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return j.Tag.ops().all(j.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??N.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:j.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:j.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,P.uniq)((0,A.toA)(e.tagIdsToAdd).filter((e=>(0,x.gt0)(e)&&!t.includes(e)))),r=(0,P.uniq)((0,A.toA)(e.tagIdsToRemove).filter((e=>(0,x.gt0)(e)&&t.includes(e))));if((0,P.isEmpty)(i)&&(0,P.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&j.Tag.deltaAssetCountAndAncestors(t,-1),(0,P.isEmpty)(i)||N.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,P.isEmpty)(r)||N.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,P.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&j.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,z.coalesceStreams)((0,P.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,_.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,M.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,x.gt0)(this.id)&&(0,x.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,k.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,M.isTrue)(e.shown)))??this.getAssetFiles({refresh:!0})?.find((e=>(0,M.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,T.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,E.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,T.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,T.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,A.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,x.gte)(this.rating,w.Settings.likeRating.valueOrDefault),hidden:(0,M.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=U,s=U,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("Asset.version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},U.$tableName="Asset",U.$uniqueColumnName="id",U.$booleanFields=["shown","hidden"]},54017:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(76760),o=i(19851),l=i(88158),u=i(45393),c=i(68852),d=i(81168),h=i(13991),f=i(54296),m=i(56519),p=i(76490),g=i(89724),y=i(98314),v=i(38835),w=i(8769),b=i(29882),S=i(95696),P=i(62105),_=i(74128),T=i(35721),M=i(69589),E=i(28874),k=i(28544),D=i(16170),x=i(45200),C=i(34238),A=i(87001),F=i(42233),I=i(21404),O=i(40958),L=i(17586),R=i(22573),N=i(38639),B=i(42659),j=i(33374),z=i(50357),V=i(75240),W=i(11371),U=i(55835),q=i(31586),H=i(68708),G=i(34666),$=i(89937),J=i(75020),K=i(64526),Y=i(41844),X=i(43487),Z=i(48723),Q=i(94710),ee=i(72761);class te extends ee.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>C.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=X.Asset.shownUnhidden(e.q).join("AssetFile","AssetFile.assetId","Asset.id").where("AssetFile.version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("AssetFile.updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("AssetFile.mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("AssetFile.uri",i+"%");return t})).orderBy("AssetFile.id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("AssetFile.id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,q.gt0)(e)?te.ops().first(X.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=X.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,R.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(te.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=te.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=te.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:te.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,H.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith($.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,H.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,U.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,A.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,q.closeTo)(i.mtime,this.mtime,2*B.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return E.Settings.forceSync.valueOrDefault?E.Settings.forceSync.key+"=true":this.version!==u.AssetFileVersion?"AssetFileVersion: "+this.version+" != "+u.AssetFileVersion:this.whyNotMatchesFile(e)}async inSyncWithFile(e){const t=await this.whyNotInSyncWithFile(e);return this.logger().tap({msg:"inSyncWithFile()",result:null==t,meta:{whyNotInSync:t}})}async fileFields_(e){const t=e??await this.posixFile_();return null==t?void 0:await(0,h.assetFileStatFields_)(t)}isInLibrary(){return this.uri.startsWith($.PS_LIBRARY_PROTOCOL)}async isNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){const t=await this.whyNotNoop(e);return this.logger().tap({msg:"isNoop()",result:null==t,meta:{whyNotNoop:t}})}async whyNotNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){if(!0===e.forceSync)return"forceSync is true";if(!(0,q.gt0)(this.id))return"missing .id";if(!(0,q.gt0)(this.assetId))return"missing .assetId";{const e=await this.whyNotInSyncWithFile();if(null!=e)return e}if(await(0,Y.mayCopyAssetsToLibrary)()){const e=K.Library.instanceRequired_().assetFileRepository(),t=e.whyNotCopyFile(await this.posixFile_());if((0,R.blank)(t)&&null==await e.existingLibraryAssetFile(this))return"need to copy into library"}this.syncState=_.AssetFileSyncStates.noop}isVersionUpToDate(){return(0,G.gte)(this.version,u.AssetFileVersion)}async siblingCount(){return te.dbl.pluckFirstf((e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=(0,M.forceContextOrSetting)()){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,q.gt0)(this.id)&&!t.forceSync)return void(null==this.syncState&&(this.upsert(),this.syncState??(this.syncState=_.AssetFileSyncStates.noop)));const i=await this.isFileDeleted();if(!0===i)return this.syncState=_.AssetFileSyncStates.deleted,this.delete(),!0!==t.skipAssetRepair&&Q.Task.addOne("repairAsset",{assetId:this.assetId}),this;if(!1===i){const i=await this.updateFromFile_(e,t);return this.syncState??(this.syncState=null==i?_.AssetFileSyncStates.noop:_.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=_.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,H.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e,t=(0,M.forceContextOrSetting)()){const i=Date.now(),r=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&!0!==t.forceSync&&await this.matchesFile(e))return void r.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=_.AssetFileSyncStates.deleted,void r.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,R.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,H.assignAllFields)(this,(0,H.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=_.SyncFileStates.synced,r.elapsed("finished",Date.now()-i,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,H.assignFields)(this,(0,H.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...te.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,q.gt0)(this.assetId)?X.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,x.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,R.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,A.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,R.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,R.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),k.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,T.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,j.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,N.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===W.ReducerNames.fit)).map((e=>(0,T.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=C.URI.parse(this.uri),t=(0,U.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>Z.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=C.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,L.at)((0,L.at)(e,-1)?.tagPath,-1)}(0,z.eql)(e[0]?.tagPath,[J.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===$.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,L.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===J.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===$.PS_LOCAL_FILE_SCHEME){const t=C.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,H.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,N.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:ie(this.createdAt),updatedAtLocale:ie(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function ie(e){return(0,U.map)(e,(e=>(0,V.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=te,r=new WeakSet,s=function(){if((0,R.blank)(this.uri))return"blank uri";if((0,R.blank)(this.sha))return"blank sha";if(!(0,q.gt0)(this.width))return"missing width";if(!(0,q.gt0)(this.height))return"missing height";if(!(0,q.gt0)(this.capturedAtLocal))return"missing capturedAtLocal";if(!(0,q.gte0)(this.capturedAtPrecisionMs))return"missing capturedAtPrecisionMs";if(E.Settings.useImageHashes.valueOrDefault){const e=[];for(const t of["dctHash","diffHash","meanHash"])(0,R.blank)(this[t])&&e.push(t);if(1===e.length)return"missing image hash: "+e[0];if(e.length>1)return"missing image hashes: "+e.join(", ")}return this.isVersionUpToDate()?void 0:"outdated version"},te.$tableName="AssetFile",te.$uniqueColumnName="uri",te.$booleanFields=["shown"],te.$transientFields=["nativePath","syncState"]},48722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(76596),s=i(31586);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},37094:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},69853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setAssetRotation_=void 0;const r=i(50213),s=i(39250),n=i(66778),a=i(69589),o=i(40958),l=i(45599),u=i(98553),c=i(31586),d=i(21605),h=i(43487),f=i(94710),m=(0,l.defer)((()=>new s.LastOneInWins("Asset")));t.setAssetRotation_=async function(e,t,i){if(!(0,c.gt0)(e))throw new Error("invalid asset "+(0,u.stringify)(e));if(!(0,d.isRotation)(t))throw new Error("setRotation("+t+"): invalid rotation "+(0,u.stringify)(t));return m().enqueue({key:e,fn:s=>async function(e,t,i,s){const c=Date.now(),d=(0,r.mkLogger)("setAssetRotation("+(0,u.stringify)({assetId:e,rotation:t})+")"),m=h.Asset.ops().findById(e);if(null==m)return d.throw("Unknown assetId:"+e);const p=(0,l.defer)((()=>{f.Task.addOne("repairAsset",{assetId:e})}));d.throwIfAborted_(s);const g=m.getAssetFiles();if(null==m.getShown())return p(),d.throw("No primary asset file for Asset "+e+". Trying to repair.",{doNotSend:!0,fatal:!1,retriable:!1});const y=await i.ap(e).smallestFileForReducer("fit");if(null==y)return p(),d.throw("Missing previews for Asset "+e+". Trying to repair.",{doNotSend:!0,fatal:!1,retriable:!1});const v=[];for(const e of g)try{const i=await e.posixFile();if(null==i||await i.notExists()){d.info("cannot rotate variation: file is missing",{f:i,af:e});continue}if(d.throwIfAborted_(s),null==await(0,n.matchAndWriteRotation_)(y,i,t)){d.info("cannot rotate variation: matchRotation() failed",{f:i,af:e});continue}v.push(await e.upsertIfNeeded_(i.clear(),(0,a.forceContextOrSetting)({forceSync:!0})))}catch(t){d.warn("failed to update asset file",{af:e,error:t})}return(0,o.compact)(v),(0,o.isNotEmpty)(v)&&await i.apb(e,g,{forceRebuildPreviews:!0}).build_(),d.info("setRotation("+t+"): completed.",{elapsedMs:Date.now()-c,updatedAssetFiles:v}),v}(e,t,i,s)})}},45295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},61204:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(19851),s=i(50213),n=i(97352),a=i(75020),o=i(4407),l=i(48723),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},31687:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(38835),s=i(42659),n=i(31586),a=i(72761);class o extends a.TimestampedModel{static ping(e){return o.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){if(null==o.db())throw new Error("no library is open"+r.NoLibraryErrorFlag);try{o.ping(e);const t=o.ops().findOneBy({name:e});if(null==t||t.name!==e||(0,n.lt)(t.updatedAt,Date.now()-20*s.secondMs))throw new Error("Heartbeat row wasn't inserted")}finally{try{o.dbl.runf((t=>t.delete().where({name:e})))}catch{}}}}t.Heartbeat=o,o.$tableName="Heartbeat",o.$uniqueColumnName="name",o.$useCache=!1},95700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(19851),s=i(56038),n=i(28874),a=i(42659),o=i(41400),l=i(69032),u=i(61204),c=i(49796);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h());try{await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())}catch{}};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},55046:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(57975),n=i(50213),a=i(7282),o=i(65211),l=i(40958),u=i(38639),c=i(45599),d=i(31586),h=i(68708),f=i(34666),m=i(54993),p=i(57038),g=i(94448),y=i(33572),v=i(63872);class w{constructor(){this.$instanceId=(0,a.isTest)()?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if((0,a.isProd)())throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}update(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("update()",{self:this.toJSON()}),this.class().ops().updateOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},94448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},33572:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(50213),s=i(40958),n=i(22573),a=i(38639),o=i(97790),l=i(51926),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},63872:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(48884),m=i(19851),p=i(50213),g=i(81168),y=i(48299),v=i(12943),w=i(38835),b=i(34102),S=i(28874),P=i(40958),_=i(76790),T=i(22573),M=i(50357),E=i(96249),k=i(98553),D=i(55835),x=i(31586),C=i(68708),A=i(59455),F=i(86859),I=i(33572);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,I.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new F.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,k.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,k.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,D.mapOr)(this.db(),(e=>e.isOpen),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,A.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,_.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,A.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,k.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,D.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,k.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,T.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,T.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);if(null==s)return;return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,k.stringify)(e))}reload(e){const t=[],i=this.allf((i=>{for(const r of e){const e=this.model.hasId(r)?this.model.pickId(r):this.$pickModelUcn(r);null!=e?(t.push([r,e]),i=i.orWhere(e)):h(this,s,"f").warn("reload(): given insufficient partial model",{fragment:r})}return i})),n=[];for(const[e,a]of t){const t=i.find((e=>(0,M.eqlSubset)(a,e)));if(null==t)h(this,s,"f").warn("reload(): failed to find result in db",{prior:e,dbArr:i});else{const i=h(this,r,"m",u).call(this,e);h(this,r,"m",l).call(this,i,t),i!==e&&h(this,r,"m",l).call(this,i,t),n.push(t)}}return n}upsert(e){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const t=this.columnNames(),i=[];for(const s of(0,f.batches)((0,A.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=new Map,n=new Set,a=(0,P.compact)(s.map((e=>this.fromJSON(e))));for(const t of a){const i=(0,k.stringify)(this.$pickModelUcn(t));e.set(i,t),this.model.hasId(t)||n.add(i),t.$beforeUpsert()}h(this,r,"m",c).call(this,a.map((e=>e.$toDbJSON(t))));const o=this.reload(a),l=new Map(o.map((e=>[(0,k.stringify)(this.$pickModelUcn(e)),e])));for(const e of a){const t=(0,k.stringify)(this.$pickModelUcn(e)),r=l.get(t)??e;n.has(t)&&r.$afterInsert(),r.$afterUpsert(),i.push(r)}}return i}delete(e){const t=(0,A.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,k.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},20958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(19851),s=i(50213),n=i(88158),a=i(99331),o=i(70025),l=i(8769),u=i(22573),c=i(98553),d=i(50989),h=i(72761);t.OperationNames=(0,d.strEnum)("rebuildLibrary","forceRestartSync");const f=(0,r.lazy)((()=>(0,s.mkLogger)("model.Operation")));class m extends h.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(m.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return m.getFirstPendingOp(e)??m.ops().insertOne(e)}static getFirstPendingOp(e){return f().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,u.blank)(e?.name)?f().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return f().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce_(e,t,i=n.identity){const r=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=r)return void f().debug("applyOnce(): already done",{priorCompleted:r});const s=this.ops().insertOne(e);try{const e=await t(s);return(0,a.ending)()||s.markCompleted(),e}catch(t){if((0,o.isRedoableError)(t))return void f().info("applyOnce(): redoable error",{crit:e,error:t});throw(0,l.onError)("Operation.applyOnce(): "+(0,c.stringify)(e),t),t}}markCompleted(){null==this.completedAt&&(this.completedAt=Date.now(),this.upsert())}}t.Operation=m,m.$tableName="Operation",m.$uniqueColumnName="id",m.$useCache=!1},49796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.toPct=void 0;const r=i(48161),s=i(1708),n=i(48884),a=i(50213),o=i(28874),l=i(40958),u=i(42659),c=i(45599),d=i(98553),h=i(55835),f=i(31586),m=i(68708),p=i(67478),g=i(51926),y=i(59455),v=i(54993),w=i(76386),b=i(33572),S=i(55009),P=i(72761),_=(0,c.defer)((()=>(0,a.mkLogger)("model.Progress")));function T(e){return null==e||!(0,f.isNumber)(e)||e<0||e>100?void 0:(0,f.sigFigs)(e,3)}t.toPct=T;const M=(0,g.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function E(){const e=o.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*u.dayMs}t.defaultMinCreatedAt=E;class k extends P.TimestampedModel{static vacuum(e=o.Settings.progressRetentionDays.valueOrDefault*u.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t)));for(const e of(0,n.batches)(i,o.Settings.dbBatchSelectSize.valueOrDefault))S.ProgressMeta.dbl.runf((t=>t.whereIn("progressId",e).delete())),k.dbl.runf((t=>t.whereIn("id",e).delete()))}static countCompletedDirectorySyncs(){return this.dbl.pluckFirstf((e=>e.where({state:"done"}).whereNotNull("completedAt").where("uri","like","ps%")))}static times(){return _().tap({msg:"times()",result:this.dbl.all({sql:M})})}static insertNew(e){const t=(0,h.map)(e.dek,d.stringify);return this.ops().insertOne({...(0,m.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&this.assignFromPojo(e),super.upsert()}$beforeUpsert(){super.$beforeUpsert(),null==this.id&&(this.pid??(this.pid=s.pid),this.hostname??(this.hostname=(0,r.hostname)())),"done"===this.state&&(this.completedAt??(this.completedAt=Date.now())),this.completePct=T(this.completePct),this.incompletePct=T(this.incompletePct),this.scanningPct=T(this.scanningPct)}$afterUpsert(){super.$afterUpsert(),(0,w.tellWebProgressUpdated)()}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,l.compactBlanks)((0,p.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,d.stringify)((0,l.compactBlanks)((0,y.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,m.omit)(e,"volume","uri"))}getMeta(){return S.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncomplete(e=E()){return this.logger().tap({msg:"priorIncompleteProgress()",result:k.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc")))})}getLastCompletedAt(e=E()){return k.dbl.pluckFirstf((t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e)))}getLastIncompleteStartAt(){return k.dbl.pluckFirstf((e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0)))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),S.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,l.diff)(t.map((e=>e.name)),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),S.ProgressMeta.ops().upsert((0,m.entries)(e).map((([e,t])=>({progressId:this.id,name:e,value:(0,v.toS)(t)})))),(0,l.isNotEmpty)(i)&&S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).whereIn("name",i).delete()))}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),S.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,m.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=k,k.$tableName="Progress",k.$uniqueColumnName="id"},55009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},39604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(19851),s=i(50213),n=i(95696),a=i(40958),o=i(22573),l=i(86859),u=i(94448),c=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),d=(0,r.lazy)((()=>new l.DbRequest(u.modelDb,"ShaBlocklist")));function h(e){return null!=(0,u.modelDb)()&&!(0,o.blank)(e)&&c().tap({msg:"isShaBlockslisted",result:null!=d().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}function f(...e){if(null==u.modelDb.prior())return;const t=(0,a.uniq)(e).map((e=>({sha:e})));return(0,a.isEmpty)(t)?void 0:d().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,u.modelDb)())return null;const t=h(await n.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=h,t.upsertFileToShaBlockslist=async function(e){if(null==(0,u.modelDb)())return;const t=await n.PosixFile.for(e).sha();return null==t?void 0:f(t)},t.upsertToShaBlockslist=f},48723:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(56038),o=i(34102),l=i(19851),u=i(50213),c=i(36372),d=i(97352),h=i(28874),f=i(81168),m=i(42231),p=i(75020),g=i(40958),y=i(22573),v=i(42659),w=i(41400),b=i(50357),S=i(55835),P=i(31586),_=i(34666),T=i(20214),M=i(51926),E=i(59455),k=i(12168),D=i(6186),x=i(57038),C=i(21074),A=i(7656),F=i(43487),I=i(48722),O=i(45295),L=i(98784),R=i(41507),N=i(72761),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,M.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:F.Asset.dbl.pluckFirst(F.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset(),this.ops().clearDbCache()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{r.clear();for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.update({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,M.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:A.RecursiveAssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),this.ops().upsertOne(i)}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return F.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,T.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();return(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)})),r.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,M.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(F.Asset.dbl.all(t).map(I.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return F.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,k.fmt)(e.length)+" of ")+(0,k.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,M.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:A.RecursiveAssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?F.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(F.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(I.toAssetId))));for(const t of r)t.assetIdF.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(this.id??0),"Asset.id",i)).limit(t))).map(I.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!0,z.cmp=(e,t)=>(0,_.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=F.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(D.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e}),B);const V=(0,l.lazy)((()=>F.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},98784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(38156),s=i(3127),n=i(40958),a=i(41400),o=i(94715),l=i(55046),u=i(48723);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=new r.PushProgressObserver({op:"Rebuilding tag search index"},u.Tag.dbl.pluckFirstf((e=>e.count("*")))),t=this.dbl.db();o.Migrations.create_tag_fts(t.db),await u.Tag.ops().batched({qb:e=>e,onResults:t=>(this.$logger().throwIfAborted_(),this.insertFts(t),e.incrProgress(t.length),(0,a.delay)(1))}),e.completed()}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},41507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},94710:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Task=t.StaleTaskError=t.InvalidTaskError=t.TaskNames=t.Tasks=t.testTask=void 0;const c=i(78474),d=i(22454),h=i(23560),f=i(12089),m=i(76740),p=i(22911),g=i(99331),y=i(31562),v=i(38835),w=i(70025),b=i(8769),S=i(74128),P=i(28874),_=i(37692),T=i(40958),M=i(22573),E=i(42659),k=i(45599),D=i(98553),x=i(49769),C=i(68708),A=i(50989),F=i(59455),I=i(58723),O=i(34274),L=i(90901),R=i(61989),N=i(93755),B=i(69032),j=i(55046);t.testTask=(0,f.shim1)({name:"testTask",impl:async e=>{}}),t.Tasks={applyDeleted:I.applyDeleted,applyExcluded:I.applyExcluded,runTagMaintenance:B.runTagMaintenance,updateAssetFile:N.updateAssetFile_,repairAsset:async function(e){e.forceSync=!0,e.skipPreviews=!0,e.skipAssetTagging=!0;const t=await(0,R.updateAsset_)(e);return(0,T.isNotEmpty)(t?.assetIdsToUpdate)&&q.add(t?.assetIdsToUpdate.map((t=>({fn:"repairAsset",args:{...e,assetId:t},priority:W.repairAsset+1})))),null!=t&&!0!==t.deleted&&(0,M.blank)((0,F.toA)(t.rejected).join(""))&&(0,M.blank)(t.error)&&q.addOne("assetPostUpsertTasks",(0,C.omit)(e,"skipPreviews","skipAssetTagging")),t},assetPostUpsertTasks:L.assetPostUpsertTasks,syncFile:O.importFileToResult_,testTask:t.testTask},t.TaskNames=(0,A.strEnum)(...(0,C.keys)(t.Tasks));class z extends Error{}t.InvalidTaskError=z;class V extends Error{}t.StaleTaskError=V;const W={applyDeleted:16,applyExcluded:16,runTagMaintenance:14,updateAssetFile:13,repairAsset:12,assetPostUpsertTasks:10,syncFile:0,testTask:-1},U=["repairAsset"];class q extends j.Model{constructor(){super(...arguments),r.add(this),o.set(this,(0,k.defer)((()=>new m.Abortable)))}static countTaskNames(){const e={};for(const t of s.dbl.allf((e=>e.select("fn").count().groupBy("fn"))))e[t.fn]=t["count(*)"];return e}static orderBy(e){return e.orderBy([{column:"priority",order:"desc"},{column:"retries",order:"desc"},{column:"id",order:"asc"}])}static count(){return s.dbl.pluckFirstf((e=>e.count("id")))}static freeSlots(){return P.Settings.taskListCap.valueOrDefault-s.count()}static countByFn(e){return s.dbl.pluckFirstf((t=>t.where({fn:e}).count("id")))}static nextByFn(e,t=(e=>e)){return s.ops().allf((i=>s.orderBy(t(i.where({fn:e})))))}set args(e){this.argsJSON=(0,D.stringify)(e)}get args(){const e=(0,D.parseJSON)(this.argsJSON);return(0,C.notEmptyObj)(e)&&(e.halt=u(this,o,"f").call(this)),e}get isSerial(){return U.includes(this.fn)}toString(){return`Task#${this.fn}(${this.argsJSON})`}static addOne(e,t){return s.add([{fn:e,args:t}])[0]}static add(e,t=!1){if((0,T.isEmpty)(e))return[];const i=s.ops().upsert(e.map((e=>({fn:e.fn,argsJSON:(0,D.stringify)(e.args)})),t));return s.ee.emit("added",i),(0,h.isTaskListManager)()||(0,_.addStateEvent)("checkTasks"),i}$beforeUpsert(){this.priority??(this.priority=W[this.fn]),this.retries??(this.retries=P.Settings.maxRetries.valueOrDefault)}donePromise(){return(0,h.isTaskListManager)()?(0,x.getOrSet)(u(s,s,"f",n),this.id,(()=>new p.Deferred(this.toString(),{payload:this}))):(0,y.untilTrue)((()=>null==s.ops().findById(this.id)),{intervalMs:E.secondMs})}abort(e){this.logger().warn("aborting task",{reason:e,task:this}),u(this,o,"f").call(this).abort(e),this.delete(),(0,M.blank)(this.args.path)||(0,S.syncReport)().onProgress({path:this.args.path,from:this.fn,state:S.SyncFileStates.failed,details:e})}async _run(){if(this.retries<0)throw this.logger().warn(".run(): too many retries"+v.InternalErrorFlag,{job:this}),this.delete(),new z;if(!u(this,r,"m",l).call(this))throw this.logger().warn(".run(): someone already started this task",{job:this}),new V;try{const e=Date.now(),i=await t.Tasks[this.fn](this.args);return this.logger().throwIfAborted_(u(this,o,"f").prior()),s.taskResolvedCounts.incr(this.fn),s.ee.emit("resolved",this,i,Date.now()-e),this.delete(),u(s,s,"f",n).get(this.id)?.resolve(i),i}catch(e){if((0,g.ending)())throw this.logger().info("task failed, but we're ending. We'll leave it for next time.",{task:this}),e;throw s.taskRejectedCounts.incr(this.fn),(0,w.isRedoableError)(e)?(this.retries++,this.priority--,this.upsert()):!0===(0,w.isRetriableError)(e)&&this.retries>=0?this.logger().warn("run failed, but we can retry it later",{task:this,error:e}):(s.ee.emit("rejected",this,e),this.delete(),u(s,s,"f",n).get(this.id)?.reject(e),(0,b.onError)(this.toString()+" failed",e)),e}finally{u(s,s,"m",a).call(s)}}}t.Task=q,s=q,o=new WeakMap,r=new WeakSet,a=function(){for(const[e,t]of u(this,s,"f",n).entries())t.isSettled&&u(this,s,"f",n).delete(e)},l=function(){const e=this.retries;if(1===s.dbl.runf((t=>t.where({id:this.id,retries:e}).update({retries:e-1}))).changes)return--this.retries,!0;{const e=this.toJSON(),t=this.reload();return this.logger().warn(".#decrRetries(): someone already started this task",{before:e,reloaded:t}),!1}},q.$tableName="Task",q.$uniqueColumnName="fn,argsJSON",q.$useCache=!1,q.taskResolvedCounts=new d.CountingSet,q.taskRejectedCounts=new d.CountingSet,q.ee=new c.EventEmitter,n={value:new Map}},72761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),this.createdAt??(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},73407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeAssetTags_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(47783),o=i(54017),l=(0,r.lazy)((()=>(0,s.mkLogger)("model.WriteAssetTags")));t.writeAssetTags_=async function(e,t){const i=o.AssetFile.ops().findBy({assetId:e});return(0,n.mapAsync)({name:"writeAssetTags",arr:i,f:e=>async function(e,t){const i=await e.posixFile_();if(null!=i&&!0===await(i?.exists()))return(0,a.writeTags_)(i,t,e.mimetype);l().info("Skipping AssetFile:"+e.id+" (file is missing)",{writeTags:t})}(e,t)})}},58723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyExcluded=t.applyDeleted=void 0;const r=i(50213),s=i(43487),n=(0,r.mkLogger)("ops.ApplyRemovable");async function a(e,t,i){const r=e?"Deleting":"Excluding",a=e?"deletedAt":"excludedAt";await s.Asset.dbl.batched({qb:e=>e.select("id").where("shown",0).andWhere(a,"<=",t),onResults:async t=>{for(const a of t){n.throwIfAborted_(i);try{await s.Asset.remove({assetId:a,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){n.error(r+" failed",{assetId:a,error:e})}}}})}t.applyDeleted=function(e){return a(!0,e.createdAt,e.halt)},t.applyExcluded=function(e){return a(!1,e.createdAt,e.halt)}},76386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)((()=>(0,s.mkLogger)("progress.Progress")));t.ProgressRateMs=(0,r.lazy)((()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:1.5))),t.tellWebProgressUpdated=(0,r.lazy)((async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch((e=>h().warn(".tellWebProgressUpdated: failed",{error:e})))}),(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},44694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryTermToFuzzyDate=void 0;const r=i(98725),s=(0,i(19851).lazy)((()=>new r.FuzzyDateParser({fuzzyDateParsing:!0,fuzzyYearParsing:!0})));t.queryTermToFuzzyDate=function(e){return s().parse(e)}},43786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToString=t.NormieQuerySymbols=t.SetQuerySymbols=t.isTrueTerm=t.flatTerms=t.findTerm=t.hasNsTerm=t.isQuery=t.isClause=t.isAndClause=t.isOrClause=t.isTerm=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(51926),o=i(54993);function l(e){return"object"==typeof e&&(0,s.notBlank)(e.term)&&(null==e.not||"boolean"==typeof e.not&&(null==e.ns||(0,a.isString)(e.ns)))}function u(e){return"object"==typeof e&&Array.isArray(e.queries)}function c(e){return"or"===e?.type&&u(e)}function d(e){return"and"===e?.type&&u(e)}function h(e){return d(e)||c(e)}function f(e,t){if(l(e))return t(e)?e:void 0;for(const i of e.queries){const e=f(i,t);if(null!=e)return e}}t.isTerm=l,t.isOrClause=c,t.isAndClause=d,t.isClause=h,t.isQuery=function(e){return l(e)||h(e)},t.hasNsTerm=function(e,t){return null!=f(e,(e=>e.ns===t))},t.findTerm=f,t.flatTerms=function e(t){return l(t)?[t]:(0,r.flatMap)(t.queries,e)},t.isTrueTerm=function(e){return(0,n.isTrue)(e?.not)?(0,n.isFalse)(e?.term):(0,n.isTrue)(e?.term)},t.SetQuerySymbols={not:"¬",and:"∧",or:"∨"},t.NormieQuerySymbols={not:"-",and:"AND",or:"OR"},t.queryToString=function e(i,r=t.SetQuerySymbols){if(null==i)return"";if(l(i)){let e=i.term;return null==i.term.match(/^[a-z]+$/i)&&(e='"'+e.replace(/"/g,'\\"')+'"'),`${(0,n.isTrue)(i.not)?r.not:""}${null==i.ns?"":i.ns+":"+(0,o.toS)(i.op)}${e}`}return"("+i.queries.map((t=>e(t,r))).join(` ${"or"===i.type?r.or:r.and} `)+")"}},7573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeTerm=t.isAssetTerm=t.AssetTermNs=t.AssetTermDateNs=t.AssetTermBoolNs=t.normalizeQuery=void 0;const r=i(48884),s=i(75020),n=i(40958),a=i(76790),o=i(22573),l=i(38639),u=i(50989),c=i(54993),d=i(44694),h=i(43786);function f(e){return(0,a.sortBy)((0,n.uniqBy)(e,h.queryToString),(e=>[(0,h.isTerm)(e)?0:(0,h.isOrClause)(e)?1:2,(0,h.queryToString)(e).replace(/[¬(]+/g,"")]))}t.normalizeQuery=function e(t){if((0,h.isTerm)(t))return g(t);const i=t.queries.map(e);if(0===i.length)throw new Error("empty query");if(1===i.length)return i[0];const[s,n]=(0,r.partition)(i,h.isTerm),[a,o]=(0,r.partition)(n,(e=>e.type===t.type));for(const e of a)s.push(...e.queries);const l={type:t.type,queries:f([...s,...o])};return l.queries.every((e=>(0,h.isTerm)(e)&&e.not))?e({type:"and"===t.type?"or":"and",queries:f(l.queries.map((e=>({...e,not:!1}))))}):l},t.AssetTermBoolNs=(0,u.strEnum)("deleted","excluded","liked","hidden"),t.AssetTermDateNs=(0,u.strEnum)("date","updated");const m={delete:t.AssetTermBoolNs.deleted,trash:t.AssetTermBoolNs.deleted,trashed:t.AssetTermBoolNs.deleted,exclude:t.AssetTermBoolNs.excluded,remove:t.AssetTermBoolNs.excluded,removed:t.AssetTermBoolNs.excluded,like:t.AssetTermBoolNs.liked,fav:t.AssetTermBoolNs.liked,fave:t.AssetTermBoolNs.liked,faved:t.AssetTermBoolNs.liked,favorite:t.AssetTermBoolNs.liked,favourite:t.AssetTermBoolNs.liked,hide:t.AssetTermBoolNs.hidden,archive:t.AssetTermBoolNs.hidden,archived:t.AssetTermBoolNs.hidden},p={kw:s.TagRoots.Keywords,keyword:s.TagRoots.Keywords,keywords:s.TagRoots.Keywords,dir:s.TagRoots.fs,directory:s.TagRoots.fs,folder:s.TagRoots.fs};function g(e){if((0,o.blank)(e.ns)&&null!=e.term.match(/^\d{4}[-\d]*$/)&&null!=(0,d.queryTermToFuzzyDate)(e.term))return{ns:"date",term:e.term};if("when"===(0,c.toS)(e.ns).toLowerCase())return g({...e,ns:t.AssetTermDateNs.date,term:e.term.replace(/\//g,"-")});let i=(0,o.notBlankOr)(e.ns,e.term).toLowerCase();if(i=m[i]??i,t.AssetTermBoolNs.includes(i)){let t=!(0,l.isFalse)(e.term);return!0===e.not&&(t=!t),{ns:i,term:(0,c.toS)(t)}}if(t.AssetTermNs.includes(i))return{...e,ns:i};if("before"===i||"after"===i){if(null!=e.op)throw new Error(i+": doesn't support operators");const r="after"===i&&!0!==e.not||!0===e.not;return{ns:t.AssetTermDateNs.date,op:r?">":"<",term:e.term}}return i!==e.term.toLowerCase()?{not:e.not,op:e.op,ns:p[i]??i,term:e.term}:e}t.AssetTermNs=(0,u.strEnum)(...t.AssetTermDateNs.values,...t.AssetTermBoolNs.values),t.isAssetTerm=function(e){return(0,h.isTerm)(e)&&t.AssetTermNs.includes(g(e).ns)},t.normalizeTerm=g},33693:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseQuery_=void 0;const s=r(i(31704)),n=i(19851),a=i(50213),o=i(7282),l=i(38835),u=i(31586),c=r(i(70471)),d=(0,n.lazy)((()=>(0,a.mkLogger)("query.QueryParser")));t.parseQuery_=function(e){try{const t=new s.default.Parser(s.default.Grammar.fromCompiled(c.default)).feed(e.trim()).finish();if(t.length>1&&!(0,o.isProd)()&&d().throw("parseQuery(): ambiguous grammar!",{input:e}),null==t[0])throw new Error("invalid query");return d().debug("parseQuery()",{input:e,result:t[0]}),t[0]}catch(t){const i=t.token?.col,r=`Query syntax error${(0,u.gt0)(i)?" around column "+i:""}: "${e}"`;throw d().warn("parseQuery(): bad query",{msg:r,err:t}),new Error(r+l.NonRetriableErrorFlag+l.DoNotSendErrorFlag)}}},23523:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToSql=t.queryStringToSql_=t.defaultAssetQuery=void 0;const r=i(19851),s=i(50213),n=i(66649),a=i(89724),o=i(70417),l=i(28874),u=i(42231),c=i(22573),d=i(38639),h=i(98553),f=i(54993),m=i(57038),p=i(43487),g=i(44694),y=i(43786),v=i(7573),w=i(33693),b=(0,r.lazy)((()=>(0,s.mkLogger)("query.QueryToSql")));function S(e,t,i){if((0,y.isTerm)(t))return function(e,t,i){return(0,v.isAssetTerm)(t)?function(e,t){switch(t.ns){case v.AssetTermNs.date:case v.AssetTermNs.updated:return function(e,t){const i=t.op??"=",r="date"===t.ns?"Asset.capturedAtLocal":"updated"===t.ns?"Asset.updatedAt":void 0;if(null==r)throw new Error("internal error: unexpected namespace for "+(0,h.stringify)(t));const s="Asset.updatedAt"===r?n.datedToMillis:a.maybeDatedToLocal,l=(0,g.queryTermToFuzzyDate)(t.term),u=s(l),c=l?.following()?.toDateTime(),d=s(c?.minus({second:1})),f=(0,o.max)([u,d]);if(null==l||null==u||null==f)throw new Error((0,y.queryToString)(t,y.NormieQuerySymbols)+" can't be parsed as a date");if("="===i)return e.whereBetween(r,[u,f]);if("<"===i)return e.where(r,i,u);if("<="===i)return e.where(r,i,f);if(">="===i)return e.where(r,i,u);if(">"===i)return e.where(r,i,f);throw new Error("internal error: unexpected op for "+(0,h.stringify)(t))}(e,t);case v.AssetTermNs.hidden:return e.where("Asset.hidden",_(t));case v.AssetTermNs.excluded:return M({qb:e,column:"Asset.excludedAt",whereNull:0===_(t)});case v.AssetTermNs.deleted:return M({qb:e,column:"Asset.deletedAt",whereNull:0===_(t)});case v.AssetTermNs.liked:return e.where("Asset.rating",P(t)?">=":"<",l.Settings.likeRating.valueOrDefault);default:throw new Error("not asset term:"+(0,y.queryToString)(t))}}(e,t):function(e,t,i){const r=t.term.startsWith("/"),s="="===t.op,n=function(e,t){if(null==t||"fs"!==e.ns)return e.term;const i=e.term.split("/"),r=i.findIndex(c.notBlank);if(-1===r)return e.term;const s=i[r];return i[r]=t.get(s)??s,i.join("/")}(t,i);if(r||s)return e.whereIn("Asset.id",(0,m.knex)()("AssetTag").join("Tag","Tag.id","AssetTag.tagId").select("assetId").whereLike("Tag._path",t.ns+(r?"":"%")+n.replace(/\//g,u.TagSep).replace(/\*/g,"%")+u.TagSep+(s?"":"%")));let a=(0,m.knex)()("AssetTag").join("tag_fts","tag_fts.rowid","AssetTag.tagId").select("assetId");const o="path:"+T(n.replace(/\//g," + "));if((0,c.blank)(t.ns)){if((0,d.isTrue)(t.not))throw new Error("Cannot negate without a namespace ("+(0,y.queryToString)(t)+")");a=a.where("tag_fts","MATCH",o)}else a=a.where("tag_fts","MATCH","(root:"+T(t.ns)+((0,d.isTrue)(t.not)?" NOT ":" AND ")+o+")");return e.whereIn("Asset.id",a)}(e,t,i)}(e,t,i);for(const r of t.queries)e=(0,y.isAndClause)(t)?e.andWhere((e=>S(e,r,i))):e.orWhere((e=>S(e,r,i)));return e}function P(e){const t=(0,d.isTrue)(e.term);return!0===e.not?!t:t}function _(e){return P(e)?1:0}function T(e){return e.includes("*")?e.split("*").map(T).join(" * "):`"${(0,f.toS)(e).replace(/"/g,'""')}"`}function M({qb:e,column:t,whereNull:i}){return i?e.whereNull(t):e.whereNotNull(t)}function E(){return p.Asset.ops().query().where("Asset.shown",1).join("AssetTag","AssetTag.assetId","Asset.id")}function k(e,t=E(),i){return e=(0,v.normalizeQuery)(e),(0,y.hasNsTerm)(e,v.AssetTermBoolNs.hidden)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.excluded)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.deleted)||(t=t.andWhere({"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null})),t.andWhere((t=>S(t,e,i)))}t.defaultAssetQuery=E,t.queryStringToSql_=function(e,t=E()){const i=(0,w.parseQuery_)(e);return null==i?(b().warn("assetQuery("+e+"): parsed to null"),t):k(i,t)},t.queryToSql=k},70471:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};function s(e){return e[0]}Object.defineProperty(t,"__esModule",{value:!0}),t.parseTerm=void 0;const n=r(i(80265)),a=i(40958),o=i(54993);function l(e){if(null==e[0]&&["and","or"].includes((0,o.toS)(e[1]).toLowerCase()))throw new Error("Unmatched "+e[1]);return{not:null!=e[0]?.[0]?.value,ns:e[0]?.[1]?.value,op:e[0]?.[3]?.value,term:e[1]}}function u(e){return e[0]?.value}t.parseTerm=l;const c=n.default.compile({qstr:[{match:/"(?:[^\\"]|\\.)*?"/,value:e=>e.slice(1,-1).replace(/\\"/g,'"')},{match:/'(?:[^\\']|\\.)*?'/,value:e=>e.slice(1,-1).replace(/\\'/g,"'")}],lp:"(",rp:")",not:/[-¬]/,col:":",op:/<=?|>=?|=/,or:/ +(?:or|OR|Or|∨|\|{1,2}) +/,and:/(?:and|AND|And|∧|\&{1,2}) +/,str:/[^\s:\(\)"'][^\s:\(\)]*/,ws:/ +/}),d={Lexer:c,ParserRules:[{name:"Expression$ebnf$1",symbols:[]},{name:"Expression$ebnf$1$subexpression$1",symbols:[c.has("or")?{type:"or"}:or,"Clause"]},{name:"Expression$ebnf$1",symbols:["Expression$ebnf$1","Expression$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Expression",symbols:["Clause","Expression$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[1]))]);return 1===t.length?t[0]:{type:"or",queries:t}}},{name:"Clause$ebnf$1",symbols:[]},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("and")?{type:"and"}:and],postprocess:s},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Clause$ebnf$1$subexpression$1",symbols:["__","Clause$ebnf$1$subexpression$1$ebnf$1","Factor"]},{name:"Clause$ebnf$1",symbols:["Clause$ebnf$1","Clause$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Clause",symbols:["Factor","Clause$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[2]))]);return 1===t.length?t[0]:{type:"and",queries:t}}},{name:"Factor",symbols:["Term"],postprocess:s},{name:"Factor",symbols:[c.has("lp")?{type:"lp"}:lp,"_","Expression","_",c.has("rp")?{type:"rp"}:rp],postprocess:function(e){const t=(0,a.compact)(e[2]);return 1===t.length?t[0]:t}},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("not")?{type:"not"}:not],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[c.has("op")?{type:"op"}:op],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1",symbols:["Term$ebnf$1$subexpression$1$ebnf$1",c.has("str")?{type:"str"}:str,c.has("col")?{type:"col"}:col,"Term$ebnf$1$subexpression$1$ebnf$2"]},{name:"Term$ebnf$1",symbols:["Term$ebnf$1$subexpression$1"],postprocess:s},{name:"Term$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term",symbols:["Term$ebnf$1","Value"],postprocess:l},{name:"Value",symbols:[c.has("qstr")?{type:"qstr"}:qstr],postprocess:u},{name:"Value",symbols:[c.has("str")?{type:"str"}:str],postprocess:u},{name:"_$ebnf$1",symbols:[c.has("ws")?{type:"ws"}:ws],postprocess:s},{name:"_$ebnf$1",symbols:[],postprocess:()=>null},{name:"_",symbols:["_$ebnf$1"]},{name:"__",symbols:[c.has("ws")?{type:"ws"}:ws]}],ParserStart:"Expression"};t.default=d},22968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeRebuildLibrary=t.forceRebuildLibraryLater=t.rebuildLibraryOperationCrit=void 0;const r=i(45393),s=i(28874),n=i(98553),a=i(43487),o=i(54017),l=i(20958),u=i(33567);function c(){return{name:l.OperationNames.rebuildLibrary,value:(0,n.stringify)({AssetVersion:r.AssetVersion,AssetFileVersion:r.AssetFileVersion})}}t.rebuildLibraryOperationCrit=c,t.forceRebuildLibraryLater=function(){a.Asset.dbl.runf((e=>e.update({version:0}))),o.AssetFile.dbl.runf((e=>e.update({version:0}))),l.Operation.dbl.runf((e=>e.where(c()).delete()))},t.maybeRebuildLibrary=async function(){return s.Settings.skipLibraryRebuild.valueOrDefault?void 0:l.Operation.applyOnce_(c(),(()=>(new u.LibraryRebuild).doneLatch))}},33567:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LibraryRebuild=void 0;const c=i(19851),d=i(83412),h=i(25764),f=i(8769),m=i(76752),p=i(28874),g=i(15674),y=i(22573),v=i(42659),w=i(31586),b=i(12168),S=i(12236),P=i(35580),_=i(49796),T=i(94710),M=i(18209);class E extends d.DoneWrapper{constructor(){super("LibraryRebuild",(()=>u(this,r,"m",a).call(this)),h.EndableRanks.first),r.add(this),this.assetFileEta=new m.ETA,this.assetEta=new m.ETA,this.assetFilesUpdated=0,this.assetsUpdated=0,this.initialAssetTodoCount=(0,M.outdatedAssetCountSync)(),this.initialAssetFileTodoCount=(0,M.outdatedAssetCountSync)(),this.assetFileTodo=(0,c.lazy)((()=>(0,M.outdatedAssetFileCountSync)()),5*v.secondMs),s.set(this,(0,c.lazy)((()=>_.Progress.insertNew({uri:S.RebuildingURI,volume:"🔄",scanningPct:0})))),o.set(this,((e,t,i)=>{"updateAssetFile"===e.fn?(this.assetFilesUpdated++,this.assetFileEta.push(i),u(this,r,"m",n).call(this)):"repairAsset"===e.fn&&(this.assetsUpdated++,this.assetEta.push(i),u(this,r,"m",n).call(this))})),T.Task.ee.on("resolved",u(this,o,"f")),this.doneLatch.observe(u(this,r,"m",l).call(this))}assetTodo(){return(0,M.outdatedAssetCountSync)()}}t.LibraryRebuild=E,s=new WeakMap,o=new WeakMap,r=new WeakSet,n=async function({force:e=!1,done:t=!1}={}){const i=u(this,s,"f").call(this);if(e||!(0,w.gt)(i.updatedAt,Date.now()-v.secondMs))if((t??this.isDone())&&"done"!==i.state){const e=[];this.assetFilesUpdated>0&&e.push(`Updated file metadata for ${(0,b.fmt)(this.assetFilesUpdated)} files (roughly ${(0,b.fmt)(this.assetFileTodo())} remain).`),this.assetsUpdated>0&&e.push(`Refreshed ${(0,b.fmt)(this.assetsUpdated)} assets (roughly ${(0,b.fmt)(await this.assetTodo())} remain).`),i.dek=e,i.upsert({state:"done",hed:"Finished rebuilding your library 🎉",completePct:100,incompletePct:0,scanningPct:0})}else{let e="Rebuilding your library";const t=this.assetFileTodo(),r=await this.assetTodo(),s=(this.assetFileEta.etaMs(t/(0,g.maxConcurrentImports)())??0)+(this.assetEta.etaMs(r)??0),n=[];t>0&&n.push(`Updating file metadata (${(0,b.fmt)(this.assetFilesUpdated)} processed)`),r>0&&n.push(`Refreshing assets and previews (${(0,b.fmt)(this.assetsUpdated)} processed`);const a=t+r,o=this.assetFilesUpdated+this.assetsUpdated,l=(0,w.clamp)(0,100,Math.round(o/(a+o)*100)),u=(0,m.fmtEstimate)(s);(0,y.notBlank)(u)&&(e+=", "+u+"…"),i.dek=n,i.upsert({state:"processing",hed:e,completePct:l,incompletePct:100-l,scanningPct:0})}},a=function(){T.Task.ee.off("resolved",u(this,o,"f"))},l=async function(){this.logger.info("Starting library rebuild...");const e=p.Settings.forceFilters.getState();try{p.Settings.forceFilters.envValue=!0;const e=P.TaskList.instance(),t=await this.assetFileTodo(),i=await this.assetTodo();if(this.logger.info(".run()",{assetFileTodo:t,assetTodo:i}),0===t&&0===i)return;let s=!1;for(;!s;)s=(await(0,M.enqueueAssetFileUpdates)()).done,this.logger.info("run(): waiting for asset updates to complete..."),await e.awaitDrain(["updateAssetFile"],s?0:p.Settings.taskListCap.valueOrDefault/2);for(s=!1;!s;)s=(await(0,M.enqueueAssetUpdates)()).done,await e.awaitDrain(["repairAsset","assetPostUpsertTasks"],s?0:p.Settings.taskListCap.valueOrDefault/2);await u(this,r,"m",n).call(this,{done:!0,force:!0}),this.logger.info("rebuild complete!")}catch(e){(0,f.onError)("LibraryUpdater.run() failed",e)}finally{p.Settings.forceFilters.setState(e)}}},18209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.enqueueAssetUpdates=t.outdatedAssetCount=t.enqueueAssetFileUpdates=t.outdatedAssetFileCountSync=t.outdatedAssetCountSync=t.outdatedAssetFileCount=t.currentUriRoots=void 0;const r=i(50213),s=i(45393),n=i(70417),a=i(45200),o=i(5696),l=i(7014),u=i(40958),c=i(45599),d=i(41400),h=i(20214),f=i(54993),m=i(43487),p=i(54017),g=i(94710),y=(0,c.defer)((()=>(0,r.mkLogger)("sync.UpdateQueue")));async function v(){return[...await(0,h.thenCollect)((0,l.volumes)(),(async e=>(0,a.nativePath2uri)(e.mountpoint,e))),o.PSLIB_ROOT_URI].map(f.toS)}t.currentUriRoots=v,t.outdatedAssetFileCount=async function(){const e=await v();return p.AssetFile.dbl.pluckFirstf((t=>t.count("AssetFile.id").distinct().where("version","!=",s.AssetFileVersion).andWhere((t=>e.forEach((e=>t.orWhereLike("AssetFile.uri",e+"%")))))))},t.outdatedAssetCountSync=function(){return m.Asset.outdatedCount()},t.outdatedAssetFileCountSync=function(){return p.AssetFile.dbl.pluckFirstf((e=>e.count("id").where("version","!=",s.AssetFileVersion)))},t.enqueueAssetFileUpdates=async function(){const e=[];for(const t of await v())e.push(await p.AssetFile.dbl.batched({maxResults:g.Task.freeSlots(),onResults:async e=>{const t=[];for(const i of e)t.push({fn:"updateAssetFile",args:{assetFileId:i.id,path:await(0,a.uri2nativePath)(i.uri),skipAssetRepair:!0}});g.Task.add(t),y().info("Scheduled updateAssetFile",{tasks:t})},qb:(e,i)=>(e=e.select({id:"AssetFile.id",uri:"AssetFile.uri"}).distinct().orderBy("AssetFile.id","asc").where("AssetFile.version","!=",s.AssetFileVersion).andWhereLike("AssetFile.uri",t+"%"),(0,u.isNotEmpty)(i)&&(e=e.andWhere("AssetFile.id",">",(0,n.max)(i.map((e=>e.id))))),e)}));return y().tap({msg:"enqueueAssetFileUpdates",level:"info",result:{done:e.every((e=>e.done)),tasksAdded:(0,n.sumf)(e,(e=>e.resultCount))}})},t.outdatedAssetCount=async function(){const e=await v();return m.Asset.dbl.pluckFirstf((t=>t.count("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").where("Asset.version","!=",s.AssetVersion).andWhere((t=>e.forEach((e=>t.orWhereLike("AssetFile.uri",e+"%")))))))},t.enqueueAssetUpdates=async function(){const e=[];for(const t of await v())e.push(await m.Asset.dbl.pluckBatched({maxResults:g.Task.freeSlots(),onResults:e=>(g.Task.add(e.map((e=>({fn:"repairAsset",args:{assetId:e}})))),y().info("Scheduled repairAsset for ",{assetIds:e}),(0,d.delay)(1)),qb:(e,i)=>(e=e.select("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").orderBy("Asset.id","asc").where("Asset.version","!=",s.AssetVersion).andWhereLike("AssetFile.uri",t+"%"),(0,u.isNotEmpty)(i)&&(e=e.andWhere("Asset.id",">",(0,n.max)(i))),e)}));return y().tap({msg:"enqueueAssetUpdates",level:"info",result:{done:e.every((e=>e.done)),tasksAdded:(0,n.sumf)(e,(e=>e.resultCount))}})}},3996:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const a=i(19851),o=i(50213),l=i(79781),u=i(56519),c=i(56038),d=i(59189),h=i(38835),f=i(95696),m=i(48368),p=i(181),g=i(69589),y=i(28874),v=i(28544),w=i(47783),b=i(87001),S=i(40958),P=i(76790),_=i(22573),T=i(42659),M=i(55835),E=i(31586),k=i(43487),D=i(54017);t.isFileInSync=async function(e){return new C(f.PosixFile.for(e)).alreadySynced()};const x=new d.SerialLaterQueue;class C{constructor(e,t=(0,g.forceContextOrSetting)()){this.file=e,this.ctx=t,r.set(this,void 0),this.rejectedAssetIds=new Set,this.rejectedSiblingIds=new Set,this.alreadySynced=(0,c.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>n(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,c.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new D.AssetFile).updateFromFile_(this.file);return null==e?n(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,a.lazy)((async()=>{const e=await(0,w.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,a.lazy)((()=>y.Settings.useImageHashes.valueOrDefault?(0,m.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,a.lazy)((()=>(0,u.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,a.lazy)((async()=>{const e=await this.capturedAt_();return n(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,c.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,_.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return n(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await x.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return n(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new k.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,c.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,p.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtAndImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,c.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return n(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;n(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw n(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),s(this,r,(0,o.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f")}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),n(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}n(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(e=this.file){const t=await e.uri_();if(null!=t)return D.AssetFile.ops().firstf((e=>e.whereIn("uri",[...(0,b.uriEncodingVariants)(t),this.file.fileuri()])));n(this,r,"f").warn("byUri() uri is null",{file:e})}async assetByNormalizedPathUri(){const e=await this.file.normalize();return e.nativePath===this.file.nativePath?void 0:(await this.byUri(e))?.getAsset()}async assetBySha(){const e=await this.file.sha_();return k.Asset.findFirstByFile((t=>(t=t.where("AssetFile.sha",e),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds))),this.rejectedSiblingIds.size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),t)))}async assetByCapturedAtAndImageHash(){const e=await this.capturedAt_();if(null==e)return n(this,r,"f").throw("Cannot import, capturedAt is null"+h.InternalErrorFlag);if(y.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(D.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=y.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=D.AssetFile.query();return(0,E.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(T.secondMs,y.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,c.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)n(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(y.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void n(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const a=await this.dominantLabhashes();if((0,S.isNotEmpty)(a)){const t=e.localBoundaries({delta:4*s});if(null==t)n(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",a).orWhereIn("mode1",a).orWhereIn("mode2",a))));if(null!=e)return e}}const o=this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash));if(null!=o)return o;if(y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const r={};for(let e=0;e0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds)));const i=await this.firstSimilarAsset(D.AssetFile.ops().all(t));return null!=i&&n(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const s=(0,P.sortBy)(e.filter((e=>!this.rejectedSiblingIds.has(e.id)&&!this.rejectedAssetIds.has(e.assetId))),(e=>[(0,M.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of s)if(null!=e){await e.getNativePath();const i=D.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const s=(0,l.whyNotSameAsset)(t,e,i);if(null==s)return n(this,r,"f").info("Found sibling AssetFile",e),k.Asset.ops().findById(e.assetId);this.rejectedSiblingIds.add(e.id),n(this,r,"f").debug("Contemporary assetFile not similar: "+s,e?.uri)}}}t.AssetFileFinder=C,r=new WeakMap},34274:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult_=void 0;const u=i(19851),c=i(50213),d=i(73568),h=i(38835),f=i(95696),m=i(62105),p=i(74128),g=i(181),y=i(69589),v=i(28874),w=i(40958),b=i(22573),S=i(38639),P=i(59455),_=i(64526),T=i(19113),M=i(94710),E=i(3996),k=i(90901);t.importFileToResult_=async function(e){const t=_.Library.instanceRequired_();return(0,p.syncReport)().wrap_({path:e.path,from:"AssetFileImporter",fn_:()=>new D(f.PosixFile.for(e.path),t.assetFileRepository(),e).apply_()})};class D{constructor(e,t,i){r.add(this),this.file=e,this.repo=t,this.start=Date.now(),s.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else if(this.ctx.forceFilters||null==await this.prior()){const t=await(0,m.whyRejectFile)(this.file,(0,T.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,s,"f").throwIfAborted_();const i=await this.prior();if((0,w.isNotEmpty)(e)&&null!=i&&(l(this,s,"f").info("Deleting prior AssetFile",{rejected:e,prior:i}),i.delete(),this.ctx.skipAssetRepair?l(this,s,"f").info("Skipping asset repair",{assetId:i.assetId}):(l(this,s,"f").info("Scheduling asset repair",{assetId:i.assetId}),M.Task.addOne("repairAsset",{assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)}))),null!=i){const t=i.getAsset();null!=t?.deletedAt&&e.push("Asset is marked as deleted"),null!=t?.excludedAt&&e.push("Asset is marked as excluded")}if(l(this,s,"f").throwIfAborted_(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,b.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,s,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,s,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,s,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,r,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,s,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new E.AssetFileFinder(e,this.ctx),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=D,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(){l(this,s,"f").throwIfAborted_();const e=await l(this,s,"f").tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if((0,w.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,s,"f").throwIfAborted_();const t=await l(this,s,"f").tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,s,"f").throwIfAborted_();const i=await l(this,s,"f").tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return l(this,s,"f").throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return l(this,s,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,s,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,s,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;await l(this,s,"f").tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault}),l(this,s,"f").throwIfAborted_();try{o=await(0,k.assetPostUpsertTasks_)({asset:a,...this.ctx})}catch(e){e instanceof d.AbortError?l(this,s,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,s,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:r,assetFile:i,asset:a,uri:n,uris:[n,...(0,P.toA)(o?.newAssetFileUris)]}}},41844:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(50213),c=i(74128),d=i(81674),h=i(57902),f=i(4936),m=i(28874),p=i(47783),g=i(14245),y=i(67083),v=i(16170),w=i(54979),b=i(98604),S=i(40958),P=i(22573),_=i(98553),T=i(68708),M=i(89937),E=i(59455),k=i(54017),D=i(94710);t.mayCopyAssetsToLibrary=async function(){return m.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,u.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!0!==m.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,d.l)())return"no active subscription";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(m.Settings.libraryDir.valueOrDefault))return e+" already contained by "+m.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,m.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(M.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,E.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(k.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),D.Task.addOne("repairAsset",{assetId:t,forceSync:!0})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,_.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return a.addAssetFile(d),(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,p.readCapturedAt)(e),i=(0,f.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,p.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,p.readTags)(e);if(null!=i){if(m.Settings.writeGeolocationTagsToLibraryCopies.valueOrDefault){const e=(0,g.geolocationToXmp)(i);(0,T.isEmptyObj)(e)||await(0,p.writeTags_)(t,e)}return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred)}this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},90901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const r=i(50213),s=i(92434),n=i(73568),a=i(99331),o=i(39250),l=i(38835),u=i(57159),c=i(48604),d=i(66106),h=i(69589),f=i(40958),m=i(45599),p=i(23838),g=i(31586),y=i(64526),v=i(88224),w=i(43487),b=i(41844),S=i(68640),P=(0,m.defer)((()=>(0,r.mkLogger)("sync-file.AssetPostUpsertTasks"))),_=(0,m.defer)((()=>new o.LastOneInWins("Asset tasks")));async function T(e){const t=e,i=e,r=(0,g.toGt0)(t.asset?.id)??(0,g.toGt0)(i.assetId);if(null==r)throw new Error("assetPostUpsertTasks_(): unexpected null assetId"+l.InternalErrorFlag);const o=(0,h.forceContextOrSetting)(e),m=P().addContext(`.postUpsertAssetTasks_(Asset:${r})`);if(m.abortable=o.halt,o.skipPreviews&&o.skipAssetTagging)return void m.info("skipped (skipPreviews && skipAssetTagging)");const T=t.asset??w.Asset.ops().findById(r);if(null==T)return m.throw("unexpected null asset",{asset:T});try{return await _().enqueue({key:r,abortable:m.abortable,fn:()=>async function(e,t,i){const r=(0,h.forceContextOrSetting)(i),n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted_(),(0,f.isEmpty)(a)&&(await w.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,b.mayCopyAssetsToLibrary)())for(const[t,i]of(0,p.groupBy)(a,(e=>e.sha)).entries()){e.throwIfAborted_();try{for(const r of i)r.isInLibrary()&&await r.exists()&&e.debug("no-op for file SHA: already in library.",{sha:t,uri:r.uri});for(const e of i)if(await e.exists()){const t=await y.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,r);if(null!=t){o.newAssetFileUris.push(t.uri);continue}}}catch(r){e.warn("Failed to copy variation to library, but we'll try to continue",{sha:t,uris:i.map((e=>e.uri)),error:r})}}e.throwIfAborted_();const l=r.skipPreviews?void 0:await(0,S.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...r}),u=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?P().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,s.bestExistingAssetFile)(e.getAssetFiles())}(t,l);if(null==u)return e.throw("null primaryOrShownAssetFile_()",{asset:t});const m=await u.posixFile_();if(!0!==r.skipPreviews&&t.isVideo()){if(null==m)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});o.transcoded=null!=await(0,d.transcode_)(m,c.Previews.instance().ap(n).mp4(),{force:r.forceRebuildPreviews,halt:r.halt})}return e.throwIfAborted_(),t.markShownAndUpsert_(u),r.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,v.tagAndUpsertAsset_)(t),o}(m,T,{...e,...o})})}catch(e){if(e instanceof n.AbortError)return void m.warn("aborted, next caller will clean up my mess",{error:e});const t=[e];if(!(0,a.ending)()){m.error("failed, marking asset unshown",{error:e});try{T.markUnshownAndUpsert()}catch(e){m.error("failed to mark asset unshown",{upsertError:e}),t.push(e)}}throw new u.WrappedError("Failed to post-process assset "+T.id,{causes:t})}}t.assetPostUpsertTasks=function(e){try{return T(e)}catch(e){if(e instanceof n.AbortError)return void P().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=T},61989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset_=t.updateAsset=void 0;const r=i(48884),s=i(50213),n=i(45393),a=i(79184),o=i(79781),l=i(92434),u=i(56519),c=i(70417),d=i(69589),h=i(28874),f=i(40958),m=i(22573),p=i(38639),g=i(50357),y=i(43487),v=i(54017),w=i(3996),b=i(90901);async function S(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,r=(0,s.mkLogger)(`sync-file.UpdateAsset(${i})`);r.abortable=t.halt;const S=y.Asset.ops().findById(i);if(null==S)return r.throw("no such asset");const _=S.getAssetFiles({refresh:!0});if((0,f.isEmpty)(_))return r.warn("No asset files: deleting."),S.delete(),{asset:S,rejected:"Empty asset (no AssetFiles)"};const T=S.$clone(),M=S.getShown()?.$clone();for(const e of _)r.throwIfAborted_(),await e.upsertIfNeeded_(void 0,t);_.some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&S.clear(),await P(r,_);const E=(0,l.sortAssetFiles)(_),k=E?.[0];if((0,f.isEmpty)(E)||null==k)return r.warn("No existing files. Skipping for now."),S.markUnshownAndUpsert(),{asset:S,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!k.isVersionUpToDate())return r.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:k}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${k.id}, could not be updated. Un-showing Asset:${i}`};const D=await k.capturedAt();if(null==D)return r.warn("Best file failed to extract a captured-at",{bestAcceptedAF:k}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${k.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const x=new Set,[C,A]=await(0,u.partitionAsync)(E,(e=>(0,o.isSimilarAssetFile)(e,k)));if(r.throwIfAborted_(),(0,f.isNotEmpty)(A)){const e=await(0,a.aggregateAssetFiles)(A);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});x.add(e.id);for(const i of t)e.addAssetFile(i);v.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),r.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function F(e){return(0,f.uniq)(C.map((t=>t[e])))}const I=await Promise.all(C.map((e=>e.capturedAt()))),O=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,L=I.map((e=>e?.localBoundaries({delta:O}))),R=(0,c.min)(L.map((e=>e?.start)))??D.localBoundaries({delta:O})?.start,N=(0,c.max)(L.map((e=>e?.end)))??D.localBoundaries({delta:O})?.end,B=v.AssetFile.ops().all(v.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${k.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",F("sha")),null==R||null==N?r.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:R,endBoundary:N}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[R,N]),e.orWhereIn("AssetFile.meanHash",F("meanHash")).orWhereIn("AssetFile.diffHash",F("diffHash")).orWhereIn("AssetFile.dctHash",F("dctHash"))))));if(r.throwIfAborted_(),h.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const e=await k.posixFile();if(null==e)r.info("bestAcceptedAF has no posixFile, cannot expand query for fuzzy dates",{bestAcceptedAF:k});else{const i=new w.AssetFileFinder(e,t);for(const e of[...C,...B])i.rejectedAssetIds.add(e.assetId),i.rejectedAssetIds.add(e.id);let s=h.Settings.maxContemporaryAdoptionAssets.valueOrDefault;for(;--s>0;){r.throwIfAborted_();const e=await i.assetByCapturedAtAndImageHash();if(null==e){r.info("allowFuzzyDateImageHashMatches(): no additional assets found to adopt");break}if(r.info("allowFuzzyDateImageHashMatches(): found asset with similar image",{a:e}),null!=e){i.rejectedAssetIds.add(e.id);for(const t of e.getAssetFiles())r.info("found asset file by fuzzy date and image hash",{uri:t.uri,assetId:e.id}),B.push(t),i.rejectedAssetIds.add(t.id)}}}}r.info("asset file candidates for adoption: ",B.map((e=>e.posixPathFromGrandparent)));const j=[];for(const e of B){r.throwIfAborted_();try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,k)&&(r.info("adopting similar asset file",{af:e}),x.add(e.assetId),e.shown=!1,S.addAssetFile(e),e.upsert(),j.push(e))}catch(t){r.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}}r.info("fetched expansion",{retainAFs:C.map((e=>e.id)),rejectAFs:A.map((e=>e.id)),externalAssetFiles:B.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:j.map((e=>e.posixPathFromGrandparent))}),await P(r,[...C,...j]),t.skipPreviews&&t.skipAssetTagging?(r.info("skipping previews and tagging",t),S.upsert()):await(0,b.assetPostUpsertTasks_)({...t,asset:S});const z=!(0,g.eql)(T,S),V=!(0,g.eql)(M,S.getShown()),W=!(z||V||t.forceRebuildPreviews||t.forceSync);return r.tap({msg:"updateAsset() result",level:"info",result:{asset:S,assetIdsToUpdate:Array.from(x),assetFiles:S.assetFiles,skipped:W},meta:{ctx:t,assetChanged:z,primaryAssetFileChanged:V}})}async function P(e,t){const[i,s]=(0,r.partition)(t,(e=>e.isVersionUpToDate()));for(const t of s){e.throwIfAborted_();const r=i.find((e=>e.sha===t.sha));if(null!=r){e.info("backfilling",{sibling:r,dest:t});const i=await t.updateFromShaSibling_(r);null!=i&&i.upsert()}}}t.updateAsset=async function(e){try{const t=await S(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}},t.updateAsset_=S},93755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t.updateAssetFile_=t.updateAssetFile=void 0;const r=i(50213),s=i(92434),n=i(98314),a=i(74128),o=i(69589),l=i(87001),u=i(40958),c=i(22573),d=i(68708),h=i(43487),f=i(54017),m=i(94710);async function p(e){const t=Date.now(),i=e,s=e,n=s.af?.id??i.assetFileId,u=(0,r.mkLogger)(`updateAssetFile(${n})`),d=s.af??f.AssetFile.ops().findById(n);if(null==d)return u.throw("db record not found",{assetFileId:n});const h=await d.posixFile_(),p=(0,o.forceContextOrSetting)(e),v={id:n,assetFileId:n,path:h?.nativePath,uri:d?.uri};if(null==h){const e=["cannot resolve URI"];return(0,c.blank)(d.mountpoint)||e.push("is "+d.mountpoint+" mounted?"),(0,a.syncReport)().onProgress({path:d.uri,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:e.join(": "),state:a.SyncFileStates.skipped}),{...v,error:"file for URI not found"}}const w=await(h?.isDeletedUri(d.uri));if(null==w)return u.info("no-op: file URI points to an unmounted volume",v),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:((0,c.toNotBlank)(d.mountpoint)??"volume")+" is not currently mounted",state:a.SyncFileStates.skipped}),{...v,skipped:!0};const b=e.whyReject??await d.whyRejected();if(w||!(0,c.blank)(b)){const e={...v,rejected:b,deleted:w};return u.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:w?"file no longer exists":"rejected: "+b,state:a.SyncFileStates.deleted}),d.delete(),!0!==p.skipAssetRepair&&m.Task.addOne("repairAsset",{assetId:d.assetId}),e}const S=await h.uri_();if(!await(0,l.uriIsEquivalent)(S,d.uri)){const e=await g(d,S,p);if(null!=e)return{...v,...e}}return!p.forceSync&&await d.matchesFile()?(u.info("no-op: file already matches db record",v),d.touch(),{...v,skipped:!0}):{...v,...await y(d,p)}}async function g(e,t,i){const n=(0,r.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,u.uniq)([...(0,l.uriEncodingVariants)(e.uri),...(0,l.uriEncodingVariants)(t)]);n.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const o=f.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,u.isNotEmpty)(o)){n.warn("Found other AssetFiles with equivalent URIs.",{afIds:o.map((e=>e.id))});const t=[e,...o],r=(0,s.sortAssetFiles)(t);if((0,u.isEmpty)(r))return n.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,d.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const l=t.map((e=>e.id));for(const e of r)if(await e.exists()){f.AssetFile.dbl.runf((t=>t.whereIn("id",l.filter((t=>t!==e.id))).delete()));const r=y(e,i);return h.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,u.uniq)(t.map((e=>e.assetId)))))),r}}n.info("no-op, no duplicate URIs.")}async function y(e,t){const i=Date.now();return null!=await e.upsertIfNeeded_(void 0,t)&&h.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:await e.getNativePath(),elapsedMs:Date.now()-i,from:"updateAssetFileIfNeeded()",state:e.syncState??a.SyncFileStates.unknown}),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await p(e)}catch(t){return{id:e.assetFileId,...e,error:(0,n.errorToS)(t)}}},t.updateAssetFile_=p,t.handleAssetFileUriChange=g,t.updateAssetFileIfNeeded=y},68640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const r=i(99331),s=i(38835),n=i(48604),a=i(50213),o=i(69589),l=i(87001),u=i(40958),c=i(45599),d=i(50357),h=i(31586),f=i(68708),m=i(59455),p=i(43487),g=(0,c.defer)((()=>(0,a.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,m.toA)(e.assetFiles).find((e=>(0,h.gt0)(e.assetId)))?.assetId,i=(0,o.forceContextOrSetting)(e),a=g().addContext(".Asset:"+t);if(i.skipPreviews)return void a.warn("skipPreviews is true: no-op");if(!(0,h.gt0)(t))return a.throw("invalid assetId",{assetId:t});const c=e.asset??p.Asset.ops().findById(t);if(null==c)return a.throw("Asset:"+t+" not found");a.throwIfAborted_(i.halt);try{const e=await c.getExistingAssetFiles();if((0,u.isEmpty)(e))return void a.warn("no existing assetFiles",{asset:c});const r=n.Previews.instance().ap(t),o=await r.readInfo();a.throwIfAborted_(i.halt);const h=await(0,n.buildAssetPreviews_)({...i,assetId:t,assetFiles:e}),m=e.find((e=>e.id===h?.assetFileId))??e.find((e=>(0,l.uriIsEquivalent)(h?.uri,e.uri)));a.info("buildAssetPreviews_()",{result:h,primaryAssetFile:m});const p=await(m?.posixFile_());if(null==m||null==p||!0!==await(p?.exists()))return a.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:h,assetFiles:e.map((e=>(0,f.pick)(e,"id","uri"))),primaryAssetFile:m,primaryPosixFile:p});const g=(0,d.eql)(o,h),y=null==h||g;return{...h,noop:y}}catch(e){throw(0,r.ending)()||(a.warn("Failed to update previews. Un-showing asset "+t,{error:e}),c.markUnshownAndUpsert()),e}}},94019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(87290),o=i(34102),l=i(16287),u=i(45969),c=i(43334),d=i(28874),h=i(45200),f=i(69375),m=i(7014),p=i(41400),g=i(31586),y=i(92244),v=i(46832);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const w=(0,r.lazy)((async()=>{const e=[];for(const t of await(0,m.volumes)()){if(!0===t.ignorable||!1===t.ok||(c.isMac||(0,u.isDocker)())&&"/"===t.mountpoint||(0,f.isExcludedMountpoint)(t.mountpoint)||!(0,g.gt0)(t.size))continue;const i=await(0,v.toUriPath)(t.mountpoint,(0,h.nativePath2uri)(t.mountpoint,t));null!=i&&e.push(i)}return e}));async function b(){const e=[],i=[],r=d.Settings.argvScanPaths.toNotEmpty()??d.Settings.scanPaths.values;for(const s of r)if(await(0,l.isReadableDirectory)(s)){const r=await(0,v.toUriPath)(s);null==r?(e.push(s),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",s)):i.push(r)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",s);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,p.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];if(d.Settings.argvScanPaths.isNotEmpty()){for(const i of d.Settings.argvScanPaths.values){const r=await(0,v.toUriPath)(i);null!=r?e.push(r):(0,t.logger)().warn("pathsToSync(): Ignoring scanPath element: failed to create URI path",i)}return e}e.push(...(await b()).result),!0===d.Settings.scanAllDrives.value&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:d.Settings.libraryDir.valueOrDefault,originalsDir:d.Settings.originalsDir.value})));d.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),d.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},98622:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runTimeIsStale=t.SyncCron=void 0;const r=i(1708),s=i(17415),n=i(28874),a=i(41400),o=i(30301),l=i(31586);t.SyncCron=(0,o.lazy)((()=>{const e=n.Settings.syncCronTZ.valueOrDefault??(0,s.toValidIanaZone)(r.env.TZ);return n.Settings.syncCron.cron(null==e?void 0:{timezone:e})})),(0,a.later)((()=>{n.Settings.syncCron.watchLater((()=>t.SyncCron.unset())),n.Settings.syncCronTZ.watchLater((()=>t.SyncCron.unset()))})),t.runTimeIsStale=function(e){return null==e||(0,l.lte)((0,t.SyncCron)().nextRun(new Date(e))?.getTime(),Date.now())}},92244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.isStale=t.bestPathToSync=t.stalePathsToSync=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(23560),o=i(22277),l=i(87290),u=i(57902),c=i(28874),d=i(40958),h=i(76790),f=i(42659),m=i(75240),p=i(31586),g=i(20958),y=i(49796),v=i(94019),w=i(98622),b=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));t.nativePathBlocklist=new o.TTLSet(10*f.minuteMs);const S=10*f.minuteMs;async function P(){const e=await(0,v.pathsToSync)(),t=c.Settings.forceSync.valueOrDefault?[]:await y.Progress.times();return b().tap({msg:"pathsAndTimesToSync()",level:u.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}function _(e,t){return null==e.lastStartedAt||null==e.lastCompletedAt||(0,p.lte)(e.lastStartedAt,t)||(0,w.runTimeIsStale)(e.lastCompletedAt)}function T(){return g.Operation.getFirstPendingOp({name:g.OperationNames.forceRestartSync})}async function M(e){const t=T(),i=t?.createdAt,s=e.filter((e=>_(e,i)));if((0,d.isEmpty)(s))return(0,a.isSyncService)()&&t?.markCompleted(),b().tap({msg:"bestStable(): No stale paths to sync!",level:"info",result:void 0,meta:{arr:e,forceRestartOp:t}});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,p.gt)(e.lastUpdatedAt,Date.now()-10*f.minuteMs))return b().tap({msg:"bestStable(): returning most recently updated",level:"info",result:{...e,why:"recently updated"}})}const n=(0,r.leastBy)(s,(e=>[e.lastStartedAt??0,e.lastCompletedAt??0]));return b().tap({msg:"bestStable(): returning least-recently-started or least-recently-completed:",level:"info",result:null==n?void 0:{...n,why:"least recently started or completed"},meta:{stale:s}})}function E(e,t){return null==e.lastStartedAt?"new":null==e.lastCompletedAt?"todo":(0,p.gt)(e.lastUpdatedAt,Date.now()-f.minuteMs)?"syncing":_(e,t)?"stale":"synced"}function k(e){return null==e?void 0:new Date(e).toISOString()}function D(e){if(null==e)return;const t=Date.now()-e;return t<2*f.secondMs?"just now":(0,m.fmtDuration)(t)+" ago"}t.pathsAndTimesToSync=P,t.stalePathsToSync=async function(){const e=await P(),t=T(),i=t?.createdAt,r=e.filter((e=>_(e,i)));return(0,h.sortBy)(r,(e=>[null!=e.lastUpdatedAt&&Date.now()-Se.nativePath)),t=await M(e),i=(0,l.libraryOriginalsDirPosixFile)()?.nativePath,r=T()?.createdAt;return e.map((e=>({path:e.nativePath,library:i===e.nativePath,status:E(e,r),isNext:e.nativePath===t?.nativePath,lastStartedISO:k(e.lastStartedAt),lastStarted:D(e.lastStartedAt),lastCompletedISO:k(e.lastCompletedAt),lastCompleted:D(e.lastCompletedAt)})))}},46832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.posixFileToUriPath=t.toUriPath=void 0;const r=i(53265),s=i(45200),n=i(22573),a=i(68708),o=i(54993);async function l(e,t){if((0,a.isObject)(e)&&!(0,n.blank)(e.nativePath)&&!(0,n.blank)(e.uri))return e;const i=(0,r.resolve)((0,o.toS)(e)),l=await t??await(0,s.nativePath2uri)(i);return null==l?void 0:{nativePath:i,uri:l.toString()}}t.toUriPath=l,t.posixFileToUriPath=function(e){return l(e.nativePath,e.uriObject_())}},7656:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.DirectAssetCountForTagQuery=t.RecursiveAssetCountForTagQuery=t.nonLeafTagIds=void 0;const r=i(50213),s=i(56038),n=i(95704),a=i(38156),o=i(42659),l=i(45599),u=i(41400),c=i(31586),d=i(51926),h=(0,l.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function f(e){return e.prepare((0,d.compressWhitespace)("SELECT"," t1.id,"," count(t2.id) AS cnt","FROM"," Tag t1"," JOIN Tag t2 ON t1.id = t2.parentId","GROUP BY"," 1","HAVING"," cnt > 0")).pluck().all()}async function m(e,i=[]){const r=e.prepare(t.RecursiveAssetCountForTagQuery).pluck(),o=e.prepare(t.DirectAssetCountForTagQuery).pluck(),l=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId"),c=new Set(f(e)),d=new a.PushProgressObserver({op:"Rebuilding tag asset counts"},e.prepare("SELECT count(*) FROM Tag").pluck().get());await(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e){const e=!c.has(t);(0,s.timeSync)("db.rebuildTagAssetCounts("+(e?"leaf":"cte")+")",(()=>{const s=(e?o:r).get({tagId:t});l.run({tagId:t,assetCount:s,updatedAt:Date.now()}),d.incrProgress(),h().debug("_rebuildTagAssetCounts()",{isLeaf:e,whereClauses:i,tagId:t,assetCount:s})})),t%10==0&&(h().throwIfAborted_(),await(0,u.delay)(1))}}}),d.completed()}t.nonLeafTagIds=f,t.RecursiveAssetCountForTagQuery=(0,d.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.DirectAssetCountForTagQuery=(0,d.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," AssetTag"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," AssetTag.tagId = :tagId"," AND Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL;"),t.rebuildTagAssetCounts=async function(e,t=o.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>m(e,["assetCount IS NULL"]))),(0,c.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rm(e)))}},69032:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(1728),c=i(56038),d=i(34102),h=i(49076),f=i(69589),m=i(28874),p=i(42231),g=i(85087),y=i(98770),v=i(59107),w=i(63870),b=i(7014),S=i(22573),P=i(42659),_=i(41400),T=i(75240),M=i(31586),E=i(34666),k=i(51926),D=i(75020),x=i(54017),C=i(48723),A=i(98784),F=i(7656),I=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>A.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return I().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=((0,o.isTest)()?5:30)*P.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=I().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.throwIfAborted_(i?.halt),await L(),i.recountAllTags&&(s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)(),s.info("rebuilding tag asset counts..."),await(0,F.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0))}catch(e){I().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,M.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),I().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const L=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{I().info("updating tag mountpoints...");const e=C.Tag.findByPath([D.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await N(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function R(){t.tagFtsRebuild.unset(),L.unset()}async function N(e){if(null==e||2!==e.depth||!e._path.startsWith(D.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===D.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,T.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,_.later)((()=>{(0,d.ee)().on("clearCache",R),m.Settings.libraryDir.watchLater(R)})),t.fixFileRootTag=N,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,k.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,_.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},5379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(93944).install()}catch{}const r=i(69554),s=i(38790),n=i(53978),a=i(43380),o=i(5670),l=i(98392),u=i(31503),c=i(1739);!async function(){await new r.CLI(o.ServiceNames.web).add(l.ExposeArg,u.LogArgs,n.TimingArg,a.WriteSettingsArg,s.ColorArgs).parse(),new c.WebService}()},13808:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AboutRouter=void 0;const s=r(i(7252)),n=i(45255),a=i(81168),o=i(76596),l=i(51773),u=i(81674),c=i(28874),d=i(85087),h=i(7014),f=i(38639),m=i(42659),p=i(75240),g=i(55835),y=i(31586),v=i(20214),w=i(13538),b=i(83104),S=i(12168),P=i(77948),_=i(49796),T=i(92244),M=i(8283);t.AboutRouter=class{router(){return s.default.Router().get("/about",(0,l.wrap)("AboutRouter",this.about.bind(this)))}async about(e,t,i){const r=n.ShortCommandTimeoutMs+m.secondMs,s=await(0,w.thenOrTimeoutAs)({p:(0,P.systemInformation)(),timeoutMs:r,as:[{term:"System information",defn:"Failed to fetch system information: timeout after "+(0,o.fmtMs)(r),defnClass:"fail"}]}),l=await(0,w.thenOrTimeout)((0,v.thenMap)((0,h.volumes)(),(e=>e.map((e=>({ignorable:e.ignorable,mountpoint:e.mountpoint,uuid:e.uuid,volsha:(0,g.map)(e.uuid,d.volsha),size:(0,S.fmtBytes)(e.size,2),free:(0,S.fmtBytes)(e.available,2),full:(0,y.gt0)(c.Settings.minDiskFreeGb.valueOrDefault)&&(0,y.lt)(e.available,c.Settings.minDiskFreeGb.valueOrDefault*S.GB),label:e.label,remote:!0===e.remote?{remote:e.remote,host:e.remoteHost,share:e.remoteShare}:void 0}))).filter((e=>!0!==e.ignorable)))),r);l===b.Timeout&&s.push({term:"volumes() timeout",defn:"Failed to fetch volume metadata: timeout after "+(0,o.fmtMs)(r),defnClass:"fail"});const E=null==_.Progress.db()?void 0:await(0,w.thenOrTimeout)((0,T.syncPathsForUI)(),n.ShortCommandTimeoutMs);E===b.Timeout&&s.push({term:"sync paths timeout",defn:"Failed to fetch sync path metadata: timeout after "+(0,o.fmtMs)(n.ShortCommandTimeoutMs),defnClass:"fail"});const k=await(0,u.b)();return(0,M.render)(e,t,"about",{title:"About PhotoStructure",systemInfo:s,volumes:Array.isArray(l)?l.map((e=>({...e,mountpoint:(0,a.wbrPath)(e.mountpoint)}))):void 0,syncPaths:Array.isArray(E)?E:void 0,subTier:await(0,u.t)(),subTrial:(0,f.isTrue)(k?.l?.trial),subEmail:k?.l?.sub,subExpiresInDuration:(0,g.map)(k?.l?.exp,(e=>(0,p.fmtDuration)(e.getTime()-Date.now(),1))),subExpiresAt:(0,g.map)(k?.l?.exp,m.fmtIsoDate)})}}},76020:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AdminPostRouter=void 0;const s=r(i(7252)),n=i(45608),a=i(34102),o=i(51773),l=i(40749),u=i(62327),c=i(65238),d=i(18454),h=i(2858),f=i(7014),m=i(42659),p=i(41400),g=i(98553),y=i(98401),v=i(14611),w=i(53791),b=i(35758),S=2*m.secondMs;t.AdminPostRouter=class{router(){return s.default.Router().post("/admin/restart",(0,o.wrap)("AdminHealthRouter:restart",this.restart.bind(this))).post("/admin/bounce",(0,o.wrap)("AdminHealthRouter:bounce",this.bounce.bind(this))).post("/admin/refresh/:id",(0,o.wrap)("AdminHealthRouter:refresh",this.refresh.bind(this))).post("/admin/clear-library",(0,o.wrap)("AdminHealthRouter:clear-library",this.clearLibrary.bind(this))).post("/admin/clear-caches",(0,o.wrap)("AdminHealthRouter:clear-caches",this.clearCaches.bind(this))).post("/admin/recheck-tools",(0,o.wrap)("AdminHealthRouter:recheck-tools",this.recheckTools.bind(this))).post("/admin/repair-db",(0,o.wrap)("AdminHealthRouter:repair-db",this.repairDb_.bind(this))).post("/admin/run-maintenance",(0,o.wrap)("AdminHealthRouter:repair-db",this.maintenance_.bind(this))).post("/admin/shutdown",(0,o.wrap)("AdminHealthRouter:shutdown",this.shutdown.bind(this)))}async restart(e,t,i){await(0,v.restartLibrary_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Restarted library...",timeout:S},url:"/splash"})}async refresh(e,t,i){const r=e.params.id,s=d.HealthCheck.findById(r);if(null==s)throw new Error("No health check found with id="+(0,g.stringify)(r));const n=await s.refresh();(0,u.sendRedirectionToast)({response:t,toast:{text:"Health check "+r+": "+n.level,timeout:S},url:"/health"})}async bounce(e,t,i){(0,p.delay)(m.secondMs).then((()=>(0,n.exit)({reason:"/bounce requested by "+e.ip,status:0}))),(0,u.sendRedirectionToast)({response:t,toast:{text:"Restarting webserver...",timeout:15*m.secondMs},url:"/splash"})}async clearLibrary(e,t,i){await(0,h.clearLibraryDirSetting)(),(0,v.restartLibrary_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Prior library was unset. Restarting...",timeout:S},url:"/splash"})}async clearCaches(e,t,i){await(0,f.clearVolumesCache)({deleteFileCache:!0}),await(0,c.clearReaddirCaches)(),(0,a.ee)().emit("clearCache"),"/health"===(0,l.referrer)(e)?(0,u.sendRedirectionToast)({response:t,toast:{text:"Cleared caches.",timeout:S},url:"/health"}):(0,u.sendServerToast)({response:t,toast:{text:"Cleared caches."},reload:!0})}async recheckTools(e,t,i){(0,a.ee)().emit("clearToolCache"),(0,u.sendRedirectionToast)({response:t,toast:{text:"Cleared tool caches.",timeout:S},url:"/health"})}async repairDb_(e,t,i){(0,b.dbModelRepair)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Started library database repair...",timeout:S},url:"/splash"})}async maintenance_(e,t,i){(0,y.cleanup_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Started library maintenance jobs...",timeout:S},url:"/"})}async shutdown(e,t,i){(0,p.delay)(S).then((()=>(0,w.shutdown)("requested by "+e.ip))),(0,u.sendServerToast)({response:t,toast:{text:"Shutdown initiated."}})}}},13831:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiAssetRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(97352),o=i(56519),l=i(4867),u=i(76596),c=i(57159),d=i(51773),h=i(62327),f=i(86580),m=i(81674),p=i(72308),g=i(45969),y=i(28874),v=i(40958),w=i(76790),b=i(75761),S=i(38639),P=i(55835),_=i(31586),T=i(68708),M=i(21605),E=i(41942),k=i(75020),D=i(54993),x=i(43487),C=i(37094),A=i(69853),F=i(48723),I=i(94710),O=i(73407),L=(0,n.mkLogger)("web.ApiAssetRouter"),R=["hidden","excludedAt","deletedAt"];t.ApiAssetRouter=class{constructor(e){this.previews=e}wrapApi(e,t){return(i,r,s)=>(0,h.wrapWithToast)({response:r,f:async()=>{const s=(0,_.toGt0)(i.params.assetId);if(null==s)return r.sendStatus(400);const n=await(0,o.thenMapOr)(x.Asset.ops().findById(s,{shown:1}),(e=>t(i,s,e)),(()=>this.onMissingAsset(i,s)));if(L.debug(e,{result:n}),null!=n)return(0,d.jsonOrRedirect)(n,r);throw new c.WrappedError("Asset "+s+" wasn't found",{retriable:!1,doNotSend:!0,fatal:!1})}})}router(){return s.default.Router().get("/api/asset/:assetId/info",this.wrapApi("ApiAssetRouter.assetInfo",this.assetInfo.bind(this))).get("/api/asset/:assetId/streams",this.wrapApi("ApiAssetRouter.assetInfo",this.assetStreams.bind(this))).get("/api/asset/:assetId",this.wrapApi("ApiAssetRouter.asset",this.asset.bind(this))).put("/api/asset/:assetId",this.wrapApi("ApiAssetRouter.save",this.save.bind(this))).put("/api/asset/:assetId/resync",this.wrapApi("ApiAssetRouter.resync",this.resync.bind(this)))}async assetInfo(e,t,i){const r=i.getAssetFiles(),s=i.getShown(),n=(0,P.map)(s,(e=>e.getNativePath())),a=(0,p.isLocalhost)(e.ip)&&!(0,g.isDocker)();if(y.Settings.resyncAssetOnVisit.valueOrDefault&&I.Task.addOne("repairAsset",{assetId:t,forceSync:!1,forceRebuildPreviews:!1}),null==s||null==n)return void L.error("no shown AssetFile found for "+t,{asset:i,shown:s,shownPathP:n});L.debug("assetInfo()",{assetId:t,shown:s,shownPathP:n,ip:e.ip,showOpenFile:a});const l=i.getTags(),c=await(0,o.mapAsync)({name:"api.assetInfo.tags",arr:l,f:e=>e.toApiTag()}),h=await(0,o.mapAsync)({name:"api.assetInfo.files",arr:r,f:e=>e.toApi(this.previews,s.sha)});return(0,w.sortByInPlace)(h,(e=>[!e.shown,!e.exists,e.nativePath])),{assetId:t,capturedAtLocale:s.capturedAtLocale((0,d.requestLang)(e)),...(0,T.pick)(s,"mimetype","focalLength","iso","aperture","shutterSpeed"),durationHMS:(0,P.map)(s.durationMs,u.durationHMS),fps:s.fps,files:h,tags:c,showOpenFile:a}}async onMissingAsset(e,t,i){const r="next"===e.query.from;L.info("onMissingAsset()",{query:(0,T.entries)(e.query),params:(0,T.entries)(e.params),assetId:t});const s=(0,_.toInt)(String(e.query.priorAssetId)),n=(0,P.mapOr)(i,(e=>e.id),(()=>s));if(null==n)return void L.warn("onMissingAsset(): no context asset available");const l=await(0,o.thenMapOr)(i,(e=>e.capturedAtLocal),(()=>x.Asset.dbl.pluckFirstf((e=>e.select("capturedAtLocal").where({id:n})))));let u=x.Asset.shownUnhidden(x.Asset.query().select("id").limit(1).whereNotIn("id",(0,v.compact)([t,s])));u=r?u.andWhere("capturedAtLocal","<",l).orderBy("capturedAtLocal","desc"):u.andWhere("capturedAtLocal",">",l).orderBy("capturedAtLocal","asc");const c=x.Asset.dbl.pluckFirst(u);return L.warn("Asset redirect",{fromAssetId:n,priorAssetId:s,fromTime:l,toAsset:c}),(0,a.mapGt0)(c,(t=>(0,E.mkReplace)((0,b.assetUrl)({assetId:t,params:[e.query,e.params]}),{text:`Asset ${n} is no longer available.`,type:"info"})))}async asset(e,t,i){const r=i.getShown();if(null==r)return L.error("no shown AssetFile found for "+t+", disabling (for now)."),i.upsert({shown:!1}),L.error("Asset un-shown."),I.Task.addOne("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),this.onMissingAsset(e,t,i);i.getBeforeAfterId();const s={...i.partialSimpleAsset(),name:r.basename,width:r.width,height:r.height,rotation:r.rotation??0,capturedAtLocale:r.capturedAtLocale((0,d.requestLang)(e)),aspectRatio:(0,f.aspectRatio)(r),durationHMS:(0,P.map)(r.durationMs,u.durationHMS),downloadable:await r.originalDownloadable({brief:!0}),contextTag:await i.whenApiTag(),beforeAssetId:i.beforeId,afterAssetId:i.afterId};if(r.isVideo){const r=await i.videoSources();return await i.getExistingAssetFiles(),(0,v.isEmpty)(r)?(L.warn("no existing files for "+t+", trying to repair, but redirecting user now."),I.Task.addOne("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),this.onMissingAsset(e,t,i)):{...s,videoAttrs:i.videoAttrs(),videoSources:r}}return{...s,imgAttrs:await i.fitAttrs(this.previews)}}async assetStreams(e,t,i){const r=(0,_.toInt)((0,D.toS)(e.query.limit),{defaultValue:k.BeforeAfterStreamLimit}),s=i.getStreams(r);return L.tap({msg:"assetStreams",result:{assetId:t,assetStreams:await(0,o.mapAsync)({name:"assetStreams",arr:s,f:e=>e.toApi()})}})}async save(e,t,i){if(await(0,m.l)())return L.warn("save(): disabled"),{showTryPlusToast:!0};const r=i.isActive(),s={hidden:(0,S.toBoolean)(e.body.hidden),excludedAt:(0,P.map)((0,S.toBoolean)(e.body.excluded),(e=>e?Date.now():null)),deletedAt:(0,P.map)((0,S.toBoolean)(e.body.deleted),(e=>e?Date.now():null)),rating:(0,P.map)((0,S.toBoolean)(e.body.liked),(e=>e?y.Settings.likeRating.valueOrDefault:null))};if(!(0,v.isEmpty)((0,T.keys)(s))){L.info("save()",{obj:s,body:e.body}),C.AssetRevision.insert(...(0,T.entries)((0,T.omit)(s,...R)).map((([e,r])=>({assetId:t,field:e,priorValue:i?.[e],newValue:r}))));const n=null===s.deleted?null:null!=s.deleted?-1:s.rating;void 0!==n&&await(0,O.writeAssetTags_)(t,{Rating:n}),i.upsert(s),i.isActive()!==r&&F.Tag.deltaAssetCountAndAncestors(i.tagIds(),i.isActive()?1:-1)}const n=i.partialSimpleAsset(),a=(0,M.normalizeRotation)((0,_.toInt)(e.body.rotation));return null!=a&&0!==a&&(await(0,A.setAssetRotation_)(t,a,this.previews),n.rotation=a),n}async resync(e,t){return x.Asset.dbl.runf((e=>e.where({id:t}).update({version:0}))),await(0,l.thenOrTimeoutError)({p:I.Task.addOne("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}).donePromise(),timeoutMs:y.Settings.taskTimeoutMs.valueOrDefault}),{v:x.Asset.dbl.pluckFirstf((e=>e.where({id:t}).select("updateCount")))}}}},53881:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSearchRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(68178),l=i(28874),u=i(7014),c=i(40958),d=i(22573),h=i(38639),f=i(31586),m=i(12168),p=i(32790),g=i(54993),y=i(43487),v=i(48722),w=i(43786),b=i(7573),S=i(33693),P=i(23523),_=(0,n.mkLogger)("web.ApiSearchRouter");t.ApiSearchRouter=class{router(){return s.default.Router().get("/api/search",(0,a.wrap)("ApiSearchRouter.get",this.get.bind(this)))}async get(e,t){const i=(0,g.toStr)(e.query.q," "),r=p.AssetQueryOrderByColumns.validOrElse((0,g.toStr)(e.query.orderby,","),p.AssetQueryOrderByColumns.capturedAt),s=(0,h.isTrue)(e.query.asc),n={column:r===p.AssetQueryOrderByColumns.capturedAt?"Asset.capturedAtLocal":"Asset.updatedAt",order:s?"asc":"desc"},a=(0,f.toGt0)((0,g.toStr)(e.query.offset));if(_.debug("get()",{q:i,orderBy:n,offset:a}),(0,d.blank)(i))return t.json({});const T=(0,b.normalizeQuery)((0,S.parseQuery_)(i));let M=(0,P.defaultAssetQuery)().select({id:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"}).orderBy([n,"Asset.id"]).limit(512);const E=(0,w.findTerm)(T,(e=>"fs"===e.ns))?await(0,u.mountpointToVolsha)():void 0;null!=a&&(M=M.offset(a));const k=null==a?await async function(e,t,i){const r=await function(e,t){return y.Asset.dbl.pluckFirst((0,P.queryToSql)(e,(0,P.defaultAssetQuery)().countDistinct("Asset.id"),t))}(t,i),{emptyTrashQuery:s,removeAssetsQuery:n}=function(e){const t=1===(0,w.flatTerms)(e).length,i=t&&(0,w.isTrueTerm)((0,w.findTerm)(e,(e=>e.ns===b.AssetTermBoolNs.deleted)));return{emptyTrashQuery:i,removeAssetsQuery:!i&&t&&(0,w.isTrueTerm)((0,w.findTerm)(e,(e=>e.ns===b.AssetTermBoolNs.excluded)))}}(t);if(0===r)return{description:s?"No assets are marked for trash.":n?"No assets are marked for removal.":"No matching assets."};const a="Found "+(0,m.plur)(r,"asset");if(!s&&!n)return{description:a};const u=await function(e,t){return y.Asset.dbl.pluckFirst((0,P.queryToSql)(e,(0,P.defaultAssetQuery)().join("AssetFile","AssetFile.assetId","Asset.id").countDistinct("AssetFile.id"),t))}(t,i),c=a+" ("+(0,m.plur)(u,"file")+")",d={expectedAssetFileCount:String(u)};if(s){const t="Empty trash";return{description:c,buttonText:t,buttonIcon:"trash_forever",promptTitle:t,refreshOnActivation:!0,...l.Settings.enableEmptyTrash.valueOrDefault?{buttonClass:"error",buttonTitle:null,prompt:[`

    Are you sure you want to permanently delete ${(0,m.plur)(u,"file")} comprising ${(0,m.plur)(r,"asset")}?

    `,"","

    To proceed, please enter the number of files that will be deleted:

    "].join("\n"),formAction:(0,o.requestedUri)(e).with({path:"/api/system/empty-trash",query:d}).toString()}:{buttonClass:"disabled",buttonTitle:'This is disabled. See the "enableEmptyTrash" setting.',prompt:null,formAction:null}}}if(n){const t="Remove assets";return{description:c,buttonText:t,buttonIcon:"warning",promptTitle:t,refreshOnActivation:!0,...l.Settings.enableRemoveAssets.valueOrDefault?{buttonClass:"warning",buttonTitle:null,prompt:["

    Are you sure you want to remove "+(0,m.plur)(r,"asset")+" (comprised of "+(0,m.plur)(u,"file")+") from your library?

    ","","

    To proceed, please enter the number of files that will be removed:

    "].join("\n"),formAction:(0,o.requestedUri)(e).with({path:"/api/system/remove-assets",query:d}).toString()}:{buttonClass:"disabled",buttonTitle:'This is disabled. See the "enableRemoveAssets" setting.',prompt:null,formAction:null}}}throw new Error("internal error (mkBanner)")}(e,T,E):void 0;M=(0,P.queryToSql)(T,M,E).distinct();const D=(0,c.compact)(y.Asset.dbl.all(M).map(v.toAssetId)),x={query:{q:i,normalized:(0,w.queryToString)(T,w.NormieQuerySymbols),orderBy:r,asc:s,offset:a??0,nextOffset:D.length<512?void 0:D.length+(a??0)},banner:k,assetIds:D};return _.debug(".get("+(0,w.queryToString)(T)+") result",x),t.json(x)}validatePostRequest(e,t){return _.debug("validatePostRequest",{req_query:e.query,req_body:e.body}),this.validatePost((0,g.toStr)(e.query.expectedAssetFileCount," "),e.body.answer,t)}async validatePost(e,t,i){_.debug("validatePost",{expectedAssetFileCount:e,answer:t});const r=(0,f.toInt)((0,g.toS)(e));if(null==r)return"Canceled: the expected number of files was missing from the request.";const s=(0,f.toInt)(t);if(null==s)return"Canceled: missing user input.";const n=await y.Asset.dbl.pluckFirst(i().join("AssetFile","Asset.id","AssetFile.assetId").countDistinct("AssetFile.id"));return r!==n?`Canceled: the number of files has changed from ${(0,m.fmt)(r)} to ${(0,m.fmt)(n)}. Reload this page and try again.`:s!==r?`Canceled: you entered "${t??""}" and we expected "${r}".`:{assetFileCount:n}}}},21598:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSplashRouter=void 0;const a=i(18405),o=i(18454),l=i(37805),u=i(42659),c=i(62220),d={loading:"⏳ Loading...",welcome:"👋 Welcome!",ready:"✅ Ready",failed:"⚠️ Something's not right. Gathering details..."};class h extends a.ServerSentEventsRouter{constructor(){super("/sse/splash"),r.set(this,null)}runStateEvent(e=o.HealthCheck.runState()){const t=e===c.RunStates.loading;return t&&this.streams.length>0?n(this,r,s(this,r,"f")??setInterval((()=>{this.writeToStreams(this.runStateEvent())}),u.secondMs),"f"):null!=s(this,r,"f")&&(clearInterval(s(this,r,"f")),n(this,r,null,"f")),this.logger.tap({msg:"runStateEvent()",level:"warn",result:t?{event:"msg",data:o.HealthCheck.loadingMsg()??d[e]}:{event:"settled",data:d[e]},meta:{state:e}})}firstEvents(){return[{event:"version",data:l.version},this.runStateEvent()]}}t.ApiSplashRouter=h,r=new WeakMap},49296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSystemRouter=void 0;const s=r(i(7252)),n=i(19851),a=i(50213),o=i(97352),l=i(71567),u=i(51773),c=i(62327),d=i(74128),h=i(28874),f=i(69385),m=i(40958),p=i(38639),g=i(25763),y=i(31586),v=i(12168),w=i(54993),b=i(53791),S=i(43487),P=i(20958),_=i(94710),T=i(22968),M=(0,n.lazy)((()=>(0,a.mkLogger)("web.ApiSystemRouter")));function E(e){return async(t,i,r)=>{const s=(0,w.toStr)(t.query.expectedAssetFileCount," "),n=(0,o.extractInt)(t.body.answer);M().debug("validatePostCounts",{expectedAssetFileCount:s,answer:n});const a=(0,y.toInt)((0,w.toS)(s));if(null==a)return(0,c.sendWarningServerToast)({response:i,toast:{text:"Canceled",details:"The expected number of files was missing from the request"}});const l=(0,y.toInt)(n);if(null==l)return(0,c.sendWarningServerToast)({response:i,toast:{text:"Canceled",details:"User answer was missing"}});const u=await async function(e,t){var i,r;return M().tap({msg:`countAssetFiles(${t})`,result:(i=e.locals)[r="countAssetFiles-"+t]??(i[r]=await S.Asset.dbl.pluckFirst(S.Asset.shownRemovable(t).join("AssetFile","Asset.id","AssetFile.assetId").countDistinct("AssetFile.id")))})}(i,e);return a!==u?(0,c.sendWarningServerToast)({response:i,toast:{text:"Canceled",details:`The number of files has changed from ${(0,v.fmt)(a)} to ${(0,v.fmt)(u)}. Reload this page and try again.`}}):l!==a?(0,c.sendWarningServerToast)({response:i,toast:{text:"Canceled",details:`You entered "${n??""}" and we expected "${a}".`}}):r()}}async function k(e){M().warn("setting "+e+" to unshown...");const t=Date.now(),i={shown:0,updatedAt:t};i[e]=t;const r=S.Asset.dbl.run(S.Asset.shownRemovable(e).update(i)),s=_.Task.addOne(function(e){if("deletedAt"===e)return _.TaskNames.applyDeleted;if("excludedAt"===e)return _.TaskNames.applyExcluded;throw new Error("invalid RemovableColumn "+e)}(e),{createdAt:t});M().warn("updated assets and scheduled task",{result:r,obj:i,task:s})}async function D(e,t){return await k("deletedAt"),(0,c.sendServerToast)({response:t,reload:!0,toast:{text:"Emptied trash",details:"Assets have been removed from your library and files will be deleted in the background.",type:"success"}})}async function x(e,t){return await k("excludedAt"),(0,c.sendServerToast)({response:t,reload:!0,toast:{text:"Assets have been removed from your library.",type:"success"}})}t.ApiSystemRouter=class{constructor(e){this.openFileService=e,this.getState=(e,t)=>{const i={paused:(0,f.isPaused)()};return t.json(i)},this.getHasEmail=(e,t)=>{t.json({hasEmail:(0,g.isEmailMaybe)(h.Settings.email.value)})},this.postSystem=async(e,t)=>{const i=e.body,r=[];M().info("post()",{body:e.body}),(0,p.mapTrue)(i.pause,(()=>{(0,f.pause)(!0),r.push("Sync was paused")})),(0,p.mapTrue)(i.resume,(()=>{(0,f.pause)(!1),r.push("Sync was resumed")})),await(0,p.mapTrue)(i.restartSync,(async()=>{l.StdoutWrite.restartSync(),r.push("Sync restart was requested")})),await(0,p.mapTrue)(i.forceRestartSync,(async()=>{P.Operation.markOpCompleted({name:"forceRestartSync"},{value:"canceled (force-restarted)"}),P.Operation.ensurePendingOp({name:"forceRestartSync"}),l.StdoutWrite.restartSync(),r.push("Sync force-restart was requested")})),await(0,p.mapTrue)(i.rebuildLibrary,(async()=>{(0,T.forceRebuildLibraryLater)(),l.StdoutWrite.restartSync(),r.push("Library rebuild was requested")})),(0,p.mapTrue)(i.showSyncReports,(()=>{this.openFileService((0,d.syncReportReadme)()),r.push("Opened your sync reports directory")})),(0,p.mapTrue)(i.shutdown,(async()=>{const t="requested by "+e.ip;(0,b.shutdown)(t),r.push("Shutdown "+t)})),(0,m.isNotEmpty)(r)?(0,c.sendServerToast)({response:t,toast:{type:"info",text:r.join(". ")}}):(t.status(400),(0,c.sendServerToast)({response:t,toast:{text:"Nothing requested.",type:"warning"}}))}}router(){return s.default.Router().get("/api/system/state",(0,u.wrap)("state",this.getState)).get("/api/system/hasEmail",(0,u.wrap)("hasEmail",this.getHasEmail)).post("/api/system",((e,t)=>(0,c.wrapWithToast)({response:t,f:()=>this.postSystem(e,t)}))).post("/api/system/empty-trash",c.requirePlus,(0,c.requireEnabled)(h.Settings.enableEmptyTrash),E("deletedAt"),D).post("/api/system/remove-assets",c.requirePlus,(0,c.requireEnabled)(h.Settings.enableRemoveAssets),E("excludedAt"),x)}}},19583:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiTagRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(97352),o=i(45255),l=i(76596),u=i(51773),c=i(62327),d=i(28874),h=i(34238),f=i(40958),m=i(31586),p=i(41942),g=i(75020),y=i(27776),v=i(54993),w=i(64526),b=i(43487),S=i(48723),P=(0,n.mkLogger)("ApiTagRouter");function _({name:e,f:t}){return(0,u.wrap)(e,(async(i,r)=>{const s=(0,m.toInt)(i.params.tagId),n=(0,u.extractTagPath)(i.path).map(h.percentDecode),a=(0,u.getSeed)(i),o=(0,u.getFit)(i),l=(0,f.mapNotEmptyOr)(n,(e=>S.Tag.findByIdOrPath(s,e)),(()=>S.Tag.root())),d=null==l?void 0:t(i,l,{tagId:l.id,tagPath:l.path,seed:a,fit:o});return P.debug(e,{result:d,tagPath:n,seed:a,url:i.url}),null==l||null==d?(0,c.send404Toast)({text:"Failed to find tag "+s??n.join("/"),response:r}):(0,u.jsonOrRedirect)(d,r)}))}t.ApiTagRouter=class{router(){return s.default.Router().get("/api/tag*",_({name:"ApiTagRouter.tagGallery",f:this.tagGallery.bind(this)})).get((0,g.nextAssetsUrl)(":tagId",{}),_({name:"ApiTagRouter.tagAssets",f:this.tagAssets.bind(this)})).get((0,g.nextChildTagsUrl)(":tagId",{}),_({name:"ApiTagRouter.childTags",f:this.childTags.bind(this)}))}tagGallery(e,t,i){if(P.debug("tagGallery()",{tag:t}),null==i.seed)return P.debug("tagGallery(): no seed, redirecting..."),(0,p.mkReplace)((0,y.mkTagFullPath)(t.path,e.query));if(d.Settings.fastForwardEmptyTags.valueOrDefault){const i=t.firstNonInterstitialTagId();if(i!==t.id){const t=S.Tag.findById(i);if(null!=t)return(0,p.mkReplace)((0,y.mkTagFullPath)(t.path,e.query),{text:"Skipping to first non-empty child tag…",uuid:"redirect-to-tag",onlyShowUuidOnce:!0,type:"info"})}}const r={fullPath:e.originalUrl,fit:i.fit,...t.toApiTag(),...this.childTags(e,t,i),...this.tagAssets(e,t)};return 0===t.id&&0===b.Asset.shownCount()&&((0,l.isRecentMs)(w.Library.instance()?.start,o.ShortCommandTimeoutMs)?r.startingUp=!0:r.emptyLibrary=!0),r}childTags(e,t,i){const r=(0,m.toInt)((0,v.toS)(e.query.offset))??0,s=(0,m.toInt)((0,v.toS)(e.query.limit))??4;P.debug("childTags() got ",{thisOffset:r,limit:s,query:e.query});const n={tagId:t.id,offset:r,limit:s,seed:i.seed};n.limit=(0,a.firstGt0)(n.limit,4);const o=t.getChildrenCount(),l=0===o?[]:t.getPagedChildren(n);P.debug("childTags()",{crit:n,childTagCount:o,children:l});const u=l.length+r,c=u{const t=e.getRelatedAssetIds({seed:i.seed+e.id,limit:g.ThumbsPerSample});return(0,f.isNotEmpty)(t)?{...e.toApiTag(),assetIds:t}:void 0})));return P.tap({msg:"childTags result",result:{tagId:t.id,childTags:d,childTagCount:o,nextChildTags:c},meta:{nextOffset:u}})}tagAssets(e,t){const i={offset:(0,m.toInt)((0,v.toS)(e.query.offset),{defaultValue:0})},r=t.getPagedAssetIds(i),s=r.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetOpenGraph=void 0;const r=i(48884),s=i(48604),n=i(28874),a=i(16170),o=i(31586);t.getAssetOpenGraph=async function(e,t){if(null==(t=(0,o.toGt0)(t))||!(0,o.gt0)(n.Settings.openGraphTargetWidth.valueOrDefault))return;const i=s.Previews.instance()?.ap(t);if(null==i)return;const l=await i.readInfo();if(null==l)return;const u=[];if((0,a.isVideoMimeType)(l.mimetype)){u.push({property:"og:video",content:e.with({path:"/video/"+t}).toString()});const r=await i.mp4().exists()?"video/mp4":l.mimetype;u.push({property:"og:video:type",content:r},{property:"og:video:width",content:l.width.toString()},{property:"og:video:height",content:l.height.toString()})}else{const s=(await i.widths("fit")??[]).map((e=>({width:e,path:"/img/"+t+"/fit/"+e})));"image/jpeg"===l.mimetype&&s.push({width:l.width,path:"/img/"+t+"/actual"});const a=(0,r.leastBy)(s,(e=>Math.abs(e.width-n.Settings.openGraphTargetWidth.valueOrDefault)));if(null!=a){u.push({property:"og:image",content:e.with({path:a.path}).toString()},{property:"og:image:type",content:"image/jpeg"},{property:"og:image:width",content:a.width.toString()});const t=a.width/(l.width/l.height);(0,o.gt0)(t)&&u.push({property:"og:image:height",content:Math.round(t).toString()})}}return u}},18848:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cspHandler=void 0;const s=r(i(2525)),n=i(19851),a=i(50213),o=i(28874),l=i(49586),u=i(40958),c=(0,n.lazy)((()=>(0,a.mkLogger)("web.WebSecurity")));t.cspHandler=function(e,t,i){(e.secure||(0,l.isHttpsRequest)(e.headers))&&null==o.Settings.upgradeInsecureRequests.value&&(c().warn('Secure https request detected: setting "upgradeInsecureRequests" to true.'),o.Settings.upgradeInsecureRequests.tmpValue=!0);const r=(0,u.compactBlanks)(["'self'",o.Settings.cspDirective.valueOrDefault]),n=(0,u.compactBlanks)(["'self'","'strict-dynamic'",`'nonce-${t.locals.cspNonce}'`,o.Settings.cspDirective.valueOrDefault]);s.default.contentSecurityPolicy({directives:{defaultSrc:["'self'"],scriptSrc:n,styleSrc:r,baseUri:r,formAction:["'self'","https://account.photostructure.com"],objectSrc:["'none'"],upgradeInsecureRequests:o.Settings.upgradeInsecureRequests.valueOrDefault?[]:null},reportOnly:o.Settings.cspReportOnly.valueOrDefault})(e,t,i)}},81100:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requestAssetRepair=t.ImgActualRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(62327),l=i(52121),u=i(55835),c=i(31586),d=i(68708),h=i(43487),f=i(54017),m=i(94710),p=(0,n.mkLogger)("web.ImgActualRouter");function g(e){return m.Task.addOne("repairAsset",{assetId:e,forceSync:!0,forceRebuildPreviews:!0})}t.ImgActualRouter=class{constructor(e){this.previews=e}router(){return s.default.Router().get("/img/:assetId/:assetFileId/actual(.*)?",(0,a.wrap)("ImgActualRouter.assetImg",this.assetFileImg.bind(this))).get("/img/:assetId/actual(.*)?",(0,a.wrap)("ImgActualRouter.assetImg",this.assetImg.bind(this))).get("/dl/:assetId/:assetFileId",(0,a.wrap)("ImgActualRouter.assetFileImg",this.assetFileImg.bind(this)))}async assetImg(e,t){const i=(0,c.toInt)(e.params.assetId);if(!(0,c.gt0)(i))return(0,o.sendServerToast)({response:t,toast:{text:"Missing assetId in request",type:"warning"},httpStatusCode:400});const r=f.AssetFile.ops().findOneBy({assetId:i,shown:1});return null==r?(p.info("Unknown assetId",e.originalUrl),this.repairAssetLaterAndSendPreview(i,e,t)):this.sendAssetFile(e,t,r)}async assetFileImg(e,t){const i=(0,c.toInt)(e.params.assetId);if(!(0,c.gt0)(i))return(0,o.send404Toast)({response:t,text:'Request was missing "assetId"',httpStatusCode:400});const r=(0,c.toInt)(e.params.assetFileId);if(!(0,c.gt0)(r))return(0,o.send404Toast)({response:t,text:'Request was missing "assetFileId"',httpStatusCode:400});const s=f.AssetFile.ops().findOneBy({id:r,assetId:i});return null==s?(0,o.send404Toast)({response:t,text:"Bad request: no such asset file "+r}):this.sendAssetFile(e,t,s)}async sendAssetFile(e,t,i){const r=i.assetId,s=await i.posixFile_(),n=e.path.split("/").includes("dl")||(0,a.truthyQuery)(e,"dl");if(null==s||await s.isEmpty())return n?(0,o.send404Toast)({response:t,text:"Asset file "+i.uri+" was missing"}):this.repairAssetLaterAndSendPreview(r,e,t);if(n)return p.info("Sending download",{assetId:r,af:i,nativePath:s.nativePath}),t.download(s.nativePath,s.base);const c=e.headers["user-agent"],h=await(0,l.prepFileForBrowser)({nativePath:s.nativePath,userAgent:c,...(0,d.pick)(i,"width","height","sha","mimetype","rotation","mimetype")});return null==h?(p.warn("cannot send file (null result from prepFileForBrowser)",{assetId:r,af:i}),g(r),(0,o.send404Toast)({response:t,text:`Failed to get browser-friendly preview for Asset ${r}.`,details:"I'll try to fix it."})):(p.info("sendAssetFile(): sending supported file: "+h),t.sendFile(h,(e=>(0,u.map)(e,(e=>p.warn("failed to send file",{error:e,assetId:r,af:i}))))))}async repairAssetLaterAndSendPreview(e,t,i){g(e);const r=await this.previews.ap(e).largestFileForReducer("fit");null!=r?i.sendFile(r.nativePath):(h.Asset.ops().upsertOne({id:e,shown:!1}),(0,o.send404Toast)({response:i,text:`Asset ${e} is missing preview images.`,details:"I'll try to fix it, but it will be hidden for now."}))}},t.requestAssetRepair=g},4950:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ImgRouter=void 0;const s=r(i(7252)),n=i(76760),a=r(i(9288)),o=i(48884),l=i(50213),u=i(45255),c=i(81168),d=i(37628),h=i(51773),f=i(13940),m=i(28874),p=i(16170),g=i(34238),y=i(51140),v=i(11371),w=i(55835),b=i(31586),S=i(54993),P=i(54017),_=(0,l.mkLogger)("web.ImgRouter");t.ImgRouter=class{constructor(e){this.previews=e}router(){const e=(0,h.wrap)("ImgRouter",this.streamImage.bind(this));return s.default.Router().get("/img/:assetId/:reducer/:width",e)}async streamImage(e,t,i){const r=await this.getFileFromRequest(e,t);if(null!=r){if("setHeader"in t&&(0,b.gt)(r.width,500)){const e=P.AssetFile.dbl.pluckFirstf((e=>e.where({assetId:r.assetId,shown:1}).select("uri")))??"/asset-"+r.assetId+"."+r.file.ext,i=(0,w.map)(e,g.uriToBasename);if(_.debug("streamImage(): AssetFile URI",{shownUri:e,basename:i}),null!=i)try{t.setHeader("X-basename",(0,c.ensureSuffixIgnoreCase)(i,"."+r.file.ext))}catch(e){_.warn("streamImage(): setHeader error",{error:e})}else _.warn("streamImage(): failed to extract basename",{result:r})}return t.sendFile(r.file.nativePath)}}async getFileFromRequest(e,t){const i=e.params,r=(0,b.toInt)(i.assetId),s=v.ReducerNames.getCI(i.reducer)??"fit",l=(0,b.toInt)(i.width);if(null==r||null==s&&null==l)return _.warn("getFileFromRequest(): bad request",{assetId:r,reducer:s,width:l}),void t.sendStatus(y.HttpStatus.BadRequest);const h=this.previews.ap(r),g=h.fileForWidth(s,l);if(await g.exists())return{assetId:r,width:l,file:g};if(m.Settings.placeholderThumbs.valueOrDefault){const e=(0,d.stringShaToBuffer)((0,S.toS)(r)).toString("hex").slice(0,6),t=await(0,f.imageCacheDir_)();if(null==t)return;const i=t.join((0,c.splitEvery)(e,3).join(n.sep)+"-8w.png");return await i.applyIfEmpty_({fn_:t=>(0,a.default)({create:{width:8,height:8,channels:3,background:"#"+e}}).png().toFile(t.nativePath),timeoutMs:u.ShortCommandTimeoutMs}),{assetId:r,width:8,file:i}}const w=await h.widths(s)??[],P=await h.readInfo(),T=(0,p.isImageMimeType)(P?.mimetype)&&(0,p.isMimeTypeSupportedByBrowser)(P?.mimetype)?P?.width:void 0,M=(0,o.leastBy)([...w,T],(e=>(0,b.gt0)(e)&&Math.abs(l-e)));return null==M||M===l?(_.warn("Missing file, and no other widths found",{path:g.nativePath,assetId:r,reducer:s,requestedwidth:l,existingWidth:M}),void t.sendStatus(y.HttpStatus.NotFound)):M===T?(_.debug("redirecting to image actual",{assetId:r,reducer:s,width:l,f:g,existingWidth:M}),void t.redirect(["/img",r,"actual"].join("/"))):(_.debug("replacing requested width",{assetId:r,reducer:s,width:l,f:g,existingWidth:M}),void t.redirect(["/img",r,s,M].join("/")))}}},76018:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.siteManifest=t.ManifestRouter=void 0;const s=r(i(7252)),n=i(19851),a=i(50213),o=i(51773),l=i(68178),u=i(70854),c=i(28874),d=(0,n.lazy)((()=>(0,a.mkLogger)("web.ManifestRouter")));async function h({requestUri:e,id:t}){return{id:t??"com.photostructure",name:"PhotoStructure",start_url:e.with({path:c.Settings.defaultHomepagePath.valueOrDefault,query:null,fragment:null}).toString(),display:"fullscreen",icons:[{src:"/192.png",sizes:"192x192",type:"image/png"},{src:"/512.png",sizes:"512x512",type:"image/png"},{src:"/images/logo-gradient.svg",sizes:"any",type:"image/svg+xml"}],theme_color:"#845BAC",background_color:"#845BAC"}}t.ManifestRouter=class{router(){return s.default.Router().get("/site.webmanifest",(0,o.wrap)("SiteManifest",this.siteManifest.bind(this)))}async siteManifest(e,t,i){const r=await((0,u.LibraryUIDStore)()?.readUid_().catch((()=>{}))),s=(0,l.requestedUri)(e,{protocol:"http",host:c.Settings.hostname.value}),n=await h({id:r,requestUri:s});d().debug("siteManifest",n),t.type("application/manifest+json").json(n)}},t.siteManifest=h},16271:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAssetFileRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(72308),l=i(31586),u=i(54017),c=(0,n.mkLogger)("web.OpenAssetFileRouter");t.OpenAssetFileRouter=class{constructor(e){this.openFileService=e}router(){return s.default.Router().get("/api/openAssetFile/:assetFileId",(0,a.wrap)("OpenAssetFileRouter.assetFile",this.assetFile.bind(this)))}async assetFile(e,t){if(c.info("assetFile(): got request",{url:e.originalUrl,ip:e.ip}),!(0,o.isLocalhost)(e.ip))return c.info("Non-localhost request",{url:e.originalUrl,ip:e.ip}),t.sendStatus(400);const i=(0,l.toInt)(e.params.assetFileId);if(!(0,l.gt0)(i))return c.info("Missing assetFileId",e.originalUrl),t.sendStatus(400);const r=u.AssetFile.ops().findOneBy({id:i});if(null==r)return c.info("Invalid assetFileId",e.originalUrl),t.sendStatus(400);const s=await r.posixFile_();return null==s||await s.clear().notExists()?(c.info("File not found",{url:e.originalUrl,af:r,file:s}),t.sendStatus(400)):(c.info("Requesting openFileService("+s.nativePath+")...",{url:e.originalUrl,ip:e.ip}),this.openFileService(s.nativePath),t.sendStatus(204))}}},24255:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PingRouter=void 0;const s=r(i(7252)),n=i(99331),a=i(51140);t.PingRouter=class{router(){return s.default.Router().get("/ping",((e,t)=>t.sendStatus((0,n.ending)()?a.HttpStatus.ServiceUnavailable:a.HttpStatus.OK)))}}},39761:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getPlansLicense=t.getPlansBilling=t.getPlansActivate=t.getPlansPick=t.PlansRouter=void 0;const s=r(i(7252)),n=i(19851),a=i(50213),o=i(88158),l=i(37805),u=i(51773),c=i(68178),d=i(33603),h=i(70114),f=i(28874),m=i(22573),p=i(42659),g=i(59455),y=(0,n.lazy)((()=>(0,a.mkLogger)("web.PlansRouter")));async function v(e,t){return await S({req:e,res:t,remotePath:"/plans/pick"})}async function w(e,t){return await S({req:e,res:t,remotePath:"/",params:{skipIndex:!0}})}async function b(e,t){return await S({req:e,res:t,remotePath:"/"})}async function S({req:e,res:t,remotePath:i,params:r={}}){const s=(0,c.requestedUri)(e).with({path:"/plans/license"}),n=await(0,d.sids)({timeoutMs:4*p.secondMs}),a=new URL("https://account.photostructure.com"+i);return a.searchParams.append("version",l.version),a.searchParams.append("uids",n.join(",")),(0,m.mapNotBlank)(f.Settings.coupon.value,(e=>a.searchParams.append("coupon",e))),a.searchParams.append("redirectToLibraryUrl",s.toString()),(0,o.mapEntries)(r,((e,t)=>a.searchParams.append(e,t))),y().info("GET /plans/pick",{redirectToLibraryUrl:s.toString()}),t.redirect(a.toString())}async function P(e,t){try{(0,m.mapNotBlankOr)(e.query.license,(async e=>{await(0,h.writeLicense)(e,3*p.secondMs),y().info("getPlansLicense(): Saved new license",e)}),(()=>{y().info("getPlansLicense(): no license in request",e.originalUrl)}))}catch(t){y().error("getPlansLicense(): Failed to save license",{err:t,url:e.originalUrl})}const i=(0,m.notBlankOr)((0,g.toA)(e.query.then)[0],"/settings");y().info("getPlansLicense(): redirecting to "+i),t.redirect(i)}t.PlansRouter=class{router(){return s.default.Router().get("/plans/pick",(0,u.wrap)("GET /plans/pick",v)).get("/plans/activate",(0,u.wrap)("GET /plans/activate",w)).get("/plans/billing",(0,u.wrap)("GET /plans/billing",b)).get("/plans/license",(0,u.wrap)("GET /plans/license",P))}},t.getPlansPick=v,t.getPlansActivate=w,t.getPlansBilling=b,t.getPlansLicense=P},37380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressProvider=void 0;const r=i(58587),s=i(1708),n=i(89788),a=i(54557),o=i(19851),l=i(50213),u=i(56519),c=i(18454),d=i(43334),h=i(69385),f=i(40958),m=i(38639),p=i(42659),g=i(96249),y=i(49769),v=i(12236),w=i(54993),b=i(43487),S=i(54017),P=i(49796),_=(0,o.lazy)((()=>(0,l.mkLogger)("web.ProgressWithAssets")));t.ProgressProvider=class{constructor(e=10){this.maxLen=e,this.priorRecentAssets=new a.FifoCache(15,15*p.secondMs),this.testProgressStatesByVolume=new Map}async updates(){return(0,u.thenMap)(this.states(),(e=>({states:e})))}async states(){if((0,h.isPaused)())return[{volume:"⏸",state:"paused",hed:"Paused",dek:["Processing is paused. Resume via the navigation menu"+(d.isElectron?" or the system tray menu":"")+"."],recentAssetIds:[]}];const e=await c.HealthCheck.errorResults();if((0,f.isNotEmpty)(e))return _().warn("health check is failing",{errors:e}),[{volume:"⚠️",state:"paused",hed:"Health checks failed. Click for details.",dek:(0,f.uniq)((0,g.flatten)(e.map((e=>e.msg)))),recentAssetIds:[]}];const t=this.recentProgress();return _().debug("recentProgressWithAssets()",t),(0,f.isEmpty)(t)&&(0,m.isTrue)(s.env.TEST_PROGRESS)?this.testProgress():t}recentProgress(){const e=P.Progress.ops().allf((e=>e.where("updatedAt",">",Date.now()-p.minuteMs).whereNotNull("state").orderBy("volume")));(0,f.filterInPlace)(e,(e=>!(!(0,r.pidExists)(e.pid)&&"done"!==e.state&&(_().warn("Incomplete progress is from a dead process",{progress:e}),e.upsert({state:null}),1))));const t=[],i=new Set;for(const r of e){const e="done"===r.state,s=r.toSyncState(),n=this.priorRecentAssets.get((0,w.toS)(r.id))??[];if(!e){const e=((0,v.noRecentAssetIdsProgress)(s)?[]:S.AssetFile.recentAssetIdsByUriRoot((0,v.isRebuildProgress)(s)?void 0:s.uri,p.minuteMs,this.maxLen+i.size)).filter((e=>!i.has(e)&&!n.includes(e)));(0,f.isNotEmpty)(n)&&e.length>=this.maxLen&&e.splice(0,this.maxLen-1),n.unshift(...e),n.length=this.maxLen,this.priorRecentAssets.set((0,w.toS)(r.id),n);for(const e of n)i.add(e)}t.push({...s,recentAssetIds:n})}return t}async testAssetIds(e){const t=(0,y.getOrSet)(this.testProgressStatesByVolume,e,(()=>new n.BoundedList(this.maxLen))),i=b.Asset.dbl.pluckFirstf((e=>b.Asset.shownUnhidden(e).select("id").orderByRaw("random()").first()));return null!=i&&t.push(i),t.toA()}async testProgress(){const e=Math.round(Date.now()/(30*p.secondMs))%3,t=(d.isWin?["C:","D:","E:"]:["/","/home/bob/pictures","/mnt/nas"])[e];return[{volume:t,state:"processing",hed:"Processing, about 32 minutes remaining",dek:["Processing C:\\Users\\mrm\\Pictures\\20161214-pixel\\DCIM\\Camera\\IMG_20160903_090736.jpg","Processed 445 images and videos. 1,386 remain to be processed."],completePct:40,incompletePct:25,scanningPct:35,recentAssetIds:await this.testAssetIds(t)}]}}},8283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.render=void 0;const r=i(72993),s=i(19851),n=i(50213),a=i(7282),o=i(81674),l=i(72308),u=i(45969),c=i(43334),d=i(28874),h=i(69385),f=i(38639),m=i(13538),p=i(2322),g=i(48723),y=(0,s.lazy)((()=>(0,n.mkLogger)("web.PugHelpers")));t.render=async function(e,t,i,s={}){const n=e.headers["user-agent"];t.setHeader("Feature-Policy","autoplay 'self'");const v=[],w=!0===n?.toLowerCase().includes("electron")&&(0,l.isLocalhost)(e.ip)||(0,f.isTrue)(e.query.electron);w&&(v.push("electron"),c.isMac?v.push("mac"):c.isWin?v.push("win"):c.isLinux&&v.push("linux")),(0,a.isDev)()&&v.push("is-dev"),(0,p.isChrome)(n)?v.push("chrome"):(0,p.isSafari)(n)?v.push("safari"):(0,p.isFirefox)(n)&&v.push("firefox"),(0,p.isIphone)(n)?v.push("iphone"):(0,p.isIpad)(n)&&v.push("ipad"),(0,h.isPaused)()&&v.push("is-paused"),(0,l.isLocalhost)(e.ip)&&!(0,u.isDocker)()&&v.push("is-localhost");try{!0===await(0,m.thenOrTimeout)((0,o.p)(),250)&&v.push("is-plus")}catch{}d.Settings.enableArchive.valueOrDefault&&v.push("enable-archive"),d.Settings.enableDelete.valueOrDefault&&v.push("enable-delete"),d.Settings.enableRemove.valueOrDefault&&v.push("enable-remove");const b={bodyClass:v.join(" "),isDocker:(0,u.isDocker)(),isElectron:w,isDev:a.isDev,nonce:t.locals.cspNonce,hasEmail:d.Settings.email.hasValue(),...s};y().debug("render()",{ua:n,template:i,options:b,headers:e.headers}),t.render(i,{rootTags:null==g.Tag.db()?void 0:g.Tag.roots(),title:(0,r.AppName)(),...b})}},8446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SSEHealthRouter=void 0;const r=i(22911),s=i(18405),n=i(18454),a=i(72901),o={event:"done",data:{done:!0}};function l(e){return null==e?void 0:{event:"result",data:e}}class u extends s.ServerSentEventsRouter{constructor(){super("/sse/health")}firstEvents(e,t){return this.sendResults(t),[]}async sendResults(e){const t=[],i=[];i.push(n.HealthCheck.summary());for(const e of n.HealthCheck.all()){const r=e.toResultSync();i.push(r),("pending"===r.level||e.isStale())&&t.push(e)}e.write((0,a.mkEventStream)(...i.map(l))),this.logger.debug("sendResults (sync)",{pending:t.map((e=>e.id)),resolved:i.map((e=>e.id))});for await(const i of r.Deferred.toAsyncIterable(t.map((e=>e.result())))){const t=(0,a.mkEventStream)(l(i),l(n.HealthCheck.summary()));this.logger.debug("sendResults (async)",{result:i,chunk:t}),e.write(t)}e.write((0,a.mkEventStream)(l(n.HealthCheck.summary()),o),(()=>this.endStream(e)))}}t.SSEHealthRouter=u},44143:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SSEProgressRouter=void 0;const a=i(18405),o=i(72901),l=i(51140),u=i(40958),c=i(94383),d=i(76386);class h extends a.ServerSentEventsRouter{constructor(e){super(c.ApiProgressPath),r.add(this),this.updatesProvider=e}firstEvents(){return setTimeout((()=>n(this,r,"m",s).call(this)),250),[]}router(){return super.router().patch(d.ApiProgressPatchPath,this.onSendUpdates.bind(this))}async onSendUpdates(e,t){try{return this.logger.debug("Received PATCH, sending updates.",{remotePort:e.socket?.remotePort}),await n(this,r,"m",s).call(this),t.sendStatus(l.HttpStatus.OK)}catch(e){return this.logger.warn("onSendUpdates(): Failed to send updates",{error:e}),t.sendStatus(l.HttpStatus.InternalServerError)}}}t.SSEProgressRouter=h,r=new WeakSet,s=async function(){if(!this.ended&&!(0,u.isEmpty)(this.streams))try{const e=await this.updatesProvider.updates();if(null==e)return void this.logger.warn("Failed to fetch updates");if(this.ended)return;const t=(0,o.mkEventStream)({data:e});(0,u.filterInPlace)(this.streams,(e=>!e.destroyed));for(const e of this.streams)try{e.write(t)}catch{}}catch(e){this.logger.warn("Failed to send updates",e)}}},59898:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsRouter=void 0;const s=r(i(7252)),n=i(51168),a=i(76760),o=i(50213),l=i(7282),u=i(45255),c=i(71567),d=i(87290),h=i(55939),f=i(34102),m=i(51773),p=i(83278),g=i(66106),y=i(81674),v=i(43205),w=i(45969),b=i(43334),S=i(4936),P=i(28874),_=i(2858),T=i(40958),M=i(22573),E=i(38639),k=i(42659),D=i(75240),x=i(98553),C=i(55835),A=i(68708),F=i(13538),I=i(12168),O=i(59455),L=i(54993),R=i(78339),N=i(57064),B=i(8283),j=(0,o.mkLogger)("web.SettingsRouter");t.SettingsRouter=class{constructor(e=d.libraryDirPosixFile,t=R.librarySettings,i=N.suggestedLibraryDirs){this.libraryDir=e,this.settings=t,this.libraryDirSuggester=i}router(){return s.default.Router().get("/setting",((e,t)=>t.redirect("/settings"))).get("/settings",(0,m.wrap)("GET /settings",this.get.bind(this))).post("/settings",(0,m.wrap)("POST /settings",this.post.bind(this)))}async get(e,t){const{err:i,libraryDir:r}=e.body;let s;try{await(0,_.readSettings)(),s=await(0,F.thenOrTimeoutError)(this.requestSettings(e),P.Settings.statTimeoutMs.valueOrDefault)}catch(e){return j.warn("readSettings() took too long. Redirecting to the health check page.",e),t.redirect("/health")}try{return await(0,F.thenOrTimeoutError)(this.renderSettings(e,t,s,r,i),P.Settings.statTimeoutMs.valueOrDefault)}catch(e){return j.warn("requestSettings() took too long. Redirecting to the health check page.",e),t.redirect("/health")}}async renderSettings(e,t,i,r,s){(0,f.ee)().emit("clearCache");let o=await(0,F.thenOrTimeoutMaybe)(this.libraryDirSuggester(),u.ShortCommandTimeoutMs)??[];if(!/choose a different directory/i.test((0,L.toS)(s))){const e=await N.SuggestedLibraryDir.for(r);null!=e&&o.unshift(e)}(0,T.isEmpty)(o)&&(o=void 0);const c=this.libraryDir();(0,M.blank)(s)&&(0,w.isDocker)()&&(null==c||await c.isNotDirectory())&&(s=`PS_LIBRARY_DIR, ${c?.nativePath??"/ps/library"}, doesn't exist: please add it as a bind mount.`);const d=await(0,F.thenOrTimeoutMaybe)((0,g.getVideoToolDetails_)((0,l.isProd)()?void 0:e.query),u.ShortCommandTimeoutMs),A=await(0,h.picturesDir)(),O=await(0,y.b)(),R={err:s,...i,autoUpdateCheck:i.autoUpdateCheck??!0,allowUserAgent:i.allowUserAgent??!0,reportErrors:i.reportErrors??!0,welcome:(0,C.mapOr)((0,l.isProd)()?void 0:e.query.welcome,E.isTrue,(()=>!(0,_.libraryHasSettings)())),title:null==c?"Welcome!":"Settings",videoToolDetails:d,picturesPath:A,jsonScanPaths:(0,C.map)(P.Settings.scanPaths.value,x.stringify),delimiter:a.delimiter,exampleScanPath:[A,b.isWin?"D:\\PHOTOS":b.isMac?"/Volumes/External HD/Pictures":"/mnt/nas/homes/photos"].join(a.delimiter),currentLibraryDir:(0,C.map)(c,(e=>e.nativePath)),minFreeAvailable:(0,I.fmtBytes)(P.Settings.minDiskFreeGb.valueOrDefault*I.GB),suggestedLibraryDirs:o,samplePath:(0,S.pathToLibraryAsset)(n.DateTime.now(),p.BaseFile.for("photo.jpg")).join(a.sep),subTier:await(0,y.t)(),subTrial:(0,E.isTrue)(O?.l?.trial),subEmail:O?.l?.sub,subExpiresInDuration:(0,C.map)(O?.l?.exp,(e=>(0,D.fmtDuration)(e.getTime()-Date.now(),1))),subExpiresAt:(0,C.map)(O?.l?.exp,k.fmtIsoDate),userAgent:await(0,v.systemUserAgent)()};j.info("rendering settings",R),(0,m.disableCache)(t),await(0,B.render)(e,t,"settings",R)}async post(e,t){const i=e.body,r=(0,M.toNotBlank)("libraryDirCustom"===i.libraryDirRadio?i.libraryDir:i.libraryDirRadio),s=i=>this.renderSettings(e,t,u,r,i),n=r??P.Settings.libraryDir.valueOrDefault;if((0,M.blank)(n))return s("Please choose a directory for your library.");const o=(0,a.resolve)(n),u=this.requestSettings(e);j.info("POST",{libraryDir:o,settings:u,body:i}),(0,l.isTest)()&&(0,c.stdoutWrite)({post:i,settings:u,method:e.method,libraryDir:o});try{const e=await(0,R.saveLibrarySettings)(o,u);if("error"in e)return j.info("error saving library settings",{result:e}),s(e.error);j.info("saved library settings. Waiting for bookkeeping to finish...",e),await e.ready,j.info("ready. Redirecting to /splash...",e)}catch(e){return s(e)}return t.redirect("/splash")}requestSettings(e){const{scan:t,scanPath:i,copyAssets:r,autoUpdateCheck:s,allowUserAgent:n,reportErrors:a}=e.body,o={...this.settings()};return(0,M.notBlank)(t)&&(o.scanAllDrives="scanAllDrives"===t,o.scanPath=(0,T.compactBlanks)((0,O.toA)(i))),(0,M.notBlank)(r)&&(o.copyAssets="copyEnabled"===r),o.allowUserAgent=(0,E.toBoolean)(n),o.autoUpdateCheck=(0,E.toBoolean)(s),o.reportErrors=(0,E.toBoolean)(a),j.tap({msg:"requestSettings()",level:"info",result:o,meta:{req_body:(0,A.pick)(e.body,"scan","scanPath","copyAssets","autoUpdateCheck","allowUserAgent","reportErrors")}})}}},77203:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SpaRouter=void 0;const s=r(i(7252)),n=i(51773),a=i(68178),o=i(75710),l=i(8283);t.SpaRouter=class{router(){const e=(0,n.wrap)("SpaRouter",this.get.bind(this));return s.default.Router().get("/tag*",e).get("/asset/:assetId",(0,n.wrap)("SpaRouter.Asset",this.getAsset.bind(this))).get("/search",e)}async getAsset(e,t,i){const r=await(0,o.getAssetOpenGraph)((0,a.requestedUri)(e),e.params.assetId);return(0,l.render)(e,t,"app",null==r?{}:{meta:r})}get(e,t,i){if(!e.path?.startsWith("/tag")||null!=(0,n.getSeedOrRedirect)(e,t))return(0,l.render)(e,t,"app",{})}}},2314:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.VideoRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(40958),l=i(55835),u=i(31586),c=i(54017),d=(0,n.mkLogger)("web.VideoRouter");t.VideoRouter=class{constructor(e){this.previews=e}router(){return s.default.Router().get("/video/:assetId",(0,a.wrap)("VideoRouter",this.videoImage.bind(this)))}async videoImage(e,t,i){const r=e.params,s=(0,u.toInt)(r.assetId);if(!(0,u.gt0)(s))return d.warn("Malformed request (missing assetId)",{params:e.params}),t.sendStatus(400);const n=this.previews.ap(s).mp4();if(await n.exists())return d.info("streaming transcoded video",n),t.sendFile(n.nativePath);const a=c.AssetFile.ops().findBy({assetId:s,shown:1});if((0,o.isEmpty)(a))return d.warn("Malformed request (bad assetId)",{params:e.params}),t.sendStatus(400);const h=a[0],f=await(0,l.map)(h,(e=>e.posixFile_()));return null!=f&&h.isVideo&&await f.exists()?t.sendFile(f.nativePath):(d.warn("Shown assetFile isn't a video",h),t.sendStatus(400))}}},1739:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebService=void 0;const s=r(i(7252)),n=r(i(2525)),a=r(i(77598)),o=r(i(1708)),l=i(19851),u=i(50213),c=i(97352),d=i(71567),h=i(99331),f=i(45608),m=i(56519),p=i(38835),g=i(57159),y=i(41293),v=i(27821),w=i(78147),b=i(68178),S=i(43394),P=i(62327),_=i(30576),T=i(95696),M=i(43899),E=i(8797),k=i(63664),D=i(18454),x=i(21525),C=i(45657),A=i(33603),F=i(39471),I=i(29325),O=i(28874),L=i(2858),R=i(63870),N=i(7014),B=i(55111),j=i(51140),z=i(93493),V=i(41400),W=i(55835),U=i(62220),q=i(13538),H=i(459),G=i(27776),$=i(64526),J=i(18449),K=i(95629),Y=i(37158),X=i(8400),Z=i(13808),Q=i(76020),ee=i(13831),te=i(53881),ie=i(21598),re=i(49296),se=i(19583),ne=i(18848),ae=i(81100),oe=i(4950),le=i(76018),ue=i(16271),ce=i(24255),de=i(39761),he=i(37380),fe=i(8446),me=i(44143),pe=i(59898),ge=i(77203),ye=i(2314),ve=i(98949),we=i(43268);function be(e,t){t.endsWith(".js")&&e.setHeader("Content-Type","application/javascript")}const Se=(0,u.mkLogger)("web.WebService"),Pe=e=>(0,E.showFileInFolder)(T.PosixFile.for(e));t.WebService=class{constructor(){this.setup=(0,l.lazy)((async()=>{if(Se.debug("setup(): started"),o.default.on("SIGPIPE",(()=>{})),O.Settings.libraryDir.watchLater((()=>ke.unset())),await(0,m.rejected)(this.service.ready))return void Se.error("setup(): failed, service.ready was rejected");await(0,z.setupShimDelegates)();const e=this.app;if(e.use((new w.RequestLogger).router),e.use(((e,t,i)=>{t.locals.cspNonce=a.default.randomBytes(16).toString("hex"),i()})),O.Settings.trustProxy.hasValue()){const t=O.Settings.trustProxy.value,i="true"===t||"false"!==t&&(0,c.mapGte0Or)(t,(e=>e),t);e.set("trust proxy",i),Se.info("trust proxy set",{value:i})}if(e.use(P.expressErrorHandlerWithToast),(0,J.sentryEnabled)())try{e.use(i(16436).Handlers.requestHandler())}catch(e){Se.warn("Failed to initialize Sentry requestHandler",{error:e})}if(O.Settings.disabledHelmetMiddleware.valueOrDefault.includes(B.HelmetPlugins.all))Se.warn("DANGER: disabledHelmetMiddleware includes 'all': not enabling any Helmet middleware.");else{O.Settings.disabledHelmetMiddleware.valueOrDefault.includes(B.HelmetPlugins.contentSecurityPolicy)||e.use(ne.cspHandler);const t={contentSecurityPolicy:!1};for(const e of O.Settings.disabledHelmetMiddleware.valueOrDefault.filter((e=>e!==B.HelmetPlugins.all)))t[e]=!1;e.use((0,n.default)(t))}e.use(b.addXSettingsHandler),e.use(we.json()),e.use(we.urlencoded({extended:!1}));const t=M.ProjectPath.Public(),r=M.ProjectPath.Views();if(Se.info("setup()",{libraryDir:O.Settings.libraryDir.valueOrDefault,publicRoot:t,viewsRoot:r}),L.libraryHasSettings.watch((()=>e.set("etag",(0,L.libraryHasSettings)()))),e.set("views",r),e.set("view engine","pug"),e.use((new ce.PingRouter).router()),e.use((new y.ApiHealthRouter).router()),e.use((0,_.viewRouter)({path:"/splash",view:"splash"})),e.use((new ie.ApiSplashRouter).router()),e.use((0,_.viewRouter)({path:"/health",view:"health"})),e.use((new fe.SSEHealthRouter).router()),e.use((new Q.AdminPostRouter).router()),e.get("/status",((e,t)=>t.redirect("/health"))),e.use(await(0,S.serveStaticGz)(t)),e.use(s.default.static(t,{setHeaders:be})),e.use((new Z.AboutRouter).router()),e.use((new ve.WelcomeRouter).router()),e.use((new de.PlansRouter).router()),e.use(Ee()),(0,I.isPacked)()||(e.use("/die",((e,t)=>{Se.info("/die was requested",{url:e.originalUrl}),t.sendStatus(j.HttpStatus.Accepted),(0,f.exit)({reason:"/die",status:1})})),e.use("/test-sentry",((e,t)=>{(0,K.sendToSentry)(new g.WrappedError("test message sent to sentry at "+new Date)),t.sendStatus(j.HttpStatus.Accepted)}))),e.use(((e,t,i)=>(0,h.ending)()?(Se.info("ending(): returning 500",{requestUri:(0,b.requestedUri)(e)}),t.sendStatus(500)):function(){const e=D.HealthCheck.runState();switch(e){case U.RunStates.loading:return _e();case U.RunStates.welcome:return Me();case U.RunStates.ready:return ke()??ke.refresh()??Te();case U.RunStates.failed:return Te();default:throw new H.UnreachableCaseError(e)}}()(e,t,i))),(0,J.sentryEnabled)())try{e.use(i(16436).Handlers.errorHandler())}catch(e){Se.warn("Failed to initialize Sentry error handling",{error:e})}const l=O.Settings.httpPort.valueOrDefault,u=O.Settings.exposeNetworkWithoutAuth.valueOrDefault,v=$.Library.instance();null!=v?D.HealthCheck.addLoadingMsg("Loading library..."):D.HealthCheck.addLoadingMsg("Starting...");const T=async()=>{Se.info("setup(): http server callback",{httpPort:l,expose:u});const e=[O.Settings.httpPort];null!=v&&e.push(O.Settings.libraryDir),(0,d.stdoutWriteSettings)(...e),null==v?((0,A.sids)((0,R.commandTimeoutMs)()).catch((e=>Se.warn("failed to prefetch sids",e))),(0,N.volumes)().catch((e=>Se.warn("failed to prefetch volumes",e)))):(await(0,L.maybeUpgradeSystemSettings)(),await(0,L.maybeUpgradeLibrarySettings)(),await v.ready,ke.unset()),await(0,X.libraryHealthCheckSetup)(),await D.HealthCheck.awaitSettled(),await(0,q.thenOrTimeout)((0,C.r)(),(0,R.commandTimeoutMs)()),null!=v&&((0,x.isHealthCheckLevelFatal)((await(0,k.getLocalHealthSummary)()).level,"sync")?Se.warn("setup(): health check failed, so we're not starting sync."):d.StdoutWrite.restartSync())},E=u?e.listen(l,T):e.listen(l,O.Settings.localhost.valueOrDefault,T);return E.on("error",(e=>{Se.warn("http.server.onError()",e),"EADDRINUSE"===e.code&&(0,f.exit)({reason:"Port "+l+" is already in use: is PhotoStructure already running?"+p.FatalErrorFlag+p.DoNotSendErrorFlag+p.WebFatalErrorFlag,error:e,status:3})})),new F.EndableServer("http.WebService",E)})),this.app=(0,s.default)(),this.service=new Y.Service("web"),this.setup()}};const _e=(0,l.lazy)((()=>(0,v.redirectRouter)("/splash"))),Te=(0,l.lazy)((()=>(0,v.redirectRouter)("/health"))),Me=(0,l.lazy)((()=>(0,v.redirectRouter)("/welcome"))),Ee=(0,l.lazy)((()=>(new pe.SettingsRouter).router())),ke=(0,l.lazy)((()=>{const e=$.Library.instance();if(null==e)return Se.warn("libraryRouter invoked before library is set up."),void setImmediate((()=>ke.unset()));Se.info("Setting up library router for "+(0,W.map)(e,(e=>e.rootDir)));const t=e.previews(),i=new he.ProgressProvider,r=s.default.Router();return r.use((new le.ManifestRouter).router()),r.use(new re.ApiSystemRouter(Pe).router()),r.use((new se.ApiTagRouter).router()),r.use(new ee.ApiAssetRouter(t).router()),r.use((new te.ApiSearchRouter).router()),r.use((new ge.SpaRouter).router()),r.use(new ue.OpenAssetFileRouter(Pe).router()),r.use(new ae.ImgActualRouter(t).router()),r.use(new oe.ImgRouter(t).router()),r.use(new ye.VideoRouter(t).router()),r.use(new me.SSEProgressRouter(i).router()),r.use("/",((e,t)=>{Se.debug("in root route",{res_headersSent:t.headersSent,res_headers:t.getHeaders()}),t.redirect(302,(0,G.mkHomeFullPath)(e.query))})),r}));(0,V.later)((()=>{O.Settings.libraryDir.watchLater((()=>ke.unset()))}))},98949:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WelcomeRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(18454),l=i(81674),u=i(28874),c=i(51140),d=i(57064),h=i(39761),f=i(8283);t.WelcomeRouter=class{constructor(){this.logger=(0,n.mkLogger)("WelcomeRouter")}router(){return s.default.Router().get("/welcome",(0,a.wrap)("GET /welcome",this.get.bind(this))).post("/welcome",(0,a.wrap)("POST /welcome",this.post.bind(this)))}async get(e,t){return"welcome"!==o.HealthCheck.runState()?t.redirect(c.HttpStatus.Found,"/"):((0,d.suggestedLibraryDirs)(),(0,f.render)(e,t,"welcome",{}))}async post(e,t){return!u.Settings.pickPlanOnWelcome.valueOrDefault||await(0,l.p)()?t.redirect("/settings"):(0,h.getPlansPick)(e,t)}}},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},16436:e=>{"use strict";e.exports=require("@sentry/node")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},87550:e=>{"use strict";e.exports=require("better-sqlite3")},43268:e=>{"use strict";e.exports=require("body-parser")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},7252:e=>{"use strict";e.exports=require("express")},66150:e=>{"use strict";e.exports=require("fast-xml-parser")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},2525:e=>{"use strict";e.exports=require("helmet")},31832:e=>{"use strict";e.exports=require("knex")},51168:e=>{"use strict";e.exports=require("luxon")},93973:e=>{"use strict";e.exports=require("ml-kmeans")},80265:e=>{"use strict";e.exports=require("moo")},31704:e=>{"use strict";e.exports=require("nearley")},4927:e=>{"use strict";e.exports=require("papaparse")},83058:e=>{"use strict";e.exports=require("picomatch")},22915:e=>{"use strict";e.exports=require("platform-folders")},57272:e=>{"use strict";e.exports=require("plist")},85949:e=>{"use strict";e.exports=require("process")},90595:e=>{"use strict";e.exports=require("punycode")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},93944:e=>{"use strict";e.exports=require("source-map-support")},49378:e=>{"use strict";e.exports=require("trash")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},29907:e=>{"use strict";e.exports=require("cluster")},76982:e=>{"use strict";e.exports=require("crypto")},34589:e=>{"use strict";e.exports=require("node:assert")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=5379);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{var __webpack_modules__={60308:e=>{const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972:(e,t,i)=>{const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744:(e,t,i)=>{const r=i(78972);e.exports={decode:r}},67814:(e,t,i)=>{const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968:(e,t,i)=>{const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608:e=>{e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561:(e,t,i)=>{const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658:(e,t,i)=>{const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115:e=>{e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965:(e,t,i)=>{const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463:(e,t,i)=>{const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const w=await y(a,f,r.subarray(16));if(!w)throw new o("decryption failed");return w},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),w=await g(e,y,v),b=n(o,l,w,t,s),S=m(b,p);return a(o,t,l,w,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),w=p.subarray(32),b=n("v3.local.",s,u,t,r),S=m(b,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,w);if(!P)throw new o("decryption failed");return P}}},70981:(e,t,i)=>{const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825:e=>{e.exports=e=>!!e&&e.constructor===Object},41726:(e,t,i)=>{const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223:e=>{const t=36e5,i=24*t,r=7*i,s=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const n=s.exec(e);if(!n)throw new TypeError(`invalid time period format ("${e}")`);const a=parseFloat(n[1]);switch(n[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*a);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*a);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(a*t);case"day":case"days":case"d":return Math.round(a*i);case"week":case"weeks":case"w":return Math.round(a*r);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*a)}}},29534:(e,t,i)=>{const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761:(e,t,i)=>{const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816:(e,t,i)=>{const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366:(e,t,i)=>{const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495:(e,t,i)=>{const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682:(e,t,i)=>{const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826:(e,t,i)=>{const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227:(e,t,i)=>{const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324:(e,t,i)=>{const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665:(e,t,i)=>{const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256:(e,t,i)=>{const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120:(e,t,i)=>{const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827:(e,t,i)=>{const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859:(e,t,i)=>{const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582:(e,t,i)=>{const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406:(e,t,i)=>{const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015:(e,t,i)=>{const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568:(e,t,i)=>{const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438:(e,t,i)=>{const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466:(e,t,i)=>{const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230:(e,t,i)=>{const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961:(e,t,i)=>{const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901:(e,t,i)=>{const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933:(e,t,i)=>{const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)((()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`))),t.AppNameVersion=(0,r.lazy)((()=>(0,t.AppName)()+" "+n.version))},48884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter((e=>s.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let r=0;re?.[r])));return t}function b(e){return P(e,(e=>e.valueOf()))}function S(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function T(e,t){return(0,r.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,i){return E(e,t,i).index}function E(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;re.slice(i,i+t)))}async function D(e,t){return(0,r.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const r=(0,c.times)(t,(()=>new Array(i)));for(let s=0;se.slice(0,t+1)))},t.min=function(e){return e[b(e)]},t.leastIndex=b,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=T,t.least=function(e){return T(e,(e=>e))},t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const i=E(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=k,t.collectBatched=function(e,t,i){const s=[];for(const n of k((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of k((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter(((e,r)=>(0,d.tap)(t(e,r,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.some((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find((e=>e.every((e=>t(r,e)))));e?e.push(r):i.push([r])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&await D(e,(e=>t(r,e)))){e.push(r);continue e}null!=r&&i.push([r])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[r],(e=>i(e,r))))return r}{const r=t+s;if(re+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),b=i(99331),S=i(95937),P=i(98314),_=i(38835),T=i(70025),M=i(8769),E=i(43334),k=i(95402),D=i(28874),x=i(63870);class C extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>n(this,r,"m",s).call(this)),i,"worker"===e?(0,x.commandTimeoutMs)():y.ShortCommandTimeoutMs),r.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,k.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,S.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,r)=>{const s=t.options.streamFlushMillis;s{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&k.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,b.ending)()||!0===(0,T.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,r=new WeakSet,s=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(E.isWin?3:1)*c.minuteMs,maxTasksPerProcess:D.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:D.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:D.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,x.commandTimeoutMs)(),taskTimeoutMillis:D.Settings.taskTimeoutMs.valueOrDefault}}},71371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},89788:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(r.add(this),this.maxLength=e,s.set(this,void 0),n.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,s,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,r,"m",o).call(this,e,(e=>u(this,s,"f")[e]=t))}get length(){return u(this,n,"f")}set length(e){l(this,n,(0,d.clamp)(0,u(this,n,"f"),e),"f")}clear(){this.length=0}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,n,"f")),e<0||e>=u(this,n,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,s,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,n,"f"){u(this,s,"f")[e]=c}));return u(this,n,"f")}pop(){return u(this,r,"m",o).call(this,u(this,n,"f")-1,(e=>{var t;return l(this,n,(t=u(this,n,"f"),--t),"f"),u(this,s,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,n,"f"){u(this,s,"f")[e]=c,l(this,a,e,"f")}));return u(this,n,"f")}shift(){return u(this,r,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,n,(i=u(this,n,"f"),--i),"f"),u(this,s,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,r,"m",o).call(this,u(this,n,"f")-1-e,(e=>{const i=u(this,s,"f")[e];u(this,s,"f")[e]=u(this,s,"f")[t],u(this,s,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{constructor(e=[],t=r.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=n(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(76790),s=i(31586),n=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,s.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,r.sortBy)([...this.entries()],(([t,i])=>[-i,(0,s.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,n.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,r.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,r.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[r,s]of this.m.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=u},79840:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)((()=>a.isElectron?"Desktops":(0,n.isDocker)()?"Docker":"Servers")),t.EditionName=(0,r.lazy)((()=>s.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const r=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,r.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,((e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)((()=>n.PosixFile.for((0,r.examplesNativePath_)())))},31658:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(19851),s=i(65843),n=i(29882);t.examplesNativePath_=(0,r.lazy)((()=>{const e=(0,s.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,n.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,s.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[r.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,s.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,n.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,r.set(this,0),s.set(this,0),n.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,r,l(this,r,"f")+e.cacheHitsSync,"f"),u(this,s,l(this,s,"f")+e.cacheHitsAsync,"f"),u(this,n,l(this,n,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,r,"f"),cacheHitsAsync:l(this,s,"f"),cacheMisses:l(this,n,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,n,(t=l(this,n,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,s,(i=l(this,s,"f"),++i),"f"),c.promise):(u(this,r,(a=l(this,r,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,r,(o=l(this,r,"f"),++o),"f"),c}get(e){var t,i;const s=this.cache.get(e);return null==s||s instanceof m.Deferred&&s.isPending?u(this,n,(t=l(this,n,"f"),++t),"f"):u(this,r,(i=l(this,r,"f"),++i),"f"),s instanceof m.Deferred?s.value:s}clear(){this.cache.clear(),u(this,r,0,"f"),u(this,s,0,"f"),u(this,n,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const r=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,r),(0,c.gt0)(this.opts.timeoutMs)&&r.setTimeout(this.opts.timeoutMs),r.promise.then((e=>{this.set(i,e)}),(e=>{var t,r;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(r=l(this,o,"f"),++r),"f")})),r.promise}},r=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class r{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=r},53507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,s.range)(0,r).filter((e=>this.rows.every((t=>(0,n.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(n.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const r=i(55835),s=i(20014),n=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,r.map)(m(e,t,l(i)),(e=>n.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new s.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,r]=p(e,t);return{lat:i,lon:r}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,r.map)(n.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)((()=>!1))},80875:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const r=i(51455),s=i(98553);var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}}),t.mapParsed=function(e,t){const i=(0,s.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,s.parseJSON)((await(0,r.readFile)(e)).toString())}},57206:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDefaultJsonRevivers=void 0;const r=i(77988),s=i(51168),n=i(45599),a=i(98553),o=i(68708),l=i(24689),u=i(21330),c=i(57159),d=i(28544),h=(0,n.defer)((()=>{s.DateTime.prototype.toJSON=function(){return(0,o.compactValues)({_ctor:s.DateTime.name,ts:this.toMillis(),zone:"system"===this.zone?.type?void 0:this.zoneName})}})),f={name:s.DateTime.name,fromJSON:e=>s.DateTime.fromMillis(e.ts,(0,o.compactValues)({zone:e.zone}))};t.addDefaultJsonRevivers=(0,n.defer)((()=>{h(),(0,a.addJsonRevivers)(r.ExifDateTime,r.ExifDate,r.ExifTime,f,d.CapturedAt,l.DateInterval,u.FuzzyDate,r.BinaryField,c.WrappedError)}))},19851:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),r.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&n(this,r,"m",s).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,r=await t;if(!(0,l.eql)(i,r))for(const e of this.watchers)e(r);null!=this.ttlMs&&this.ttlMs>0&&void 0!==r&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,r.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=b(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>S(v()??await(m.isWin?P():m.isMac?T():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function b(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function S(e){return b(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=S,t.localeWin=P;const _={timeoutMs:10*a.secondMs};async function T(){return b(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return S(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=T,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const r=i(19851),s=i(32105),n=i(14593);t.rootLoggers=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));const a=(0,r.lazy)((()=>[s.ConsoleLogger.instance()]));t.mkLogger=function(e){return new n.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)}},56639:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const r=i(40958),s=i(55835),n=i(59455),a=i(48884);function o(e){const t=(0,r.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,r.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,r.compact)((0,n.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,r]of e)t[i]=r;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,r])=>t(i,r)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,s.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const r=i(98553),s=i(54557);t.memoize=function(e,t){let i=0;const n=new s.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,n.getOrSet((0,r.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?n.clear():n.delete((0,r.stringify)(e)),a.size=()=>n.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)}},7282:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},26033:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._isSupportedNode=t.RequiredNodeRange=t.isSupportedNode=void 0;const r=i(45599),s=i(76280);function n(e=process.versions.node){return(0,s.semverSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange="18||20||21",t._isSupportedNode=n},97352:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,n.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,o.toInt)(e),s=(0,o.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,s.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),r=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,r,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let r=0;re/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,r.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,r.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let r=0;const s=i*e.length;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const r=i(40958),s=i(42659),n=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,s.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[r,s]of(0,l.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of m(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,l.entries)(t))null==e[i]&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,l.keys)(e))if(r[n]=t(n,e[n]),s++,(0,o.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const r of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,r)=>i.includes(t)?void 0:e(r,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,n.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const r=i(31421),s=i(73024),n=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function b(){return(0,n.platform)()+" "+(0,n.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,n.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return A();default:return b()}}()} on ${(0,n.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function _(){return"ubuntu"===(0,t.osDistributionLinux)()}function T(){return"fedora"===(0,t.osDistributionLinux)()}function M(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of S)try{const t=(0,s.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),b)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=_,t.hasApt=function(){return P()||_()},t.isFedora=T,t.isAlpine=M;const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},k={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,c.isString)(s)?s:s?.[r]}const x=(0,a.lazy)((()=>(0,r.execSync)("sw_vers -productVersion").toString().trim()));function C(e=x()){try{return(0,o.mapNotBlankOr)(function(e=x()){return D(e,E)}(e),(t=>`macOS ${t} (${e})`),b)}catch(e){return w().warn("osNameMac(): unknown release",e),b()}}function A(e=(0,n.release)()){const t=e.startsWith("10.0.22")?"11":D(e,k);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=A,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(A())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=x();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(_())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(T())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(M())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},45393:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetVersion=t.AssetFileVersion=void 0,t.AssetFileVersion=12,t.AssetVersion=4},12801:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const r=i(72993),s=i(50213),n=i(23560),a=i(43334);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?r.SimpleShortAppName:r.SimpleAppName];(0,n.isMainService)()&&a.isElectron||e.push((0,n.serviceName)());const t=e.join(a.isElectron?" ":"-");i(85949).title=t}catch(e){(0,s.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},92782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomUid=t.safeRandomChars=void 0;const r=i(55222),s=i(65713);t.safeRandomChars=function({radix:e=r.TokenRadix,length:t}){return(0,s.decuss)((()=>e.randomChars(t)))},t.safeRandomUid=function(e){return(0,s.decuss)((()=>(e?.radix??r.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??5,e?.sepChar??"-")))}},409:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const r=i(41400),s=i(56409),n=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...r){f=!0,m=Date.now()+(0,n.max_)(t,i);const s=d=new a.Deferred(c);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return s.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,r.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new s.Latch;return p.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const r=i(68708),s=i(54993);function n(e){return e instanceof a?e.source:(0,s.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=n,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(n(t))}const s=0===r.length?t.NothingRegExp:r.map((e=>"(?:"+e+")")).join("|");return new RegExp(s,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",r=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,r||(r=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=n((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),b=i(24399),S=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",n.default.basename(S.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map((e=>n.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let T=!0;const M=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),T)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;T=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await b.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const s=r(i(1708)),n=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,n.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,n.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(s.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,n.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every((e=>t.has(e)))&&(0,r.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const r=i(5670),s=i(57150),n=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=r.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,n.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,s.logStartup)())}},28850:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,r.set(this,void 0),s.set(this,void 0),n(this,r,e,"f")}_call(){return(0,l.time)(a(this,r,"f")+(null==a(this,s,"f")?"(local)":"(remote)"),null==a(this,s,"f")?this.impl():a(this,s,"f").call(this))}setShim(e){n(this,s,e,"f")}hasShim(){return null!=a(this,s,"f")}clearShim(){n(this,s,void 0,"f")}}r=new WeakMap,s=new WeakMap},12089:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),r.add(this),this.impl=t,this.cache=i,this.toKey=a,s.set(this,void 0),n.set(this,void 0),l(this,s,e,"f")}async _call(e){return null==this.cache?u(this,r,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,r,"m",a).call(this,e),(()=>u(this,r,"m",o).call(this,e)))}setShim(e){l(this,n,e,"f")}hasShim(){return null!=u(this,n,"f")}clearShim(){l(this,n,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,r,"m",a).call(this,e))}}s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,s,"f")+(null==u(this,n,"f")?"(local)":"(remote)"),null==u(this,n,"f")?this.impl(e):u(this,n,"f").call(this,e))}},45255:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},92322:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const n=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,r.set(this,[])}[(r=new WeakMap,Symbol.iterator)](){return s(this,r,"f")[Symbol.iterator]()}get length(){return s(this,r,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=s(this,r,"f").length-1;for(;t<=i;){const n=t+Math.floor((i-t)/2),a=this.valueOf(s(this,r,"f")[n]);if(e===a)return{found:!0,index:n};e>a?t=n+1:i=n-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&s(this,r,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...s(this,r,"f")];const a=t=>t<0||t>s(this,r,"f").length-1?null:(i??this.diff)(s(this,r,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return s(this,r,"f").shift()}at(e){return(0,a.at)(s(this,r,"f"),e)}toA(){return[...s(this,r,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===s(this,r,"f").length-1){const e=[...s(this,r,"f")];return s(this,r,"f").length=0,e}return s(this,r,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return s(this,r,"f").splice(e,t)}retainLastN(e){return e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const r=i(1708),s=i(82328),n=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,s.stdoutEnded)()||console.log((0,n.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(r.stderr)||r.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const r=i(1708),s=i(95705);t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)}},71567:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:s.default.stdout})}function f({obj:e,ready:i,stream:r}){if(null==r||(0,d.streamEnded)(r))return;const s=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:s.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const r=String(e);return r+(0,l.padding)(i,t-r.length)},t.padReplace=function(e,t,i,r){return(0,c.strslice)(e,0,t)+(0,l.padding)(r,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,n.notBlank)(e)))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,o.times)(r,(i=>e.slice(i*t,(i+1)*t))),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,h.toS)(e),s=(0,h.toS)(t);return s.length>0&&(0,c.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){const r=(0,h.toS)(e),s=r.length-(t+i);return s<=0?r:r.slice(0,t).trim()+" …(+"+s+" chars)…"+r.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function b(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function S(e){return(0,d.toA)(e).sort(b)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,n.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=b,t.uniqIgnoreCase=function(e){return(0,r.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=S,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=b(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,r.isEmpty)(e)||(0,n.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function T(e){return _.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=T;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,n.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(T(e))&&(e=e.slice(1,-1).trim())),e};const E=/^['‘’].*['‘’]$/,k=/^["“”„«»〃].*["“”„«»〃]$/;function D(e,t){const i=x(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function x(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),E.test(e)||k.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,r.compactBlanks)(e),s=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=x,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,s.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=S((0,r.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,s.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,n.blank)(e)||(0,n.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const A=/#.*$/gm;t.stripComments=function(e){return e.replace(A,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,d.toA)(e))if(null!=r&&!(0,n.blank)(r))for(const e of r.split(t))(0,n.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,n.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex((e=>r.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;te.trim()))))}},83556:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)}},94863:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const r=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,r.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,r)=>i===t.charAt(r)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===r?1:void 0),(()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(r);return 2*b(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function b(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach((i=>{const n=Math.min((0,r.count)(e,(e=>e===i)),(0,r.count)(t,(e=>e===i)));(0,a.times)(n,(()=>s.push(i)))})),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[i,r]=[e,t].map(P).map((e=>(0,n.blank)(e)?"":e));return S(i,r,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=b,t.lnsDiff=_;const T=/[^\da-z]+/gi;function M(e,t){const[i,r]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(T,"").toLowerCase()));return S(i,r,(e=>c.RadixAlphaNum.decode(e)))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),(e=>e),256),n=(0,a.mapNumericOr)(t.charCodeAt(r),(e=>e),256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}t.radixDiff=M,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const r=i(98553),s=i(88158);t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))}},88264:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TTLArray=void 0;const r=i(31586);class s{constructor(e,t){this.ttlMs=e,this.maxLength=t,this.times=[],this.a=[],this.expirationListeners=[]}[Symbol.iterator](){this.vacuum();const e=[...this.a];return function*(){for(const t of e)yield t}()}push(...e){(0,r.times)(e.length,(()=>this.times.push(Date.now()))),this.a.push(...e),null!=this.maxLength&&this.vacuum()}pushUniq(...e){e.forEach((e=>{this.includes(e)||this.push(e)}))}includes(e){return this.vacuum(),this.a.indexOf(e)>=0}find(e){return this.vacuum(),this.a.find(e)}some(e){return this.vacuum(),this.a.some(e)}shift(){return this.vacuum(),this.times.shift(),this.a.shift()}first(){return this.vacuum(),this.a[0]}last(){return this.vacuum(),this.a[this.a.length-1]}shiftOrFirst(){return this.length>1?this.shift():this.first()}pop(){return this.vacuum(),this.times.pop(),this.a.pop()}onExpire(e){this.expirationListeners.push(e)}slice(e,t){return this.vacuum(),this.a.slice(e,t)}get length(){return this.vacuum(),this.a.length}clear(){return this.times.length=0,this.a.length=0,this}get values(){return this.vacuum(),[...this.a]}map(e){return this.vacuum(),this.a.map(e)}oldestEntryAge(){return this.vacuum(),this.times[0]}vacuum(){if(0===this.a.length)return;const e=this.a.length;if(null!=this.maxLength){const e=this.a.length-this.maxLength;this.times.splice(0,e),this.a.splice(0,e)}const t=Date.now()-this.ttlMs,i=this.times.findIndex((e=>e>t));if(-1===i?this.clear():i>0&&(this.times.splice(0,i),this.a.splice(0,i)),e!==this.a.length)for(const e of this.expirationListeners)e()}}t.TTLArray=s},75387:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){r.add(this),this[c]="TTLMap",s.set(this,[]),n.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,r,"m",u).call(this)),e),"f"),d(this,r,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,r,"m",u).call(this)}clear(){return d(this,n,"f").clear(),this}delete(e){return d(this,n,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,n,"f").entries())d(this,r,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,n,"f").get(e);return d(this,r,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,n,"f").get(e);if(d(this,r,"m",l).call(this,e,i))return i.v;const s=t();return null!=s&&this.set(e,s),s}lastSetOrGetTs(e){return d(this,n,"f").get(e)?.ts}set(e,t){return d(this,n,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,r,"m",l).call(this,e,d(this,n,"f").get(e))}get size(){return d(this,r,"m",u).call(this),d(this,n,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,r,"m",u).call(this),(0,f.sortBy)(d(this,n,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,n,"f").entries())d(e,r,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,s,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,n,"f").delete(e);for(const i of d(this,s,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,n,"f").entries())d(this,r,"m",l).call(this,e,t)}},22277:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){r.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,r,"m",n).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,r,"m",n).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,r,"m",s).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,r,"m",s).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,r,"m",s).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,r,"m",s).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,r,"m",n).call(this),[...this.delegate.keys()]}[(r=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,s=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},n=function(){for(const[e,t]of this.delegate)o(this,r,"m",s).call(this,e,t)}},84699:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},65211:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resetUid=t.sortByUid=t.tsFromUid=t.isUID=t.uidForTs=t.uid=t.uidSuffix=void 0;const r=i(19851),s=i(76790),n=i(22573),a=i(54993),o=i(7282),l=i(55222);let u=0;const c=l.GeoRadix;function d(e){return c.encode(e)+(0,t.uidSuffix)()}t.uidSuffix=(0,r.lazy)((()=>"-"+c.randomChars(7))),t.uid=function(){return u=Math.max(Date.now(),u+1),d(u)},t.uidForTs=d;const h=/^[\da-z]{9}-[\da-z]{7}$/i;function f(e){const t=(0,a.toS)(e).replace(/(?<=\S)-.*/,"");return(0,n.blank)(t)?void 0:c.decode(t)}t.isUID=function(e){return h.test((0,a.toS)(e))},t.tsFromUid=f,t.sortByUid=function(e){return(0,s.sortBy)(e,(e=>f(e.uid)))},t.resetUid=function(){if(!(0,o.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),u=0}},94174:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(s.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299:function(e,t){"use strict";var i,r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class o{constructor(){i.add(this),this[n]="WeakCache",r.set(this,new Map)}clear(){return a(this,r,"f").clear(),this}delete(e){return a(this,r,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){for(const[t,i]of this.entries())e(i,t,this)&&a(this,r,"f").delete(t)}get(e){const t=a(this,r,"f").get(e),i=t?.deref();return null==i&&null!=t&&a(this,r,"f").delete(e),i}getOrMaybeSet(e,t){const i=a(this,r,"f").get(e)?.deref();if(null!=i)return i;const s=t();return null!=s&&this.set(e,s),s}set(e,t){return a(this,r,"f").set(e,new WeakRef(t)),this}has(e){return null!=a(this,r,"f").get(e)?.deref()}get size(){return a(this,i,"m",s).call(this),a(this,r,"f").size}keys(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries())null==i.deref()?a(e,r,"f").delete(t):yield t}()}values(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield s}}()}entries(){const e=this;return function*(){for(const[t,i]of a(e,r,"f").entries()){const s=i.deref();null==s?a(e,r,"f").delete(t):yield[t,s]}}()}[(r=new WeakMap,i=new WeakSet,n=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}}t.WeakCache=o,s=function(){for(const[e,t]of a(this,r,"f").entries())null==t.deref()&&a(this,r,"f").delete(e)}},48963:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const r=i(42659),s=i(55835),n=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,n.toInt)(e)));if(!(0,s.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,n.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*r.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(n.toInt).filter((e=>(0,o.within)(0,Date.now()+r.dayMs,e))).map((e=>new Date(e))).get()}},79184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=void 0;const r=i(59455),s=i(48884),n=i(22859),a=i(28874),o=i(79781),l=i(92434);t.aggregateAssetFiles=async function(e){const t=(0,r.toA)((0,l.sortAssetFiles)(e)??e);return(a.Settings.assetAggregation.valueOrDefault===n.AggregateTypes.union?s.clusterSome:s.clusterEvery)(t,o.isSimilarAssetFile)}},79781:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotSimilarAssetFile=t.isSimilarAssetFile=t.whyNotSameAsset=t.VideoImageMismatchMsg=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(50357),o=i(55835),l=i(31586),u=i(68708),c=i(12168),d=i(23467),h=i(73168),f=i(50213),m=i(86580),p=i(48368),g=i(80361),y=i(28874),v=i(28544),w=i(75767),b=i(16170),S=(0,r.lazy)((()=>(0,f.mkLogger)("sync-file.AssetFileComparator")));function P(e,t,i,r=((e,t)=>[e,t])){const s=e[i],o=t[i];if((0,n.blank)(s)||(0,n.blank)(o)||(0,a.eql)(s,o))return;const[l,u]=r(s,o);return(0,a.eql)(l,u)||(0,a.eql)(s,u)||(0,a.eql)(l,o)?void 0:`Different ${String(i)}: ${s} ≠ ${o}`}function _(e){return(0,n.mapNotBlank)(e,(e=>e.toLowerCase().trim().normalize()))}function T(e,t){return[_(e),_(t)]}function M(e,t,i){const r=(0,w.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.aKey}:${r.aValue})`}function E(e,i){if(!(0,u.allKeysDefined)(e,"width","height","mimetype","sha"))return"af1 was missing required fields";if(!(0,u.allKeysDefined)(i,"width","height","mimetype","sha"))return"af2 was missing required fields";if((0,d.definedAndEql)(e.sha,i.sha))return void S().debug("matching SHA",{af1:e,af2:i});const r=(0,b.isVideoMimeType)(e.mimetype),n=(0,b.isVideoMimeType)(i.mimetype);if(r!==n)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{af1:e.uri,af2:i.uri,af1IsVideo:r,af2IsVideo:n}});const a=v.CapturedAt.fromAssetFile(e),f=v.CapturedAt.fromAssetFile(i);if(null==a)return"af1 missing capturedAt metadata";if(null==f)return"af2 missing capturedAt metadata";const _=a.isFuzzy||f.isFuzzy;if(_&&y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if((0,g.isSimilarImageHash)(t,r,{rotationsToCheck:(0,m.validRotations)(e,i)}))return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{af1:e,af2:i})}if(!a.overlaps(f))return`captured-at ${a.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`;const E=P(e,i,"make",T)??P(e,i,"model",T);if(null!=E)return E;const k=(0,o.map)((0,h.geohashDistanceMeters)(e.geohash,i.geohash),(e=>(0,l.sigFigs)(e,2))),D={cameraId:M(e,i,"cameraId")??null,imageId:M(e,i,"imageId")??null,lensId:M(e,i,"lensId")??null,exposureSettings:(0,w.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,l.gt)(k,y.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,c.fmt)(k)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:D});const x=(0,s.compact)((0,u.values)(D));if((0,s.isNotEmpty)(x))return x.join(";");if(y.Settings.useImageHashes.valueOrDefault){const t=(0,p.toImageHash)(e),r=(0,p.toImageHash)(i);if(null!=t&&null!=r){const e=(0,g.compareImageHashes)(t,r,{capturedAtIsFuzzy:_});return!0===e?.isSimilar?void 0:e?.whyNotSimilar}}return(0,u.keys)(D).filter((e=>null==D[e])).length>=y.Settings.minMatchesWithoutImageHashes.valueOrDefault?void 0:"Insufficient metadata correlation"}t.VideoImageMismatchMsg="Videos ≠ images",t.whyNotSameAsset=function(e,t,i){{const i=E(e,t);if(null!=i)return i}if("intersection"===y.Settings.assetAggregation.valueOrDefault)for(const r of i)if(r.id!==t?.id){const t=E(e,r);if(null!=t)return t}},t.isSimilarAssetFile=function(e,t){return null==E(e,t)},t.whyNotSimilarAssetFile=E},13991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const r=i(19851),s=i(55835),n=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,r.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function b(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function S(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):b(t)}async function P(e){const[i,r,s,n]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...r,...s,sha:n}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=b,t.assetFileImageHashFields_=S,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const r=i.capturedAt.toAssetFileFields();return null==r?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...r,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,s.map)((0,n.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),S(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),v=i(14036),w=i(45200),b=i(34238),S=(0,r.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function _(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>T(e*t)))}function T(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function M(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=_,t.sortScale=T,t.mtime2sort=M;const E=["make","model","rating","cameraId","imageId","lensId","geohash"];function k(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,s.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,n.sortBy)(e,C).reverse()}function D(e){const t=b.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=_(e);if(null==i)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=P.indexOf(t.scheme);if(null==r)return void S().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,n=(0,g.parsePosixPath)(t.path),l=[];for(const t of E)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:r,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(n.ext),mtime:M(s),isEditOrUpdate:/edit|update/i.test(n.base),isCover:/cover/i.test(n.base),count:Math.abs((0,p.copySuffixCountFromName)(n.name)??0),basename:d.CmpReverseFlag+n.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return S().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function x(){return(0,s.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=D(e);if(null==t)return;const i=[];for(const e of x())i.push(t[e]);return i}t.sortAssetFiles=k,t.assetFileSortCriteriaPojo=D,t.assetFileSortFields=x,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of k(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return S().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return S().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const r=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,r.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,r.set(this,void 0),s.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,n(this,s,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return n(this,s,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,n(this,s,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,r,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=n(this,r,"f")&&clearTimeout(n(this,r,"f")),a(this,r,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},r=new WeakMap,s=new WeakMap},69591:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const s=r(i(87997)),n=i(31586);t.debounce=function(e,t){let i,r=[];const a=(0,n.gt0)(t)?(...n)=>{r=n,null!=i&&s.default.clearTimeout(i),i=s.default.setTimeout((()=>{e(...r)}),t)}:e;return a.reset=()=>{null!=i&&s.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),b=i(45599),S=i(26905),P=i(55835),_=i(31586),T=i(68708),M=i(20214),E=i(57153),k=i(85556),D=i(50213),x=i(70025),C=i(95937),A="TIMEOUT",F=(0,b.defer)((()=>(0,D.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),r=(0,_.gt0)(t)?new s(A).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let r=i.length-1;r>=0;r--){const s=i[r];if(s.isSettled){if(s.name===A)return void F().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(r,1),yield s.value}}if(i.every((e=>e.name===A)))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static resolve(e,t){return new s(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;r.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,E.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=s,s,(y=p(i,s,"f",n),m=y++,y),"f",n),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof s&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,T.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,r=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new k.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===E.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==E.PromiseStates.pending}get isResolved(){return p(this,o,"f")===E.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===E.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,r,"m",m).call(this,(()=>{g(this,o,E.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,x.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,S.asError)(e);return p(this,r,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,E.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,s=I,m=function(e){if(p(this,o,"f")===E.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},n={value:0}},83412:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DoneWrapper=void 0;const r=i(56409),s=i(38836);class n extends s.EndableWrapper{constructor(){super(...arguments),this.doneLatch=new r.Latch}isDone(){return this.doneLatch.isSettled()||this.ended}donePromise(){return this.doneLatch.promise}}t.DoneWrapper=n},27395:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,r.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*n.minuteMs);const y=5*n.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const r=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:r});try{await(0,o.thenOrTimeoutError)(i.end(),r,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,r.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,s.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,s.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,r,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),r.add(this),this.opts=e,s.set(this,void 0),n.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,s,"f")}hasTimeout(){return null!=u(this,n,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,r,"m",a).call(this);const h=()=>{u(this,r,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,s,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,n,(0,d.setTimeout)((()=>{u(this,r,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref()):h(),!0}}t.EndableInterval=v,s=new WeakMap,n=new WeakMap,o=new WeakMap,r=new WeakSet,a=function(){(0,h.map)(u(this,s,"f"),d.clearInterval),c(this,s,void 0,"f"),(0,h.map)(u(this,n,"f"),d.clearTimeout),c(this,n,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,r.set(this,void 0),this.onEnds=[],s.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),n(this,s,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,r,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return n(this,r,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return n(this,s,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},r=new WeakMap,s=new WeakMap},99331:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const r=i(7282);let s=!1;t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s}},45608:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const r=(0,n.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(r)}(0,m.ending)()||(await(0,f.endEndables)(),s.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},39250:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LastOneInWins=void 0;const n=i(23838),a=i(54993),o=i(15674),l=i(73568),u=i(76740),c=i(99331),d=i(42638);t.LastOneInWins=class{constructor(e,t=o.maxCpus){this.name=e,this.maxConcurrency=t,r.set(this,new n.MultiMap),this.p=new d.Promises(e,t)}vacuum(){return s(this,r,"f").filterInPlace(((e,t)=>t.isPending&&!0!==t.payload?.aborted)),s(this,r,"f").valueCount()}enqueue({key:e,abortable:t,fn:i}){for(const t of s(this,r,"f").get(e)??[])t.payload?.abort("aborted by new work");if(this.vacuum(),(0,c.ending)())throw new l.AbortError("ending");const n=t??new u.Abortable,o=this.p.serial((0,a.toS)(e),(()=>i(n)),n);return s(this,r,"f").add(e,o),o}},r=new WeakMap},60172:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,r)=>{t=e,i=r})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new b(e,t,i,r)};class b extends g.ExtensibleFunction{constructor(e,t,i,l){super(),r.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,s.set(this,void 0),n.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,r,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,n,0,"f"),d(this,s,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,r,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,r,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,n,"f")}isStale(){return null==c(this,s,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,s,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,s,"f")?void 0:Date.now()-c(this,s,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,n,(i=c(this,n,"f"),++i),"f")}},u=function(e){d(this,s,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,r,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const r=i(98553),s=i(80049);t.memoizeAsync=function(e,t){let i=0;const n=new s.FifoCacheAsync(t),a=t=>(i++,n.getOrSetAsync((0,r.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return n.clear();{const t=(0,r.stringify)(e);return n.deleteIf((e=>t===e))}},a.size=()=>n.size,a.callCount=()=>i,a}},22781:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,r.set(this,void 0),s.set(this,!1),n.set(this,!1)}_call(){return a(this,s,"f")?(o(this,n,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,r,"f")):(o(this,s,!0,"f"),o(this,r,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,s,!1,"f"),!0===this.runLaterIfBusy&&a(this,n,"f")&&(o(this,n,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,s,"f")}prior(){return a(this,r,"f")}async force(){return await a(this,r,"f"),this._call()}}r=new WeakMap,s=new WeakMap,n=new WeakMap},37461:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var b=i(20214);async function S(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,l.gt0)(s)?(0,c.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function T({arr:e,f:t,name:i,maxConcurrent:s,timeoutMs:n,promises:a}){if(null==e)return[];const o=(0,r.compact)(await e);if((0,r.isEmpty)(o))return[];if((s=Math.round(s??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:i,timeoutMs:n});const u=a??(o.length<=s?w.PermissivePromises:new w.Promises(i,(()=>s))),d=(0,l.gt0)(n)?e=>(0,c.thenOrTimeoutError)(t(e),n):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,r.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return b.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=S,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await S(s);r.push(...await S(i(e)))}return r},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=T,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n}){return(await T({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:n})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:s,timeoutMs:n}){return(await T({name:e,arr:(0,r.compact)(t),f:i,maxConcurrent:s,timeoutMs:n})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await T({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,n.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,n.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,r)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let r,s=null;try{r=await((0,h.isFunction)(e)?e():e)}catch(e){s=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenMap2=async function(e,t,i){const r=await e;if(null==r)return;const s=await t;return null!=s?i(r,s):void 0},t.thenMapOr=async function(e,t,i){const r=await e;if(null==r)return i();const s=await t(r);return null==s?i():s},t.thenMap2Or=async function(e,t,i,r){const s=await e;if(null==s)return r();const n=await t;if(null==n)return r();const a=await i(s,n);return null==a?r():a},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const r=await T({name:e,arr:t,f:i});return(0,s.sortBy)(r,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),b=i(73614);function S(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const r=Date.now(),s=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),n=(0,b.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-r)+"ms")}),s);try{const s=await(0,c.tot)(t),n=Date.now()-r;return i?.(s,n),this.push(e,n),s}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-r),t}finally{clearTimeout(n)}}get entriesBySumDesc(){return(0,n.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(S(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),r=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,S(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(S(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function _(e,t,i){return P.instance().time(e,t,i)}function T(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,r.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,s.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const i=Date.now(),r=t();return T(e,Date.now()-i),r},t.pushTime=T,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,r.lazy)((async()=>_(e,t)),i)}},42638:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),b=i(82647),S=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){r.add(this),this.name=e,this.ee=new f.default.EventEmitter,s.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new b.Average,n.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,s,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,S.maxCpus)(),d(this,s,"f")?.call(this)??(0,S.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,n,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,n,"f")}}enqueue({name:e,l:t,payload:i,serialId:s}){const n=d(this,r,"m",l).call(this,{name:e,l:t,payload:i,serialId:s});return this.laterPop(),n}enqueueAll(e,t){const i=t.map((t=>d(this,r,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,r,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,s=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function({name:e,l:t,payload:i,serialId:r}){const s=new P.Deferred(e,{payload:i,serialId:r});return d(this,o,"f").push({d:s,l:t}),s},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,n,(t=d(this,n,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new _(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new _(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},59189:function(e,t){"use strict";var i,r=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SerialLaterQueue=void 0,t.SerialLaterQueue=class{constructor(){i.set(this,Promise.resolve())}enqueue(e){return s(this,i,r(this,i,"f").catch().then(e),"f")}},i=new WeakMap},4867:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,n.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const r=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})}},9727:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const s=r(i(1708)),n=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),b=i(88158),S=i(45969),P=i(43334),_=i(28874),T=i(3790);function M(e){return E().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const E=(0,n.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,b.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const k=["HOME","LANG","USER"],D=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?k:D),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,S.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,_.persistedSettings)()){const r=e?i.value:i.envValue;null==r||(0,o.eql)(r,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(s.default.env,(e=>M(e)||!(0,T.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:F({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let A=!1;function F({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,g.childProcLocale)():{},...C(r),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(s);if((0,y.isLogged)("debug")&&!A){A=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(s).map((([e,t])=>[e,(0,T.isHiddenEnvKey)(e)?"(hidden)":t])),[i,r]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(r))}return s}t.childEnv=F},84777:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),b=i(22911),S=i(4867),P=i(73614),_=i(70025),T=i(57159),M=i(36868),E=i(66184),k=i(45643),D=i(95402),x=i(9727),C=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function A(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function F(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",A(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",A(e)),!1;if(i===n.default.pid)return C().warn("endProcess(): asked to end MY pid",A(e)),!1;if(i===n.default.ppid)return C().warn("endProcess(): asked to end my parent pid",A(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,D.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,k.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",A(e)),!0;{D.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,D.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,k.waitForPidExit)(i,5e3)}function I(e,i,r,s=0){const a=new Date,o=[];return(0,v.niceable)(i,r)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&F(e)}),s-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,D.addPid)({pid:e.pid,cmd:i,timeoutMs:s,ppid:n.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function O(e,t,i,r){const n=(0,x.spawnOptions)(r);return(0,E.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(s.default.execFile(e,t,n),e,t,i)}async function L(e,t,i){const r=i.quiet??!1,s=i.ignoreStderr??!1,n=i.ignoreExitCode??!1,a=O(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new b.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(a.stdin);const v=new d.Latch;null==a.stdout?v.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==a.stderr||s?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,S.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,S.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,S.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const E=p.join("");(0,l.notBlank)(E)&&g.push(new Error(E)),!r&&(0,o.isNotEmpty)(g)&&C().warn(f+" resulted in errors:",g);const k=i.isIgnorableError??_.isIgnorableError,D=g.filter((e=>!0!==k(e)));if(D.length>0)throw 1===D.length?D[0]:new T.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!n&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:E}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,D.killPid)(a.pid,!0),e}}t.endProcess=F,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,r){const n=(0,x.spawnOptions)(r);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(s.default.spawn(e,t,n),e,t,i)},t.execFile=O,t.stdoutResult_=L,t.stdout_=async function(e,t,i){const r=await L(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})}},86335:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ChildService=t.ChildServiceNames=t.inspectPort=t.pathToService=void 0;const l=i(77598),u=o(i(1708)),c=i(19851),d=i(40958),h=i(22573),f=i(50268),m=i(68708),p=i(5670),g=i(50989),y=i(12168),v=i(59455),w=i(41583),b=i(54993),S=i(80875),P=i(50213),_=i(81168),T=i(27395),M=i(25764),E=i(59958),k=i(70025),D=i(83278),x=i(85021),C=i(29325),A=i(43334),F=i(28874),I=i(84777),O=i(55534),L=i(85100),R=i(34330),N=(0,c.lazy)((()=>(0,P.mkLogger)("child.ChildService")));async function B(e){const t=(0,_.ensureSuffix)(e,".js"),i=D.BaseFile.projectRoot(),r=D.BaseFile.for(u.default.cwd()),s=(0,C.isPacked)()?[i.join("bin",t),A.isElectron?i.join("app.asar",t):void 0]:[r.join("dist","library",t),r.join("dist","core",t),r.join("lib","library",t)];(0,C.isPacked)()||(A.isElectron?(s.push(r.join("dist","app",t)),s.push(i.join("src","desktop","dist","library",t))):s.push(i.join("src","library","dist","library",t)));for(const e of s)if(null!=e&&!0===await e.isNonEmptyFile((0,C.isPacked)()?y.KB:128))return N().tap({msg:"pathToService()",level:"info",result:e,meta:{cmd:t,isPacked:C.isPacked,paths:s.map(b.toS)}});return N().throw("Failed to find path to "+e,{paths:s,fatal:!0})}t.pathToService=B,t.inspectPort=function(e){switch(e){case"web":return 9223;case"sync":return 9224;default:return(0,l.randomInt)(9225,9600)}},t.ChildServiceNames=(0,g.strEnum)(...p.ServiceNames.pick("web","sync"));class j{static async mk_(e,t={}){const i=t.pathToService??await B(e);if((0,h.blank)(i))throw new Error("Failed to find path to "+e);return t.nodeArgs=(0,v.toA)(t.nodeArgs),new j(e,i,t)}constructor(e,t,i){var o,l;r.add(this),this.serviceName=e,this.cmd=t,this.opts=i,this.restartCount=0,this.name="ChildService("+e+")",this.endTimeoutMs=(0,L.serviceExitTimeoutMs)(e),this.logger=(0,P.mkLogger)(this.name);const c=[...(0,v.toA)(i.nodeArgs),t.nativePath];(0,d.isNotEmpty)(i.args)&&c.push(...i.args),this.spawnOpts=(0,m.pick)(this.opts,"argv0","cwd","detached","env","gid","shell","stdio","timeout","uid","windowsHide","windowsVerbatimArguments","forceCLocale","forWorker"),this.spawnOpts.forceCLocale=!1,(l=(o=this.spawnOpts).env??(o.env={}))[E.UV_THREADPOOL_SIZE]??(l[E.UV_THREADPOOL_SIZE]=(0,b.toS)(("web"===e?F.Settings.webUvThreads:F.Settings.syncUvThreads).valueOrDefault)),this.wc=new R.WatchedChild({name:e,childFactory:async()=>(this.restartCount>0&&await(this.opts.onPreRestart?.()),this.restartCount++,(0,I.spawn)(u.default.execPath,c,-1,this.spawnOpts)),endableRank:M.EndableRanks.service,endTimeoutMs:this.endTimeoutMs,onStdout:a(this,r,"m",n).bind(this),onStderr:a(this,r,"m",s).bind(this),onError:this.opts.onError??(e=>!1===(0,k.isIgnorableError)(e)),ignoreStopErrors:!1,exitCommand:O.ServiceExitCommand,...i}),(0,T.addEndable)(M.EndableRanks.first,this)}get startMs(){return this.wc.startTs}runHealthCheck(){return this.wc.writeStdin(x.HealthCheckCommand+"\n")}start(){return this.wc.start()}stop(){return this.wc.stop()}restart(e){return this.wc.restart(e)}get ended(){return this.wc.ended}async end(){return this.wc.ended||this.write(O.ServiceExitCommand),this.wc.end()}get pid(){return this.wc.pid}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}write(e,t=2){if(t<0)return this.logger.warn("write(): no more retries",{toStdin:e}),!1;try{const t=this.wc.proc;return!0!==t?.stdin?.writable?(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:e}),!1):t.stdin.write((0,_.ensureSuffix)(e,"\n"))}catch(i){return this.logger.warn("write(): caught "+i),this.wc.onError("onStdout()",(0,w.toErr)(i)),this.write(e,t-1)}}}t.ChildService=j,r=new WeakSet,s=function(e){const t=(0,S.parseJSON)(e);return this.logger.warn(".onStderr()",t??e),!0===t?.fatal},n=function(e){if(!(0,h.blank)(e))try{const t=(0,S.parseJSON)(e);if(null==t)return void this.logger.info(".onStdout(): non-JSON payload",e);if(!0===t?.fatal)this.wc.onError(this.name+".onStdout()",t);else if((0,f.isHealthCheckSummary)(t)){const e="failed"===t.state||"error"===t.level;this.logger.log(e?"error":"info",".onStdout(): health check summary",t),e&&this.wc.onError(this.name+".onStdout()",t,e)}else null!=this.opts.onData&&this.opts.onData(t)}catch(t){this.logger.warn(".onStdout() failed:",{data:e,error:t})}}},3790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const r=i(22573),s=i(41400),n=i(19851),a=i(28874);(0,s.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,n.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,r.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},85100:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceExitTimeoutMs=void 0;const r=i(23560),s=i(28874),n=i(45255);t.serviceExitTimeoutMs=function(e){return(0,r.isSyncService)(e)?s.Settings.syncExitTimeoutMs.valueOrDefault:n.ShortCommandTimeoutMs}},34330:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),b=i(25764),S=i(99331),P=i(42638),_=i(38835),T=i(8769),M=i(57159),E=i(66003),k=i(50213),D=i(45643),x=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new A({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class A{constructor(e){r.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,k.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),s.set(this,!1),this.onError=(e,t,i)=>{const n=new M.WrappedError(e,{cause:t}),a=!1!==n.ignorable;this.logger().log(a?"warn":"error","onError()",n),u(this,s,"f")||a||(this.lastError=n,(0,T.onError)(n),!0!==n.fatal?(i??this.opts.onError(e,n))&&(this.logger().warn("onError requested restart",{src:e,error:n}),u(this,r,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:x.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:b.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,r,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,s,"f")}async end(){return c(this,s,!0,"f"),u(this,r,"m",n).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,r,"m",n).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,s,"f")}),!u(this,s,"f")&&!(0,S.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,r,"m",n).call(this),this._stopped=!1,u(this,r,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:x.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,r,"m",l).call(this))))}}t.WatchedChild=A,s=new WeakMap,r=new WeakSet,n=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,s,"f")});const e=this.cp;return this.cp=void 0,u(this,r,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,s,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,r,"m",n).call(this),!this._stopped&&!u(this,s,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,T.onError)("Can't restart "+this.name+", failure rate is too high."+_.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,r,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,s,"f")}),this._stopped||u(this,s,"f")||(0,S.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,E.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,T.onError)("Failed to start "+this.name+_.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,s,"f")}),(0,S.ending)()||(this.opts.restartOnExit?(await u(this,r,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=n(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),r=t?.stableBasename??1?m(i):i.base.normalize(),s=i.sibling(r);if(s.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",s.posixPathFrom((0,l.examples)()));const n=(0,d.originalsDir)();if(s.isSelfOrDescendantOf(n))return a.join("$library",s.posixPathFrom(n));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",s.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},69554:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const n=i(6858),a=i(1708),o=i(37805),l=i(22573),u=i(55835),c=i(7282),d=i(19913),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{constructor(e,t,i){this.serviceName=e,this.args=t,this.additionalDescription=i,r.set(this,[]),(0,d.setServiceName)(e),(0,p.verifyUidGid)()}add(...e){return s(this,r,"f").push(...e),this}async parse(e=a.argv,t){let i=(0,m.addHelpFooter)(new n.Command).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,l.mapNotBlankOr)(this.additionalDescription,(e=>"\n\n"+e),(()=>""))).join("\n"));(0,u.map)(this.args,(e=>{i=i.arguments(e)}));for(const e of s(this,r,"f"))i=e.beforeParse(i);i.option("-V, --version","Output version information (spoiler: it's "+((0,c.isTest)()?"1.2.3-test":o.version)+")"),i.on("option:version",(()=>{console.log((0,m.cliWrapVersion)()),(0,a.exit)(0)})),i.parse(e,t??{from:h.isMainElectron?"electron":"node"});const d=i.opts();for(const e of s(this,r,"f"))await(e.afterParse?.(d));return i}},r=new WeakMap},41269:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},38790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(1708),s=i(38639),n=i(17181),a=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors. See https://no-color.org/"),afterParse:e=>{(0,s.mapBoolean)(e.color,(e=>{r.env.PS_LOG_COLOR=String(e),a.Settings.logColor.envValue=e,(0,n.setupLogFormatter)()}))}}},83210:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=void 0;const s=r(i(1708)),n=i(22573),a=i(38639);t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)}},53978:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(94174),l=i(44198),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)((0,l.env)()[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){const e=(0,s.compactBlanks)([c("user id","PUID",(0,o.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,r.lazy)((()=>{(0,u.isDocker)()&&(0,n.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},43380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WriteSettingsArg=void 0;const r=i(28874),s=i(2858),n=i(22573),a=i(38639),o=i(46292);t.WriteSettingsArg={beforeParse:e=>e.option("--write-settings","Write (or re-write, if they exist) system and library settings.toml files. See https://phstr.com/settings"),afterParse:async e=>{if((0,a.isTrue)(e.writeSettings)){const e=await(0,s.writeSystemSettings_)();if(null==e?console.info("--write-settings: Failed write system settings: no system configuration directory was found.",{checkedDirectories:(0,o.osConfigDirs)()}):console.info(`--write-settings: Wrote system settings to ${e}`),(0,n.blank)(r.Settings.libraryDir.valueOrDefault))console.error("--write-settings: Failed to write library settings: no PS_LIBRARY_DIR is set.");else{const e=await(0,s.writeLibrarySettings_)();console.info(`--write-settings: Wrote library settings to ${e}`)}}}}},54772:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),v=(0,r.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const r=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:r,closeLabhashes:[r],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function b(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,r.lazy)((()=>(0,s.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return b((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=b;const S=new Map;function P(e){return(0,a.gte0)(e)?(0,n.getOrSet)(S,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const r=(0,c.unlabhash)(e),n=b(r);return null!=r&&null!=n&&((0,s.pushUniq)(n.closeLabhashes,e),(0,s.pushUniq)(n.closeRgb,(0,c.lab2rgbhex)(r))),n})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const r=i(19851),s=i(40958),n=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return _(w(e))}function y(e){return(0,f.clampRGB)(M(T(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>E(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;se>S?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-r)])}function T(e){const[t,i,r]=v(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>S?o:(116*n-16)/P,c=t>8?Math.pow(s,3):t/P,d=l>S?l:(116*a-16)/P;return[u*b.X,c*b.Y,d*b.Z]}function M(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function E(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=_,t.lab2xyz=T,t.xyz2rgb=M,t.LabBitZip=(0,r.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=E;const k=new Map;function D(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function C(e){return A(x(e))}function A(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function F(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function I(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,n.getOrSet)(k,e,(()=>D(e,t))):D(e,t)},t.minLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,r.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(F(e))},t.hsv2hsl=A,t.hsl2hsv=F,t.hsv2rgb=I,i.c[i.s]===e&&console.log(E([0,0,0]))},42079:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const r=i(31586),s=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const n=1,a=1,o=1;function l(e,t){const[i,r,l]=e,u=(0,s.sqrt)(r**2+l**2),[c,d,h]=t,f=(u+(0,s.sqrt)(d**2+h**2))/2,m=.5*(1-(0,s.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=r*(1+m),g=d*(1+m),y=(0,s.sqrt)(p*p+l*l),v=(0,s.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let b=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);b+=2*(b<0?1:0)*Math.PI;const S=c-i,P=v-y;let _=y*v==0?0:b-w;_-=2*(_>Math.PI?1:0)*Math.PI,_+=2*(_<-Math.PI?1:0)*Math.PI;const T=2*(0,s.sqrt)(y*v)*Math.sin(_/2),M=(i+c)/2,E=(y+v)/2;let k;y*v==0?k=w+b:(k=(w+b)/2,k-=(Math.abs(w-b)>Math.PI?1:0)*Math.PI,k+=2*(k<0?1:0)*Math.PI);const D=(M-50)**2,x=1-.17*Math.cos(k-Math.PI/6)+.24*Math.cos(2*k)+.32*Math.cos(3*k+Math.PI/30)-.2*Math.cos(4*k-63*Math.PI/180),C=1+.015*D/(0,s.sqrt)(20+D),A=1+.045*E,F=1+.015*E*x,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*k-275)/25)**2),O=2*(0,s.sqrt)(Math.pow(E,7)/(Math.pow(E,7)+Math.pow(25,7))),L=-1*Math.sin(2*I)*O;return(0,s.sqrt)(Math.pow(S/(n*C),2)+Math.pow(P/(a*A),2)+Math.pow(T/(o*F),2)+L*P/(a*A)*T/(o*F))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const r=i(40958),s=i(31586),n=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,r.compact)(e.map((e=>[e.rgbhex,(0,s.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,r.compact)((0,s.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,s.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const r=(0,n.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=r&&(0,s.gt0)(i)?new c(r,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,s.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,s.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},32848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scaled_delta_e=t.dominantColorCorrelation=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(48884),o=i(31843),l=i(70417),u=i(3048);function c(e,t){const i=(0,s.sum)(e,(e=>(0,n.clamp)(0,100,e.pct))),r=(0,s.sum)(e,(e=>function(e,t){const i=(0,a.leastBy)(t,(t=>(0,u.ciede2000_delta_e)(e.lab,t.lab)));if(null==i)return 0;const r=(0,u.ciede2000_delta_e)(e.lab,i.lab),s=(0,n.clamp)(0,e.pct,(0,l.avg)([e.pct,i.pct])),o=h(r);return(0,n.clamp)(0,100,s)*o}(e,t)));return r/i}t.dominantColorCorrelation=function(e,t){return e=(0,s.compact)(e),t=(0,s.compact)(t),(0,s.isEmpty)(e)||(0,s.isEmpty)(t)?0:(0,l.avg)([c(e,t),c(t,e)])};const d=(0,r.lazy)((()=>[{x:0,y:1},{x:9,y:.8},{x:16,y:.3},{x:20,y:0}]));function h(e){return(0,n.clamp)(0,1,(0,o.lerp2d)(e,...d()))}t.scaled_delta_e=h},40401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),v=i(85810),w=i(3048),b=i(76490),S=i(1971),P=(0,r.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=S.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=S.ModeCount){const i=Date.now(),r=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of E({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=T[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function D(e){const i=t,r=4*t;g=Math.round(Math.max(i,Math.min(r,e)))}const C=f.length<=g?[]:(0,s.compact)(_.slice(0,r).map((e=>{const r=(0,p.kmeans)(f,g,{...M,seed:e}),s=x(r.centroids,f.length);if(s.lengtht&&D(g-1);const n=s.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,r]of a.entries()){const s=(0,v.unlabhash)(i),n=(0,c.leastByCtx)(e,(e=>h(e.centroid,s)));null!=n&&(0,l.times)(r,(()=>t.push(n.value)))}return t.p84}(n),2);return{...r,centroids:n,description:{kIn:g,kOut:r.centroids.length,kMerged:s.length,score:o,iterations:r.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const A=(0,c.leastBy)(C,(e=>e.score));if(null==A)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:r}),k(a,t);const F=(0,o.stringify)({...A?.description,elapsedMs:Date.now()-i}),I=(0,n.sortBy)(A?.centroids,(e=>-e.size)).map((e=>b.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:F,score:A?.score,totalColors:a.size,totalPixels:f.length,iters:A?.iterations,dominantColors:(0,b.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:F,dominantColorScore:A?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const r of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,r)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,r))}return i};const _=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],T={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},M=(0,r.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:T[y.Settings.dominantColorDeltaE.valueOrDefault]})));function E({labs:e,minK:t,thresh:i,retries:r=3}){if(r<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const s=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(s))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const n=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=s));return n.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:s,minK:t,pixelCount:e.length,filteredCount:n.length}),n):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:s,minK:t,retries:r,pixelCount:e.length,filteredCount:n.length}),E({labs:e,minK:t,thresh:.75*s,retries:r-1}))}function k(e,t){const i=e.countSum,r=e.size;D(e);const n=e.size,a=(0,s.compact)(e.top(t).map((([e,t])=>b.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:r,mergedColors:n,pixelCount:i,pctOmitted:l})}}function D(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[r,s]of[...e.entriesByCountDesc()]){const n=(0,v.unlabhash)(r),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,n)<=t));null==a?i.push({lab:n,labhash:r}):(e.delete(r),e.incr(a.labhash,s))}return e}function x(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const r=[];for(const t of e){const e=r.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?r.push(t):e.size+=t.size}const s=t/100;return(0,n.sortBy)(r.filter((e=>e.size>s)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{M.unset()}))})),t.maybeFilterGrey=E,t.dominantColorsFromModes=k,t.mergeLabhashes=D,t.mergeNearCentroids=x},85409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)((()=>(0,n.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const r=i(31586),s=i(68708),n=i(50989);t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,r.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,r.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),r=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,(e=>r.ExifDateTime.fromJSON(e))),(0,n.map)(e.end,(e=>r.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),v=i(21330),w=i(928),b=i(54261),S=i(73389),P=i(51275),_=(0,n.lazy)((()=>(0,f.mkLogger)("date.Dated")));function T(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,S.isDateTime)(e)||(0,m.isDateObject)(e))}function M(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function E(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function k(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,S.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void _().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,b.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function x(e,t){const i=M(e),r=E(e);if(null!=i&&null!=r)return(0,c.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function C(e,t,i,r){const[s,n]=(0,a.sortBy)([x(e,i),x(t,r)],(e=>e?.start));return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function A(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=T,t.toDated=function(e){return T(e)?e:void 0},t.mapDated=function(e,t){return T(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=M,t.datedToEndTs=E,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):k(e)},t.datedToDateTime=k,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(A(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??(i=D(e)),r??(r=D(t)),C(e,t,i,r))return!0;const s=(0,P.getZoneName)(e),n=(0,P.getZoneName)(t);return null==s&&null!=n&&(e=(0,v.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,v.setZone)(t,s)??t),C(e,t,i,r)},t.isoToDated=A,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const r=i(31586),s=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const r=i(22573),s=i(31586),n=i(54557),a=i(91655),o=new n.FifoCache(512);function l(e){return(0,s.isNumber)(e)?e:(0,r.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new n.FifoCache(512);t.encodeDuration=function(e){return(0,r.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,s.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const r=i(51168),s=i(40958),n=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=r.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,s.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,n.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const r=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&r.push(i+e.s)}return r.join(i)}},98247:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function v(e,t,i){const r=t.exec(e);if(null==r||(0,u.isEmptyObj)(r.groups))return;const{year:s,month:n,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(r.groups,((e,t)=>(0,l.toInt)(t)));if(null==s||null==n||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(r.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(r);return S({year:s,month:n,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=s.Info.normalizeZone(r.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:n}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,i,{zone:n??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??v(e,b(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,b=(0,n.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function S(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=S},74417:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,s.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const r=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const n=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),v=i(79842),w=i(66649),b=i(98247),S=i(98725),P=i(928),_=i(54261),T=i(73389),M=i(89724),E=i(17415),k=i(88600),D=i(51275);function x(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,r.set(this,(0,p.lazy)((()=>(0,k.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(S.ISO_YMD_RE.exec(e)?.groups??S.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tx(e))).join("-")}toLocal(){return(0,M.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function A(e,t){if(e instanceof n.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,_.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,E.zoneToTzOffsetMinutes)((0,w.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(r=>(0,d.map)((0,P.getMonth)(e),(s=>(0,d.map)((0,P.getDay)(e),(n=>(0,d.map)((0,P.getHour)(e),(a=>(0,b.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",r=15*(0,h.round)(e/15),s=Math.abs(r),n=Math.floor(s/60),a=Math.floor(Math.abs(s%60));return`${t?"UTC":""}${i}${x(n)}:${x(a)}`},t.toExifDateTime=A,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof n.ExifDateTime?e.tzoffsetMinutes:(0,T.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,_.hasTime)(e)||(i??(0,v.datedToPrecisionMs)(e))>=c.dayMs?O(e):A(e,(0,D.getZoneName)(e))?.toISOString({includeOffset:t})};const F="yyyy:MM:dd HH:mm:ss.SSS",I=F+"ZZ";function O(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>x(e))).join(t)}function L(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,r]=[e,t].map(w.datedToMillis);return null==i||null==r?void 0:i-r}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,v.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,D.hasZone)(t)?I:F):void 0},t.datedToYMD=O,t.toFuzzyDate=L,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,w.datedToMillis)(e)||null==(0,w.datedToMillis)(t))return;const[s,n]=[e,t].map((e=>(0,w.datedToMillis)(e))).sort(),o=(n-s)/(r+1),l=(0,D.getZoneName)(e),u=l===(0,D.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(s+o*i,{zone:u});return[e,t].some((e=>!(0,_.hasTime)(e)))?L(c):c},t.setZone=function(e,t,i){const r={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,D.hasZone)(e)},s=(0,E.normalizeZone)(t);return null!=e&&null!=s&&(0,_.hasTime)(e)?e instanceof y.DateInterval?e.setZone(s,r):A(e)?.setZone(s,r):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,v.datedToDateTime)(e);if(null==i)return;const r=(0,D.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),v=i(68852),w=i(4001),b=i(28874),S=i(24689),P=i(79842),_=i(66649),T=i(98247),M=i(21330),E=i(54261),k=i(73389),D=i(16400),x=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:O.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return O.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return O.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,_.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,k.isDateTime)(i)?i:(0,E.isExifDateTime)(i)?i.toDateTime():void 0};const A=new Map;function F(e,t,i){try{const r=(0,T.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const s=(0,h.getOrSet)(A,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,T.parseExifDateTimeFormat)({input:s?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:r=!0,descPredicate:s=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const n=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==n.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>S.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,T.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:T.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(b.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(b.Settings.extraDateTimeFormats.values)){const r=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>F(i,r,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of O.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:r}))if(s(e))for(const e of n){const t=a(e);if(null!=t&&(0,x.isValidDate)(t))return t}}t.parseDated=I;class O{constructor(e={}){r.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&b.Settings.fuzzyDateParsing.watchLater((()=>a(this,r,"m",n).call(this))),null==e.fuzzyYearParsing&&b.Settings.fuzzyYearParsing.watchLater((()=>a(this,r,"m",n).call(this))),a(this,r,"m",n).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??b.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??b.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!b.Settings.usePathsToInferDates.valueOrDefault)return;M.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=O,r=new WeakSet,s=function(e){const t=new L(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},n=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,r,"m",s).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,r,"m",s).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,r,"m",s).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,r,"m",s).call(this,[e,t.seps,t.yearRE]),a(this,r,"m",s).call(this,[t.yearRE,t.seps,e]),a(this,r,"m",s).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},O.instance=(0,u.lazy)((()=>new O));class L{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return M.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const r=i(55835),s=i(31586),n=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),(t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r}))}},54261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const r=i(77988),s=i(31586),n=i(68708);t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime}},73389:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const r=i(51168);t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const r=i(51168),s=i(19851),n=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,s.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?T(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function b(e){if((0,o.isNumber)(e))return Math.floor(T(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function S(e,t){if(null==e||e<0)return;let i=e;const r=()=>{const e=i%100;return i=Math.floor(i/100),e},s=10*r(),n=r(),a=r(),l=(0,o.toGt0)(r()),u=(0,o.toGt0)(r()),c=(0,o.toGt0)(r());return{year:i,month:c,day:u,hour:l,minute:a,second:n,millisecond:s,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=S(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function _(e,t){return T(Date.now()-e,t)}function T(e,t){return w(r.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,(s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])}},42499:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLuxon=void 0;const r=i(51168),s=i(19851),n=i(19043),a=i(28874);t.setupLuxon=(0,s.lazy)((async()=>{r.Settings.throwOnInvalid=!1,a.Settings.twoDigitCutoffYear.watch((e=>r.Settings.twoDigitCutoffYear=e)),r.Settings.defaultLocale=await(0,n.locale)()}))},17415:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,n.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const r=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=r&&Math.abs(r-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(r)}t.isUTCZone=function(e){return b(e)||0===S(e)?.offset(Date.now())},t.normalizeZone=S,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=_,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:_(i)};const T=/\b(?Z|UTC|GMT)\b/,M=/(?[-±+−])/,E=/[-−]/,k=/(?[01]\d)/,D=/(?[01]?\d)/,x=/(?::(?\d\d))/;function C(e){return b(e)?0:A((0,t.TimezoneOffsetRE)().exec(e))}function A(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=E.test((0,h.toS)(e.groups.tzSign))?-1:1,r=(0,l.toInt)(e.groups.tzMinutes)??0,s=null==t?void 0:i*(60*t+r);return v(s)?s:void 0}t.TimezoneOffsetRE=(0,n.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),T,new m.RegExpEscaped("|"),M,k,m.RegExpOptional.from(x),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=A;const F=/\b(?(?:Etc\/)?GMT)\b/,I=(0,n.lazy)((()=>(0,m.concatRegexp)([F,M,D,m.RegExpOptional.from(x)])));function O(e){return A(I().exec(e))}t.ianaZoneToOffsetMinutes=O,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=O(e)??C(e);if(null!=i)return _(i);if(null!=t){const i=S(e);if(null!=i)return _(i.offset(t))}}},88600:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),v=(0,s.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),w=(0,s.lazy)((()=>(0,n.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),b=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,p.datedToISO)(e)))))),S=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,y.datedToLocal)(e)))))),P=(0,s.lazy)((()=>(0,n.compact)(w().map((e=>(0,m.datedToMillis)(e))))));function _(e){if(null==e)return!1;const t=M(e);return v().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return _(e)?e:void 0},t.isValidDate=_;const T=String(new Date("bad"));function M(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===T)return T;const t=(0,n.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,E())&&s.push("year is in the future"),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const r=(0,m.datedToMillis)(e);(0,u.gt)(r,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):S().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):b().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(t)).join("; "))}catch(t){return v().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=M;const E=(0,s.lazy)((()=>r.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return _(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==M({year:e,month:t,day:i})}},51275:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const r=i(77988),s=i(31586),n=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&(e instanceof n.DateInterval||e instanceof r.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==r.UnsetZoneName&&e.zone.offset(Date.now())!==r.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===r.UnsetZoneName?void 0:e.zone?.name:e instanceof r.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const r=i(50989);t.AutoVacuumModes=(0,r.strEnum)("NONE","FULL","INCREMENTAL")},82261:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=void 0;const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056);t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h}},92407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLiveDbDir_=t.cacheDbFile_=void 0;const r=i(19851),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.lazy)((()=>(0,n.mkLogger)("db.CheckLocalDbReplica")));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}t.cacheDbFile_=h,t.getLiveDbDir_=async function(e=a.Settings.libraryDir.valueOrDefault){if(!a.Settings.forceLocalDbReplica.valueOrDefault){const t=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(e),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!1}}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:t,error:e})}}const t=await h({libraryDir:e,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(t.parent()),{db:t,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:t,error:e})}}},5531:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const r=i(50989);t.CheckpointTypes=(0,r.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},55332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=void 0;const r=i(19851),s=i(50213),n=i(76187),a=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbBackupCold")));t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[];try{for(const r of(0,n.sqliteFiles)(e)){const e=t.join(r.base).wip();i.push(e),await r.copyFile_(e)}return a().tap({msg:"completed",level:"info",result:await Promise.all(i.map((e=>e.unwip_()))),meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map((e=>e.unlink()))),e}}},91872:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=void 0;const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)((()=>(0,r.mkLogger)("db.DbRetries")));t.handleDbRetries_=function(e,t,i,r){const a=Date.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)(e,(async()=>{for(;Date.now()=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}))}},12943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toDbValued=t.isDbValued=t.isDbValue=void 0;const r=i(79842),s=i(66649),n=i(40958),a=i(68708);function o(e){return null===e||(0,n.includes)(["number","string"],typeof e)}t.isDbValue=o,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,a.entries)(t).every((([,e])=>o(e)))},t.toDbValued=function(e){return(0,a.mapFields)(e,((e,t)=>{if(!e.startsWith("$"))return"boolean"==typeof t?[e,t?1:0]:o(t)?[e,t]:(0,r.isDated)(t)?[e,(0,s.datedToMillis)(t)]:void 0}))}},65753:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxBatchPluckSize=void 0;const r=i(19851),s=i(7282),n=i(28874);t.maxBatchPluckSize=(0,r.lazy)((()=>Math.round(n.Settings.dbBatchSelectSize.valueOrDefault*((0,s.isTest)()?.25:5))))},80632:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pageSizeBytes=t.mkdb_=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(54993),u=i(50213),c=i(23560),d=i(65211),h=i(29882),f=i(53265),m=i(66430),p=i(66184),g=i(28874),y=i(15674),v=i(87550);function w(){const e=g.Settings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,a.clamp)(1,28,Math.round(Math.log2(e))))}t.mkdb_=function({nativePath:e,timeoutMs:t=g.Settings.dbBusyTimeoutMs.valueOrDefault,logSql:i=g.Settings.logSql.valueOrDefault}){e=(0,f.resolve)(e),(0,h.mkdirpSync_)((0,r.dirname)(e));const b=(0,h.posixPathFromGrandparent)(e),S=(0,m.nativePathSizeSync)(e),P=(0,u.mkLogger)("db.mkdb("+b+")");if(null!=S){const E=Math.round(S/o.MiB),k=Math.ceil(1.5*E);k>g.Settings.dbCacheSizeMb.valueOrDefault&&(P.info("Dynamically setting dbCacheSize to "+g.Settings.dbCacheSizeMb.value,{db:e,dbFileSizeMb:E}),g.Settings.dbCacheSizeMb.envValue=k);const D=Math.round(1.5*E);D>g.Settings.maxMemoryMb.valueOrDefault&&(P.warn("Large database: setting maxMemoryDb to "+D+"MB",{dbFileSizeMb:E,"Settings.maxMemoryMb":g.Settings.maxMemoryMb.valueOrDefault}),g.Settings.maxMemoryMb.envValue=D)}P.info("Opening "+e+"...");const _={fileMustExist:!1,readonly:!1};if((0,a.gt0)(t)&&(_.timeout=Math.ceil(t)),i){const x=(0,u.mkLogger)("SQLite("+b+")"),C=(0,p.defaultLogLevel)();function A(e,...t){var i;(0,n.blank)(e)||x.log(C,(i=e,(0,l.toS)(i).replace(/\s{2,}/g," ")),{args:t})}_.verbose=A}const T=new v(e,_);P.info("Open. Setting PRAGMAs...");for(const F of(0,s.compact)(['encoding = "UTF-8"',"threads = "+(0,y.maxCpus)(),"foreign_keys = ON","page_size = "+w(),"trusted_schema = 0","cache_size = -"+Math.round(g.Settings.dbCacheSizeMb.valueOrDefault*o.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL",(0,a.gt0)(g.Settings.dbBusyTimeoutMs.valueOrDefault)?"busy_timeout = "+g.Settings.dbBusyTimeoutMs.valueOrDefault:null,"temp_store = MEMORY","synchronous = "+g.Settings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,c.isDbJanitorService)()?(0,l.toS)(g.Settings.dbWalAutoCheckpoint.valueOrDefault):"0"),"auto_vacuum = "+g.Settings.dbAutoVacuumMode.valueOrDefault]))P.tapThunk({msg:"PRAGMA "+F,result:()=>T.pragma(F)});const M=T;return M.__uid=(0,d.uid)(),M},t.pageSizeBytes=w},99315:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},95704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withIdBatches=void 0;const r=i(40958),s=i(31586),n=i(59455),a=i(65753),o=i(51040);t.withIdBatches=async function(e){const t=(0,s.toGt0)(e.batchSize)??(0,a.maxBatchPluckSize)(),i=(0,o.dbValueToEscapedString)(e.primaryKeyColumnName),l=(0,r.compactBlanks)([i+" > :min",...(0,n.toA)(e.whereClauses)]).join(" AND "),u=e.db.prepare((0,r.compactBlanks)(["SELECT "+i,"FROM "+(0,o.dbValueToEscapedString)(e.tableName),"WHERE "+l,"ORDER BY "+i,"LIMIT :limit"]).join(" "));let c=-1;for(;;){const i=u.pluck().all({min:c,limit:t});if(0===i.length)return;await e.fn(i),c=(0,r.last)(i)}}},76187:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSqliteFile=t.sqliteSizeBytes=t.sqliteFiles=void 0;const r=i(17217),s=i(87391),n=i(7311);t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map((t=>e.sibling(e.base+t)))].filter((e=>e.existsSync({refresh:!0})))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)};const a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map((e=>n.SqliteExt+e))];t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1}},51040:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitBatchSql=t.dbValueToEscapedString=void 0;const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`};const o=/--.+$/gm,l=/\s+/g;t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(/;/).map((e=>e.replace(o,"").replace(l," ").trim()))),i=[];let s;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assertDirSQLiteReadWrite_=t.isDirSQLiteReadWrite=t.firstDirSQLiteReadWrite=void 0;const r=i(19851),s=i(50357),n=i(30976),a=i(50213),o=i(95696),l=i(80632),u=i(76187),c=(0,r.lazy)((()=>(0,a.mkLogger)("db.SQLiteReadWrite")));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=o.PosixFile.for(e),i=(0,n.randomChars)(8),r=t.child(".test-"+i+".sqlite");let a=null;try{await t.mkdirp_(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3}),a.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)"),a.exec(`INSERT INTO t (s) VALUES ('${i}')`);{const e=a.prepare("SELECT s FROM t").all();(0,s.eql)(e,[{s:i}])||c().throw("unexpected rows",{rows:e})}a.exec("VACUUM"),a.close(),a=(0,l.mkdb_)({nativePath:r.nativePath,timeoutMs:1e3});{const e=(0,n.randomChars)(8);a.exec(`INSERT INTO t (s) VALUES ('${e}')`);const t=a.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(t,[i,e].sort())||c().throw("unexpected rows",{rows:t})}}finally{try{a?.close()}catch{}await Promise.all((0,u.sqliteFiles)(r).map((e=>e.rm())))}}t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h},87391:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},27180:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(5916),s=i(84777),n=i(89966),a=i(63870),o=i(87550);t.sqliteVersion_=(0,r.lazyAsync)({desc:"db.sqliteVersion",later:async function(){let e;try{e=new o(":memory:");const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,n.sqliteNativePath_)(),r=(await(0,s.stdout_)(i,["-version"],{timeoutMs:(0,a.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:r.split(/\s+/,1)[0],fullToolVersion:r,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,a.commandTimeoutMs)()})},15056:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models"),t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=n(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),b=i(29882),S=i(45969),P=i(43334),_=i(28874),T=i(41692),M=i(32774),E=i(80612),k=i(32551),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function x(){if((0,S.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function C(){if((0,S.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:M.DefaultDockerLibraryDir},...x()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,k.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,k.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,k.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...x()),i}t.tmpCacheDirs=x,t.tmpDirs=function(){return(0,E.filterDirs)({dirs:x(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,E.firstDir)({dirs:C(),desc:"cache"})));const A=(0,d.lazy)((()=>{(0,T.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(F)}));function F(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{A();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,b.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=F},46292:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const r=i(19851),s=i(45969),n=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,r.lazy)((()=>((0,n.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,s.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,s.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},79960:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(45255),o=i(84777),l=i(16287),u=i(57902),c=i(43334),d=(0,r.lazy)((()=>(0,n.mkLogger)("dir.DefaultApplePhotosLibrary"))),h=["read","com.apple.photolibraryd","SystemLibraryPath"];t.defaultApplePhotosLibrary=async function(){if(c.isMac)try{const e=await(0,o.stdout_)("defaults",h,{timeoutMs:a.ShortCommandTimeoutMs});if((0,s.blank)(e))return void d().warn(`"defaults ${h.join(" ")}" returned blank (!!)`);{const t=await(0,l.isReadableDirectory)(e);return d().tap({msg:"defaultApplePhotosLibrary()",level:u.LogLevels.info,result:t?e:void 0,meta:{isReadable:t}})}}catch(e){return void d().warn("defaultApplePhotosLibrary()",e)}}},32774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const r=i(66430),s=i(45969),n=i(32774);t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),s.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(s.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,s.default.resolve((0,d.homeDir)(),".config")),(0,n.compactBlanks)(e).map((e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const r=i(22573),s=i(96706),n=i(29882);t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const r=i(44652),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()}))},35280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const r=i(29882),s=i(49776),n=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,r.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[n.libraryDataDir,n.libraryPreviewsDir,s.cacheDir])if((0,r.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},48195:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyNotLibraryDir=t.isLibraryDir=void 0;const r=i(19851),s=i(22573),n=i(98553),a=i(12168),o=i(50213),l=i(15056),u=i(98314),c=i(17217),d=i(16287),h=i(2858),f=i(87290),m=(0,r.lazy)((()=>(0,o.mkLogger)("dir.IsLibraryDir")));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g},9595:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const r=i(22573),s=i(54993),n=i(29882),a=i(28874);function o(e){return(0,r.toNotBlank)((0,s.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const r=i(40958),s=i(55835),n=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function b(e){return y(w(e),!1)}function S(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(S(e))}function _(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function T(e){return y(_(e))}async function M(e){return y((0,s.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,r.uniq)([t,i,await b(t),await P(t),await T(t),await M(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=b,t.libraryPreviewsDirPosixFile=S,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=_,t.setupLibrarySyncReportsDir_=T,t.setupLibraryDbDir_=M},46296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function b(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:s.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>s.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function S(){return(0,v.firstDir)({dirs:b(),desc:"logs"})}t.defaultLogDirs=b,t.defaultLogDir_=S,t.logDir=(0,n.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:S()}catch(e){return console.error("defaultLogDir_() failed",e),s.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,s.lazy)((async()=>{if(o.isWin){const e=await c();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,s.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,r.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const r=i(38639),s=i(7282),n=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const r=i(38639),s=i(44198);t.doNotTrack=function(){return(0,r.isTrue)((0,s.env)().DO_NOT_TRACK)}},44198:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),b=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>a.default.env[e])).join(n.delimiter).split(n.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,n.join)((0,m.homeDir)(),".psenv"));const t=(0,b.SensitiveEnvRE)(),i={...a.default.env};for(const r of e)try{const e=(0,d.debom)(s.default.readFileSync((0,g.resolve)(r))),n=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,r]of(0,c.entries)(n))t.test(e)||(i[e]=r)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+r,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const r=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const r=i(50989);t.EnvKeys=(0,r.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const r=i(22573),s=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,r.blank)(e))return i;let n;for(const a of(0,s.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(n=e.exec(a));){if(null==n.groups)continue;const{key:e,val:s}=n.groups;if((0,r.blank)(e)||null==s)continue;const a=s.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const s=r(i(1708)),n=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,n.lazy)((()=>(0,a.firstNotBlank)(s.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,s.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,n.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,n.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const r=i(58587),s=i(19851),n=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function b(...e){if((0,n.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,n.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,n.uniqSubstrings)(S((0,l.flatten)(i)))}function S(e){return(0,n.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,n.uniqSubstrings)(S(e)),r=t?.maxLen??400,s=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),r-a.length,s)+a.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(b(e),t)}t.StartTs=Date.now(),t.logger=(0,s.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new r.Rate,t.fatalErrorRate=new r.Rate,t.internalErrorRate=new r.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=b,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,r=7){return(0,a.blank)(e)&&(e=t.MissingError),_(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,r).join("; ")}},41954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const r=i(40958),s=i(26905),n=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,n.map)((0,s.errorErrno)(i),(e=>t.push(u.get(e)))),(0,n.map)((0,s.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,r.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},68301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorStore=t.ExtraEventsForPlease=void 0;const r=i(19851),s=i(42659),n=i(75240),a=i(55835),o=i(31586),l=i(68708),u=i(59455),c=i(54993),d=i(50213),h=i(45255),f=i(37628),m=i(99331),p=i(46292),g=i(38835),y=i(32144),v=i(29882),w=i(95696),b=i(55222),S=i(28874),P=(0,r.lazy)((()=>(0,d.mkLogger)("error.EventStore")));function _(e){return(0,l.omit)(e,"breadcrumbs")}t.ExtraEventsForPlease=7;class T{constructor(e){this.root=e}datedRoot(e=new Date){return this.root.join((0,c.toS)(e.getFullYear()),(0,c.toS)(e.getMonth()+1))}rmrf(){return this.root.rmrf()}msg2file(e){return this.datedRoot(new Date(e.timestamp*s.secondMs)).join((0,f.shortStringSha)(e.message,8,b.GeoRadix)+".json")}async eventsFrom(e=new Date,t=s.dayMs){const i=e.getTime(),r=i-t,a=i+t;return P().tap({msg:"eventsFrom()",result:(0,u.toA)(await this.datedRoot(e).clear().childFiles((async e=>P().tap({msg:"eventsFrom().childFiles() accept "+e.base,result:(0,y.isJsonExt)(e)&&!(0,v.isHiddenBasename)(e.base)&&(0,o.within)(r,a,e.mtimeMs())})))),meta:{when:e,deltaMs:(0,n.fmtDuration)(t)}})}async eventCount(e=new Date){return(await this.eventsFrom(e)).length}async eventQuotaExceeded(e){const i=(0,c.toS)(e).includes(g.PleaseSendErrorFlag)||(0,c.toS)(e.message).includes(g.PleaseSendErrorFlag),r=await this.eventCount(),s=S.Settings.maxErrorsPerDay.valueOrDefault+(i?t.ExtraEventsForPlease:0);return P().tap({msg:"eventQuotaExceeded()",result:r>=s,meta:{event:_(e),recentEventCount:r,maxErrorsPerDay:s,pleaseSend:i}})}async maybeSendEvent(e){if(e.timestamp=Math.floor(e.timestamp),(0,m.ending)())P().error("maybeSendEvent(): REJECT: we're ending.",{event:_(e)});else if(await this.eventQuotaExceeded(e))P().error("maybeSendEvent(): REJECT: too many recent events.",{event:_(e)});else try{const t=await this.writeEvent_(e);return P().tap({msg:"maybeSendEvent(): "+t==null?"REJECT: previously sent this event already this month":"ACCEPT",result:null!=t?e:void 0,meta:{eventFile:t}})}catch(e){return void P().error("maybeSendEvent(): REJECT: failed to write event.",e)}}writeEvent_(e){return this.msg2file(e).applyIfEmpty_({fn_:t=>t.writeJson_(e),minSizeBytes:3,returnUndefinedIfNotEmpty:!0,timeoutMs:h.ShortCommandTimeoutMs})}}t.ErrorStore=T,T.instance=(0,r.lazy)((()=>(0,a.map)((0,p.configDir)(),(e=>new T(w.PosixFile.for(e).join("events"))))))},70025:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const r=i(40958),s=i(38639),n=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,r.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function b(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function S(e){return!!((0,s.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||b(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=b,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===S(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=S;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const r=i(22573),s=i(31586),n=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,r.blank)(e)&&(0,n.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const s=!0===i.fatal,c=!0===i.ignorable;if(!s&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),s&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!s||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!s||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),s}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,s.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,s.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,s.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,s.blank)(i.message)||e.message.includes(i.message)))return e;const r=(0,s.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(r??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,r.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,s.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,n.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,n.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,n.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=t?.path;return(0,s.blank)(r)||(i=(0,h.dedupeNeedle)(i,r,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,r.set(this,new Map),s.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(n(this,r,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=n(this,r,"f").get(e);return null!=a&&(a.resolve(t),n(this,r,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(n(this,s,"f").get(e),clearTimeout),n(this,s,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},r=new WeakMap,s=new WeakMap},34102:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(78474),s=i(19851),n=i(15197);t.ee=(0,s.lazy)((()=>{const e=new r.EventEmitter;return e.setMaxListeners(70),new n.CapturingEventEmitter(e)}))},41293:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiHealthRouter=void 0;const s=r(i(7252)),n=i(45599),a=i(18454),o=i(51773);t.ApiHealthRouter=class{constructor(e="/api/health"){this.mountpoint=e,this.router=(0,n.defer)((()=>s.default.Router().get(this.mountpoint,(0,o.wrap)(this.constructor.name+".health",this.health)))),this.health=async(e,t)=>{t.json(await a.HealthCheck.awaitSettled())}}}},51773:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableCache=t.truthyQuery=t.extractLang=t.requestLang=t.extractTagPath=t.jsonOrRedirect=t.getSeedOrRedirect=t.getFit=t.getSeed=t.wrap=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(97790),u=i(97238),c=i(99036),d=i(41942),h=i(54993),f=i(48884),m=i(50213),p=i(97352),g=i(56038),y=i(38835),v=i(57159),w=i(51140),b=i(68178),S=i(62327),P=(0,r.lazy)((()=>(0,m.mkLogger)("express.Handlers")));function _(e){return(0,l.opt)(e).filter(n.notBlank).map(h.toS).map((e=>e.split(","))).map(s.compactBlanks).map((e=>e.map((e=>e.split(";").map((e=>e.trim())))))).flatMap((e=>(0,f.greatestBy)(e,(([,e])=>(0,p.firstGt0)((0,p.extractFloat)(e),1))))).map((([e])=>e)).get()}t.wrap=function(e,t){return async(i,r,s)=>(0,g.time)(e,(()=>(0,S.wrapWithToast)({f:()=>t(i,r,s),response:r})))},t.getSeed=function(e){return(0,u.toSeed)(e.query.seed)},t.getFit=function(e){return c.ThumbFits.validOrElse((0,h.toS)(e.query.fit),c.ThumbFits.square)},t.getSeedOrRedirect=function(e,t){const i=(0,u.toSeed)(e.query.seed);if(null==i){let i=(0,b.requestedUri)(e);"/tag/"===i.path&&(i=i.with({path:"/tag"})),i.query.append("seed",(0,h.toS)((0,u.prngSeed)())),t.redirect(i.toString())}return i},t.jsonOrRedirect=function(e,t){if(null==e)return(0,S.sendErrorToast)(new v.WrappedError("Internal error: jsonOrRedirect(null)"+y.InternalErrorFlag,{fatal:!1,doNotSend:!0}),t,404);for(const i of[d.XLocationRedirect,d.XLocationReplace]){const r=e[i];(0,n.notBlank)(r)&&(P().debug("jsonOrRedirect(): "+i,r),t.setHeader(i,r),t.status(w.HttpStatus.SeeOther))}return t.json(e)},t.extractTagPath=function(e){const t=e.replace(/^(?:\/api)?\/tag\/?/,""),i=t.split("/").map(decodeURIComponent),r=(0,n.blank)(t)?[]:i;return P().info("extractTagPath()",{path:e,result:r,trimmed:t,tagPath:i}),r},t.requestLang=function(e){const t=e.headers["accept-language"];return _(Array.isArray(t)?t.join(","):t)},t.extractLang=_,t.truthyQuery=function(e,t){return(0,o.mapOr)(e.query[t],(e=>!(0,a.isFalse)(e)),(()=>!1))},t.disableCache=function(e){e.setHeader("Cache-Control","no-store, max-age=0"),e.setHeader("Pragma","no-cache"),e.setHeader("Expires","Fri, 01 Jan 1990 00:00:00 GMT")}},68259:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onFinished=void 0,t.onFinished=function(e,t){let i=!1;e.on("error",(r=>{i||(i=!0,t(r,e))}));const r=()=>{i||(i=!0,t(null,e))};for(const t of["end","finish","close"])e.on(t,r);return e}},27821:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.redirectRouter=void 0;const s=r(i(7252)),n=i(49586),a=i(51140),o=i(62327);t.redirectRouter=function(e){return s.default.Router().use(((t,i)=>(0,n.isAjaxRequest)(t.headers)?(0,o.sendRedirectionToast)({response:i,redirectOrReplace:"redirect",url:"/splash"}):i.redirect(a.HttpStatus.Found,e)))}},40749:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.referrer=t.isXhr=void 0;const r=i(54993),s=/^XMLHttpRequest$/i;t.isXhr=function(e){return e.xhr||null!=s.exec((0,r.toS)(e.header("X-Requested-With")))},t.referrer=function(e){return e.header("Referer")}},78147:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RequestLogger=void 0;const r=i(7252),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(50213),u=i(8769),c=i(18454),d=i(51576),h=i(43705),f=i(82647),m=i(28874),p=i(51140),g=i(68259),y=i(68178);t.RequestLogger=class{constructor(){this.logger=(0,l.mkLogger)("web.RequestLogger"),this.responseTimes=new f.Average,this.accessLogger=m.Settings.logWebRequests.valueOrDefault?new h.LogWriter((0,n.firstNotBlank)(m.Settings.logWebDir.valueOrDefault,m.Settings.logDir.valueOrDefault),{processName:(0,s.lazy)((()=>"webrequest"))}):void 0,this.router=(0,r.Router)().use(((e,t,i)=>{const r=Date.now(),s=e.method,n=`${e.protocol?.toUpperCase()}/${e.httpVersion}`,l=`${s} ${(0,y.requestedUri)(e)} ${n}`,h=e.path.startsWith("/sse/")||"/updates"===e.path||"/api/splash"===e.path||"/api/status"===e.path?void 0:setTimeout((()=>this.logger.warn("Request is still processing: "+l,{elapsedMs:Date.now()-r})),4*(this.responseTimes.p84??a.secondMs));(0,g.onFinished)(t,(i=>{(0,o.map)(h,clearTimeout),null!=i&&(0,u.onError)(l,{error:i});const a=p.HttpStatusIs.success(t.statusCode)||p.HttpStatusIs.redirect(t.statusCode),f=Date.now()-r,m={from_ip:e.ip,protocol:n,method:s,statusCode:t.statusCode,ok:a,elapsedMs:f,runState:c.HealthCheck.runState(),userAgent:e.headers["user-agent"]};null!=i&&(m.error=i),this.responseTimes.push(f),(0,d.logBroadcaster)()?.log(a?"info":"warn","HttpRequestLogger",l,m),this.accessLogger?.log("info","",l,m),null==d.logBroadcaster.prior()&&null==this.accessLogger&&this.logger.log(null==i&&a?"debug":"warn",l,m)})),i()}))}}},68178:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addXSettingsHandler=t.requestedUri=void 0;const r=i(19851),s=i(41400),n=i(98553),a=i(37805),o=i(89724),l=i(34102),u=i(81674),c=i(28874),d=i(34238),h=i(69385),f=(0,r.lazy)((()=>({protocol:"http",host:c.Settings.hostname.valueOrDefault??"localhost",url:"/"})));t.requestedUri=function(e,t){const i={...f(),...t};return d.URI.parse((e?.protocol??i.protocol)+"://"+(e?.headers?.host??i.host)+(e?.originalUrl??i.url))};const m=(0,r.lazy)((()=>"lite"));async function p(){m.set(await(0,u.t)()),y.unset()}const g=(0,r.lazy)((()=>(0,c.isProd)()?"":"+"+(0,o.nowLocal)())),y=(0,r.lazy)((()=>{const e={ver:a.version+g(),paused:(0,h.isPaused)(),ll_vh:c.Settings.lazyLoadExtraVh.valueOrDefault,tier:m()};return Buffer.from((0,n.stringify)(e)).toString("base64")}));(0,s.later)((()=>{(0,l.ee)().on("settingsChanged",(()=>y.unset())),(0,l.ee)().on("reloadLicenses",p),u.m.watch(p),(0,l.ee)().on("pause",(()=>y.unset())),(0,l.ee)().on("resume",(()=>y.unset()))})),t.addXSettingsHandler=function(e,t,i){t.setHeader("X-Settings",y()),i()}},43394:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serveStaticGz=void 0;const r=i(22573),s=i(54993),n=i(50213),a=i(56639),o=i(81168),l=i(38835),u=i(83278),c=i(14036),d=i(51773),h=/\.asar\/?/i;t.serveStaticGz=async function(e){const t=(0,n.mkLogger)("serveStaticGz"),i=u.BaseFile.for(e),f=await i.descendants((e=>e.ext.endsWith(".gz"))),m=(0,a.toMap)(f,(e=>(0,r.mapNotBlank)((0,c.extMimetype)((0,o.stripSuffix)(e.ext,".gz")),(t=>["/"+(0,o.stripSuffix)(e.posixPathFrom(i),".gz"),{contentType:t,nativePath:e.nativePath}]))));return t.debug("ready to serve",[...m.keys()]),0===m.size&&t.error("Can't read "+i+". Please visit https://forum.photostructure.com/ for help."+l.FatalErrorFlag),(0,d.wrap)("serveStaticGz",(async(e,i,r)=>{if(null!=e.path.match(h))return i.sendStatus(404);const n=m.get((0,s.toS)(e.path));return null==n?r():(t.debug("get",{path:e.path,result:n}),i.set("Content-Encoding","gzip"),i.set("Content-Type",n.contentType),i.sendFile(n.nativePath))}))}},18405:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSentEventsRouter=void 0;const s=r(i(7252)),n=i(40958),a=i(22573),o=i(25764),l=i(38836),u=i(36868),c=i(72901),d=i(51773);class h extends l.EndableWrapper{constructor(e){super("SSERouter("+e+")",(()=>this.close()),o.EndableRanks.first),this.path=e,this.streams=[]}router(){return s.default.Router().get(this.path,(0,d.wrap)(this.name,this.updates.bind(this)))}async close(){await Promise.all(this.streams.map(u.endStream)),this.streams.length=0}async updates(e,t){if(this.ended)return void t.sendStatus(503);this.logger.info("Sending updates to "+(e.ip??e.ips));const i=(0,u.remoteDesc)(e.socket);t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"}),this.streams.push(t),t.once("error",(e=>{(0,n.removeSame)(this.streams,t),this.logger.warn("onError("+i+")",{error:e})})),t.once("close",(()=>{(0,n.removeSame)(this.streams,t),this.logger.debug("stream to "+i+" closed. ("+this.streams.length+" remain)")}));const r=(0,n.compact)(this.firstEvents(e,t));(0,n.isNotEmpty)(r)&&(this.logger.info("firstEvents",{firstEvents:r}),t.write((0,c.mkEventStream)(...r)))}endStream(e){(0,u.endStream)(e).catch((()=>{})),(0,n.removeSame)(this.streams,e)}writeToStreams(...e){const t=(0,c.mkEventStream)(...e);if(this.logger.info("writeToStreams",{events:e,payload:t}),!(0,a.blank)(t))for(const e of this.streams)if(!0===e?.closed||null==e?.socket)this.endStream(e);else try{e.write(t)}catch(t){null==e.socket||e.closed?this.endStream(e):this.logger.warn("writeToStreams failed to write to stream",{stream:(0,u.remoteDesc)(e.socket),error:t})}}}t.ServerSentEventsRouter=h},62327:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapWithToast=t.expressErrorHandlerWithToast=t.sendErrorToast=t.send404Toast=t.sendWarningServerToast=t.sendRedirectionToast=t.sendServerToast=t.requireEnabled=t.requirePlus=void 0;const r=i(19851),s=i(55835),n=i(41942),a=i(71050),o=i(27776),l=i(41583),u=i(50213),c=i(98314),d=i(70025),h=i(81674),f=i(49586),m=i(51140),p=i(68178),g=(0,r.lazy)((()=>(0,u.mkLogger)("express.ServerToastHelpers")));function y({response:e,toast:t,httpStatusCode:i,reload:r}){return(0,s.map)(i,(t=>e.status(t))),g().warn("sendServerToast()",{requestedURI:(0,p.requestedUri)(e.req),toast:t,httpStatusCode:i}),e.json({toast:t,reload:r})}function v(e,t,i){g().warn("sendErrorToast",e);const r=(0,d.stripErrorFlags)((0,c.errorToS)(e));y({response:t,toast:{text:404===i?"Not found":"Well, darn, that didn't work",uuid:r,details:r,type:(0,d.isFatalError)(e)?"error":"warning",button1Text:"Return home",button1Url:"/"+a.DismissAnchor,button1Class:"info",onClickUrl:a.DismissAnchor},httpStatusCode:i??m.HttpStatus.ServiceUnavailable})}t.requirePlus=async function(e,t,i){if(await(0,h.l)()){const e={toastPlusOnly:!0};return t.status(m.HttpStatus.Forbidden),t.json(e)}return i()},t.requireEnabled=function(e){return(t,i,r)=>e.valueOrDefault?r():y({response:i,toast:{text:"This has been disabled by your administrator.",details:`(see setting "${e.name}")`,type:"warning"},httpStatusCode:m.HttpStatus.Forbidden})},t.sendServerToast=y,t.sendRedirectionToast=function({response:e,toast:t,url:i,redirectOrReplace:r}){if((0,f.isAjaxRequest)(e.req.headers)){const s="replace"===r?n.XLocationReplace:n.XLocationRedirect;return e.setHeader(s,i),g().warn("sendRedirectionToast()",{requestedURI:(0,p.requestedUri)(e.req),toast:t,key:s,url:i}),e.json({toast:t})}return e.redirect(i)},t.sendWarningServerToast=function({response:e,toast:t,httpStatusCode:i,reload:r}){return t.type??(t.type="warning"),y({response:e,toast:t,httpStatusCode:i,reload:r})},t.send404Toast=function({text:e,details:t,response:i,httpStatusCode:r=404}){return y({response:i,toast:{text:e,details:t,type:"warning",button1Text:"Go home",button1Url:(0,o.mkHomeFullPath)()+a.DismissAnchor,button1Class:"info",onClickUrl:a.DismissAnchor,timeout:!1},httpStatusCode:r})},t.sendErrorToast=v,t.expressErrorHandlerWithToast=function(e,t,i,r){null==e?r():v(e,i)},t.wrapWithToast=async function({f:e,response:t}){try{await e()}catch(e){(0,s.map)((0,l.toErr)(e),(e=>v(e,t)))}}},30576:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.viewRouter=void 0;const s=r(i(7252)),n=i(51773);t.viewRouter=function({path:e,view:t,modeler:i}){return s.default.Router().get(e,(0,n.wrap)(t+"Router",(async(e,r)=>{const s=await(i?.(e,r))??{};return s.nonce=r.locals?.cspNonce,r.render(t,s)})))}},64660:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const s=r(i(73024)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>n.default.geteuid?.())),h=(0,a.lazy)((()=>n.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(s.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,s.default.constants.R_OK|s.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,s.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??d(),o=null!=n?[n]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!r||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const r=await(0,u.statMaybe)(i);if(null!=r){if(!r.isDirectory())return!1;if(t){if(!p(r,e))return!1}else if(t=!0,!m(r,e))return!1}}return!0},t.access=g},21144:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const s=r(i(76760)),n=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,n.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),r=await m(i.dir);for(const e of await(0,d.readdir_)(r))if((0,a.equalsIgnoreCase)(e.basename,i.base))return s.default.join(r,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const r=i(73024),s=i(76760);function n(e){return[...a(e)]}function*a(e){for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function o(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=n,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return n(e).find((e=>l(e,t)))}},83278:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),v=f(i(1708)),w=i(46466),b=f(i(57975)),S=f(i(38522)),P=i(19851),_=i(40958),T=i(5233),M=i(22573),E=i(42659),k=i(50357),D=i(96249),x=i(98553),C=i(55835),A=i(31586),F=i(68708),I=i(97790),O=i(39926),L=i(51926),R=i(59455),N=i(54993),B=i(48884),j=i(22911),z=i(99331),V=i(56519),W=i(56038),U=i(31562),q=i(76850),H=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Y=i(43334),X=i(81168),Z=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),re=i(84542),se=i(89968),ne=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),be=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const Se=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(r.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),s.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(s=new WeakMap,a=new WeakMap,r=new WeakSet,b.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,M.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=Se().get(i);if(null!=r)return r;const s=(0,fe.resolve)(i),n=new Pe(s,t);return Se().set(i,n),Se().set(s,n),n}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(se.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,s,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,X.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new se.DirectoryEntry(this.dir,new se.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,s,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,r,"m",n).call(this)??await d(e=this.clearThisAndParent(),r,"m",n).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const r of i)t.push(...(0,R.toA)(await r.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,A.gt0)(t))return;const i=await d(this,s,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const r of i)if(r.isDirectory()){const i=await this._directoryEntryChild(r).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,k.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,O.pad2)(t+1),(0,O.pad2)(i))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,E.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>=(0,E.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,E.unixtime)(t)>(0,E.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,U.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*E.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,q.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,be.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),re.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,x.stringify)(e,t?.replacer,t?.spaces),(0,F.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,T.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,z.ending)()?1:3,timeoutMs:0,retryDelay:E.secondMs,errorIsRetriable:H.isRetriableError})}async gunzip(){return d(this,r,"m",o).call(this,(0,X.stripSuffix)(this.base,".gz"),S.default.createGunzip())}async gzip(){return d(this,r,"m",o).call(this,this.base+".gz",S.default.createGzip())}async compressBrotli(){return d(this,r,"m",o).call(this,this.base+".br",S.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,ne.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,ne.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(S.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,_.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort(((e,t)=>-(0,Z.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===r)return e}))}firstMatchingLine(e){const t=new j.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,L.newlineRe)(),(r=>{const s=e.exec(r);null!=s&&(t.maybeResolve(s),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const r of e)for(const e of i)if((0,A.closeTo)(r,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new j.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),_e)try{const r=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(r,s)=>{try{const n=await e.f(r,(0,C.denull)(s));t(n)&&i.resolve(n)}catch(e){i.reject(e)}}));i.finally((()=>{r.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,A.gt0)(e.intervalMs)){const r=setInterval((async()=>{try{const r=await e.f();t(r)&&i.resolve(r)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||r.unref(),i.finally((()=>{clearInterval(r)}))}return i}}t.BaseFile=Pe,n=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,X.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Z.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*E.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},19748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const r=i(28874),s=i(88840),n=i(14036),a=i(29882);function o(e){return t=>r.Settings.respectFileExtensions.valueOrDefault?(0,n.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(s.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(s.ExtTypes.Video),t.isAssetFileExtension=o(s.ExtTypes.AssetFile)},84542:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))}},70698:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,s.lazy)((()=>(0,n.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(n.default.env.SYSTEMROOT,(e=>[e,s.default.join(e,"System32"),s.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=n(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),b=i(16287),S=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class T{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new T(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await o.stat(t);return new T(i,new P(r,s))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return T.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new T(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>T.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new T(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,b.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=T},20197:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),v=i(54557),w=i(50213),b=i(88158),S=i(56519),P=i(46292),_=i(32551),T=i(35280),M=i(87290),E=i(96706),k=i(57902),D=i(43334),x=i(78984),C=i(33995),A=i(28874),F=i(21144),I=i(83278),O=i(48313),L=i(85772),R=i(78133),N=i(46356),B=i(17217),j=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),z=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=z.get(t);if(null!=i)return i;const r=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),s=V.test(t)||r.isDirectorySync(),n=(0,R.native2posix)(r.nativePath),a=s?(0,m.ensureSuffix)(n,"/"):n;return z.set(t,a),z.set(a,a),z.set(r.nativePath,a),a}t.formatPathForGlob=W;class U{constructor(e,t,i=!0){if(r.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),j().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:A.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,j().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,b.pairToObject)(this.reason,a(this,r,"m",s).bind(this)):{}}}r=new WeakSet,s=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return j().tap({msg:"apply()",level:i?k.LogLevels.debug:k.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class q{constructor(){n.set(this,[])}push(...e){for(const t of e){if(!t.valid){j().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,n,"f").find((e=>e.pattern===t.pattern));null==e?a(this,n,"f").push(t):j().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new U((0,R.native2posix)(e),t))}toA(){return a(this,n,"f")}}n=new WeakMap;const H=new U("**/.*","hidden file"),G=new U("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new q;e.push(G,H);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new U((D.isWin?"*":"")+"/"+t.s+"/",t.desc));if(D.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,E.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}D.isLinux&&e.push(new U(`${(0,_.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new U("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,h.blank)(t)){const s=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===s.length&&e.push(new U(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new U(`**/${t}/(${s.join("|")})/`,r))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new U("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new U("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Y=(0,u.lazy)((()=>{A.Settings.excludeGlobsOmitDefaults.watchLater(J),A.Settings.excludeGlobsAdd.watchLater(J),A.Settings.excludeGlobsOmit.watchLater(J),A.Settings.globsCaseInsensitive.watchLater(J),A.Settings.libraryDir.watchLater(K),A.Settings.originalsDir.watchLater(K),A.Settings.scanPaths.watchLater(K),A.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:re,notInHiddenPhotoStructureDir:ne,whyNoMedia:L.whyNoMedia,notHidden:se}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:ne}])),t.excludeGlobs=(0,u.lazy)((()=>{Y();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&j().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):j().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!A.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of A.Settings.excludeGlobsOmit.values)i(e);for(const e of A.Settings.excludeGlobsAdd.values)t(new U(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const r=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[s,n]=(0,g.partition)(r,(e=>e.pattern.endsWith("/")));return{dir:s,file:n}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const X=[{disableAllFilters:()=>!0}],Z=[{notBlank:()=>!1}];function Q(e){return A.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Z:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return A.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Z:(0,t.excludeBundles)().dir}async function ie(e){return A.Settings.disableAllFilters.valueOrDefault?void 0:x.Predicates.whyRejected(e,...te(e))}function re(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function se(e){return(0,S.thenNot)((0,O.isHidden)(e))}function ne(e){return!(0,T.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,M.libraryDirPosixFile)(),(0,M.libraryOriginalsDirPosixFile)(),...A.Settings.argvScanPaths.values,...A.Settings.scanPaths.values]));return j().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,F.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=ne},88561:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),r.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>n(this,r,"m",s).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,r=new WeakSet,s=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},79267:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const c=i(19851),d=i(40958),h=i(42659),f=i(31586),m=i(71371),p=i(50213),g=i(7282),y=i(409),v=i(78406),w=i(25764),b=i(99331),S=i(91655),P=i(34102),_=i(89968),T=i(85772);class M{static for(e){return new M(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained)}constructor(e,t,i,a,d=0){r.add(this),this.name=e,this.rootNativePath=t,this.staleMs=i,this.isPrunable=a,this.minRetained=d,s.set(this,void 0),this.intervalMs=(0,c.lazy)((()=>(0,f.clamp)((0,g.isTest)()?0:5*h.minuteMs,h.dayMs,this.staleMs/2))),n.set(this,void 0),this.cleanup=(0,y.rateLimited)({name:this.name,minCallDelayMs:this.intervalMs()/4,f:()=>u(this,r,"m",o).call(this)}),l(this,s,(0,p.mkLogger)("fs.FileCleanup("+e+")"),"f")}scheduleInterval(){return(null==u(this,n,"f")||u(this,n,"f").ended)&&l(this,n,new v.EndableInterval({name:this.name,callback:()=>this.cleanup(),intervalMs:this.intervalMs(),rank:w.EndableRanks.first}),"f"),u(this,n,"f")}cancelInterval(){u(this,n,"f")?.end(),l(this,n,void 0,"f")}}t.FileCleanup=M,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(e){if(!(0,f.gt0)(this.minRetained))return new Set;const t=new m.BoundedGreatestSet(this.minRetained??0,(e=>e.mtimeMs()));return await e.visitDescendants((e=>{e.isFile()&&t.add(e)})),new Set(t.vacuum().map((e=>e.nativePath)))},o=async function(){try{if((0,b.ending)())return;const e=await this.rootNativePath();if(null==e)return[];const t=await _.DirectoryEntry.for(e);if(null==t)return[];u(this,s,"f").info("cleanup(): starting",{root:t,staleMs:(0,S.fmtFullDuration)(this.staleMs," ")});const i=await u(this,r,"m",a).call(this,t),n=Date.now()-this.staleMs,o=new Set,l=[],c=[];await t.clear().visitDescendants((async e=>{if((e.dir!==t.nativePath||!(0,T.isNoMediaName)(e.base))&&!i.has(e.nativePath)&&(o.has(e.nativePath)||!(0,f.gte)(e.mtimeMs(),n)))if(e.isDirectory())try{await e.rmdir_(),c.push(e.nativePath),o.add(e.dir)}catch(t){"ENOENT"===t.code&&(u(this,s,"f").warn("cleanup(): ENOENT "+e,t),(0,P.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&u(this,s,"f").warn("cleanup(): failed to rmdir "+e,t)}else if(!1!==await(this.isPrunable?.(e)))try{await e.unlink_(),l.push(e.nativePath),o.add(e.dir)}catch(t){u(this,s,"f").warn("cleanup(): failed to clean up tmpfile "+e,t)}}));const h=[...l,...c];return(0,d.isNotEmpty)(h)&&t.clear(),u(this,s,"f").info("cleanup(): done",{root:t,pruned_file_count:l.length,pruned_dir_count:c.length}),h}catch(e){return void u(this,s,"f").error("cleanup() failed",{error:e})}}},32144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,n.defer)((()=>{const e={};for(const[t,...i]of d)for(const r of i)e[r]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof r.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const r=i(68708),s=i(17217),n=i(16287),a=i(68284);async function o(e){return(0,r.pick)(await(0,n.stat_)((0,s.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,s.toNativePath)(e)))?void 0:(0,r.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const r=i(68817),s=i(19851),n=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,s.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const s=(0,n.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(s);return(0,n.blank)(s)||(0,n.blank)(a)?void 0:{ext:a,mime:s}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),r.add(this),this.nativePath=e,s.set(this,[]),n.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,n,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,r,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,s,"f").push(e)}close(){u(this,n,"f").close()}}t.FileWatcher=m,s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,s,"f"))t(e,this.nativePath)}}},13829:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withFsAdvisoryLocks_=t.defaultFsAdvisoryLockDir=void 0;const r=i(55835),s=i(13538),n=i(81168),a=i(37628),o=i(46292),l=i(73209),u=i(95696);function c(){return(0,r.map)((0,o.configDir)(),(e=>u.PosixFile.for(e).join("advisory-locks")))}t.defaultFsAdvisoryLockDir=c,t.withFsAdvisoryLocks_=async function({name:e,lockNames:t,f:i,timeoutMs:r,lockDir:o=c()}){if(null==o)return i();await o.mkdirp_();const u=(0,n.sortIgnoreCase)(t).map((e=>l.FsLock.for({name:e,file:o.join((0,a.shortFsStringSha)(e)),timeoutMs:r})));try{for(const t of u)if(!0!==await(0,s.thenOrTimeout)(t.acquire_(),r))throw new Error("Failed to acquire lock for "+e+": "+t.opts.name+" was busy");return await i()}finally{for(const e of u)e.release()}}},73209:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},S=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const _=i(58587),T=P(i(44652)),M=i(87997),E=i(40958),k=i(17586),D=i(42659),x=i(50357),C=i(75240),A=i(55835),F=i(31586),I=i(30976),O=i(13538),L=i(54993),R=i(7282),N=i(68852),B=i(23560),j=i(25764),z=i(38836),V=i(99331),W=i(22781),U=i(38835),q=i(55222),H=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends z.EndableWrapper{static newUid(e=process.pid){return S(this,s,Math.max(Date.now(),b(this,s,"f",n)+1),"f",n),(0,E.compactBlanks)([q.TokenRadix.encode(b(this,s,"f",n)),B.serviceName.prior(),(0,L.toS)(e)]).join("-")}static pidFromLockfile(e){return s.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,F.toInt)(J.exec((0,L.toS)(e))?.groups?.pid)}static for(e){return b(this,s,"f",o).find((t=>t.opts.file===e.file))??new s(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>b(this,r,"m",w).call(this)),e.endableRank??j.EndableRanks.postdb,(0,H.commandTimeoutMs)()),r.add(this),this.opts=e,l.set(this,S(t=s,s,(i=b(t,s,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(b(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(s.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await b(this,r,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+b(this,l,"f")),this.staleMs=(0,F.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),b(s,s,"f",o).push(this)}get acquired(){return b(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await b(this,r,"m",f).call(this,e)??b(this,r,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,k.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,x.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==b(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:D.secondMs);S(this,c,setInterval((()=>b(this,r,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=b(this,c,"f")&&(clearInterval(b(this,c,"f")),S(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(b(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),S(this,u,!1,"f"),(0,A.map)(b(this,d,"f"),(e=>(0,M.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?b(this,r,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),S(this,d,setTimeout((()=>b(this,r,"m",v).call(this)),(0,F.toGt0)(this.staleMs)??D.secondMs),"f"),b(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(b(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,O.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,s=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,r=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,F.gt0)(this.staleMs)&&Date.now()>b(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await b(this,r,"m",m).call(this),meta:{why:t}})},m=async function(){S(this,h,Date.now(),"f");const e=[],t=await b(this,r,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,F.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;s.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+U.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const n=i[0]===this.lockfile.base;if(n)S(this,u,!0,"f");else if(!0!==t?.vacuum){const t=s.pidFromBasename(i[0]);if((0,F.gt0)(t)&&!(0,_.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),b(this,r,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:n,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await b(this,r,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await b(this,r,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,E.filterInPlace)(b(s,s,"f",o),(e=>b(e,l,"f")!==b(this,l,"f")))},n={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const r=i(22573),s=i(51926),n=i(54993),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,s.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,s.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,n.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?d:c){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:f(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,r.blank)(i))return e;const s=(0,u.parsePosixPath)(i),n=h(s,{aggressive:!1});return[...t,n+s.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,s.map)(m.exec(t),(e=>t=e[1].trim())),(0,s.map)(g.exec(t),(e=>t=e[1].trim())),t}},19254:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=t.GrepReader=void 0;const s=r(i(73024)),n=i(57075),a=i(46466),o=i(54993),l=i(33456),u=i(17217),c=i(58722);class d extends n.Transform{constructor(e,t="\n"){super({objectMode:!1,autoDestroy:!0}),this.pattern=e,this.sep=t}_transform(e,t,i){const r=(0,o.toS)(e).match(this.pattern);null!=r&&this.push(r[1]??r[0]+this.sep),i()}}t.GrepReader=d,t.fileGrep_=async function(e,t){const i=new c.WritableToBuffer;return await(0,a.pipeline)([s.default.createReadStream((0,u.toNativePath_)(e)),new l.LineReader,new d(t),i]),(await i.buffer).toString()}},14977:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const s=r(i(44652)),n=r(i(73024)),a=i(46466),o=r(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(n.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),n.default.createWriteStream(t,{autoClose:!0})),await s.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),b=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function S(e,{autoInvalidate:i=!0}={}){const r=(0,y.toNativePath_)(e);if(i){const t=b().get(r);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),b().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await _(n.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],i="sha512"){const r=s.default.createHash(i);return await(0,a.pipeline)([e,...t,r]),r.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:b,impl:P}),t.fileShaMeta_=S,t.fileSha_=async function(e){return(await S(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const r=i(19851),s=i(42659),n=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*s.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,r.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,n.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*s.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const r=i(22573),s=i(54993),n=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,n.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,n.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,n.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,n.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,s.toS)(e))}function m(e){return(0,r.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i,this.prior=(0,r.lazy)((()=>this.file.readJson("debug")))}async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),(e=>this.write_(e)))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},33456:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(51926),n=i(54993);class a extends r.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const r=(this._prior+(0,n.toS)(e)).split((0,s.newlineRe)()),a=r.pop();this._prior=a??"";let o=!1;for(const e of r)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const s=r(i(76760)),n=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},61704:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEql=t.nativePathsEqlSync=void 0;const r=i(21144),s=i(17217);t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}}},85772:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=n(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),b=i(88561),S=i(65238),P=i(16287),_=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),T="NoMedia",M=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+T+"$","im"),E=Object.freeze(["."+T,T]),k=Object.freeze((0,u.flatten)(E.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function D(e){return null!=M.exec(e)}t.isNoMediaName=D;const x=(0,o.lazy)((()=>new b.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=v.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return D(i.base)||await(0,w.isCachedirTagFile)(i)?x().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await x().getOrSetAsync(i.nativePath,(()=>A(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function A(e){if(D(e.base))return x().set(e.parent().nativePath,e.nativePath),_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,S.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,r=await Promise.race([F(e.nativePath,i),(0,S.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=r?r:await(0,w.isCachedirTagDirectory)(e)?_().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function F(e,t){for(const i of g.isCaseSensitiveFs?k:E){if(!0===t?.aborted)return null;const r=a.default.join(e,i);if(await(0,P.exists)(r,p.LogLevels.trace))return _().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(r)})}return null}async function I(e,t,i){for(const r of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(D(r.basename))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,r.basename))});if(r.basename===w.CACHEDIR_TAG){const t=(0,a.join)(e,r.basename);if(await(0,w.isCachedirTagFile)(t))return _().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=A,t._dirHasNoMediaChild=F},29882:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),b=i(17217),S=i(16287),P=i(66430),_=i(5545);function T(e){return((0,b.isSimpleFile)(e)?e.base:n.default.basename(n.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=T,t.containsHiddenPathname=function(e){return C(e).some(T)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!T(e)))},t.resolveSimpleFile=function(e){return(0,b.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return E((0,v.posix2native)(e))},t.extname=function(e){return E(e).ext},t.dirname=function(e){return n.default.dirname((0,b.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(n.default.parse(e).ext,n.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function E(e){const t=M.exec(e)?.groups,i=t?.ext2??"",r=n.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function k(e){const t=n.default.parse((0,b.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,n.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,b.toNativePath_)(e.ancestor),i=(0,b.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,p.ensureSuffix)(t,n.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function x(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(y.isLinux?r===s:(0,p.equalsIgnoreCase)(r,s))}function C(e){return(0,b.isSimpleFile)(e)?e.pathnames:e.split(n.default.sep).filter((e=>null!=e&&""!==e))}function A(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function F({p:e,maxLength:t}){const i=(0,b.toNativePath_)(e);if(i.length<=t)return i;const r=C(e),s=[],n=[r.pop()];for(;r.length>0;)if(s.length=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),O([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),O([...s,...n])}function I(e){return e.startsWith("\\\\")}function O(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(n.default.sep),y.isWin?"":n.default.sep)}t.parseNativePath=E,t.parentBasename=k,t.grandParentBasename=function(e){return k(n.default.parse((0,b.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return x(b.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return x(b.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return x(b.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=A,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,b.toNativePath_)(e),r=(0,b.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(r))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===r?"":(0,p.stripPrefix)((0,v.native2posix)(r).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=F,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(F({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=E(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,S.isReadableDirectory)(e))return;if(A(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await s.default.mkdirp(e)}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;s.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>s.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,b.toNativePath_)(e).split(n.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=O,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:O(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,b.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const s=r(i(76760)),n=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),b=i(16287),S=(0,n.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const i=await(0,b.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function T(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,s.default.join(e,"System32"),s.default.join(e,"System32","Wbem"),s.default.join(i,"chocolatey","bin"),s.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(s.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,...T()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const r=(0,a.uniq)((0,a.compactBlanks)([...M(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of r){const i=s.default.join(t,e);if(await _(i))return y.isLinux?i:(0,w.actualPath)(i)}}S().warn("Failed to find tool",{tool:e,dirs:r})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){"use strict";var r,s,n,a=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),b=i(22573),S=i(42659),P=i(26905),_=i(75240),T=i(55835),M=i(31586),E=i(68708),k=i(13538),D=i(89937),x=i(12168),C=i(54993),A=i(48884),F=i(50213),I=i(45255),O=i(81168),L=i(56519),R=i(56038),N=i(31562),B=i(84777),j=i(9595),z=i(38835),V=i(70025),W=i(57902),U=i(55222),q=i(43334),H=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Y=i(34238),X=i(87001),Z=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),re=i(32144),se=i(73209),ne=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,A.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),r.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,F.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Y.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,L.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>U.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,L.thenMapOr)((0,Z.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>q.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,b.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,b.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,O.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),r=new fe(i,t);return(0,O.isString)(e)&&he().set(e,r),he().set(i,r),r}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,L.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,j.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,j.originalsDir)(),descendant:this,acceptSelf:!0}))return q.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,T.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Z.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,T.map)((0,b.notBlankOr)(e,(()=>this.uri_())),Y.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,r=(0,O.countChars)(t.path,"/")-i;return this.isDeleted(r)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(q.isWin||q.isMac)return this.trap("hide",(async()=>(await(0,ne.hide_)(this),this)))}async hidden(){return(0,ne.isHidden)(this)}isSidecar(){return(0,re.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,re.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,O.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,re.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,A.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,T.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,E.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*s,retryDelay:3*S.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,M.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1}){return await this.parent().mkdirp_(),(0,se.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},(async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,k.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,N.untilTrue)((()=>r.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,_.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await r.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,r,"m",s).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,r,"m",n).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:S.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,M.clamp)(I.ShortCommandTimeoutMs,10*S.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,b.notBlank)(this.ext)&&(0,b.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,S.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,T.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,L.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,O.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,r=new WeakSet,s=async function(e){let t,i=e;const r=e.wip();try{const s=await this.stat_();if(null==s)return this.pflog().throw("Can't copy missing files"+z.NonRetriableErrorFlag);if(s.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+z.NonRetriableErrorFlag);if(null==await r.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,r.nativePath,h.default.constants.COPYFILE_FICLONE),s.size>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},s.size,(()=>r.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,M.approximates)(s.size,await r.size({refresh:!0}))),{intervalMs:S.secondMs,timeoutMs:S.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:s.size,actualSize:await r.size({refresh:!0})});await this.maybeVerifySameOrThrow_(r),i=e.eql(r)?e:await r.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,s.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${s.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${r?.nativePath}) failed: ${t}`),await r.unlink(),r.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,T.map)(t,(e=>e.end()))}},n=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const r=await this.stat_(),s=r?.size;return null==r||null==s?this.pflog().throw("Can't copy missing files"):(s>5*x.MiB&&(t=new H.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},s,(()=>e.clear().size()))),q.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):q.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+z.DoNotSendErrorFlag,{error:t})}finally{(0,T.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),v=i(83278),w=i(19748),b=i(92423),S=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function _(e){if(!(0,n.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,n.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,n.gte)(e.ImageWidth,i)&&(0,n.gte)(e.ImageHeight,i)),(()=>!1)):null}async function T(e){if(!(0,n.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function M(e){if(!(0,n.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,n.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,p.readMimeType)(e))}async function k(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function D(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function x(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function A(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function F(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function I(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,b.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:A,notFileTooBig:F}]}function O(e){return[...I(e),{notMissingMimeType:E},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:x},{notDimensionsTooSmall:_},{notVideoTooShort:T},{notVideoTooLong:M},{notRejectedRating:k},{notExcludedKeyword:D}]}async function L(e,t){return await u.Predicates.whyRejected(e,...t??O(e))??await(0,b.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=_,t.hasBrowserImgMimeType=P((e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=A,t.notFileTooBig=F,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,b.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=L,t.acceptFile=async function(e){return null==await L(e)}},78133:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const s=r(i(76760)),n=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)}},43899:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>s.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(s.default.join((0,p.execDir)(),"resources"),s.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),n.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const r=s.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(r,e))return r}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const r=i(44652),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const r=i(44652),s=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let n=-1;try{const s=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(s);return n=await(0,r.open)(e,"r"),await(0,r.read)(n,a,0,s,t)}finally{(0,s.mapGte0)(n,r.close)}}},69428:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=n(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const r=i(44652),s=i(84542);t.readLines_=async function(e){return(0,s.splitCompactLines)(await(0,r.readFile)(e))}},32323:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},65238:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const s=r(i(51455)),n=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),b=i(88561),S=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,n.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function _(){try{await s.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const T=(0,a.lazy)((()=>new b.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||T.prior()?.delete(e)}async function E(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await T().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,S.statTimeoutMs)(),r=k(e),s=await(0,h.thenOrTimeout)(r,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,S.statTimeoutMs)());if(s===f.Timeout&&(0,g.onTimeout)({soft:!1}),s!==f.Timeout&&s.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),T.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!T().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=T().get(e)},t.childDirectories_=async function(e){return(await E(e)).filter((e=>e.isDirectory)).map((t=>(0,n.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?E(e):k(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=E,t.readdirCached=function(e){return T().get(e)},t.readdirUncached_=k},53265:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const s=i(73024),n=r(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=n.default.resolve(t,...e);if((0,s.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??n.default.resolve(...e))},t.execDir=(0,l.defer)((()=>n.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const r=i(22454),s=i(28874),n=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault}},8797:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.showFileInFolder=void 0;const r=i(58587),s=i(31421),n=i(19851),a=i(40958),o=i(50213),l=i(43334),u=i(24399),c=i(28874),d=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ShowFileInFolder")));async function h(e,t){try{(0,s.spawn)(e,t,{detached:!0,stdio:"ignore"}).unref()}catch(i){d().warn("spawn() failed",{err:i,cmd:e,args:t})}}t.showFileInFolder=async function(e){if(await e.isEmpty())return!1;if(c.Settings.showFileInFolderUsesThunar.valueOrDefault&&l.isLinux)return async function(e){return h("dbus-send",["--type=method_call","--dest=org.xfce.Thunar","/org/xfce/FileManager org.xfce.FileManager.DisplayFolderAndSelect",`string:"${e.dir}"`,`string:"${e.base}"`,'string:""','string:""'])}(e);if((0,a.isNotEmpty)(c.Settings.showFileInFolderCommand.values)){const t=c.Settings.showFileInFolderUsesFileUri.valueOrDefault?e.fileuri():e.nativePath,i=[...c.Settings.showFileInFolderCommand.values,t],r=i.shift();return d().info("custom showFileInFolderCommand: running",{cmd:r,args:i}),h(r,i)}return l.isLinux?async function(e){return h("nautilus",["-s",e.fileuri()])}(e):l.isWin?async function(e){const t=e.nativePath.replace(/"/g,"").replace(/'/g,"''");try{return await u.PowerShell.instance().execute(`start explorer.exe -ArgumentList '/select,"${t}"'`,r.SimpleParser),!0}catch(t){return d().warn("explorerSelect("+e+") failed",t),!1}}(e):!!l.isMac&&async function(e){return h("open",["-R",e.nativePath])}(e)}},50274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const r=i(22573),s=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)}},17217:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const s=r(i(73024)),n=r(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof s.default.Dirent?e.name:f(e)?e.base:n.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:n.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(n.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(s.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function b(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function S(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=b(e),r=b(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,u.diff)(S(r),S(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}t.stat_=v,t.statMaybe=w,t.statToType=b,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const r=i(28874);t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const r=i(22573),s=i(56409);t.onDataChunked=function(e,t,i){const r=new n(t,i,!0);return r.read(e),r.done};class n{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new s.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,r.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,r.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=n},95705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const s=r(i(57075)),n=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends s.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,r)=>{!1===e.write(t,(e=>{e&&r(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,n.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(r,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends s.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),v=i(19851),w=i(40958),b=i(22573),S=i(42659),P=i(98553),_=i(31586),T=i(68708),M=i(50989),E=i(51926),k=i(85556),D=i(54993),x=i(89788),C=i(23467),A=i(7282),F=i(23560),I=i(77377),O=i(71567),L=i(73568),R=i(25764),N=i(38836),B=i(99331),j=i(12959),z=i(87290),V=i(46296),W=i(98314),U=i(38835),q=i(5012),H=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Y=i(84542),X=i(73428);t.AssetFileSyncStates=(0,M.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,M.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,M.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,M.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const Z={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,T.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,z.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function re(){return ie().join("README.txt")}t.SyncReportHeaders=(0,M.strEnum)(...(0,T.keys)(new class{constructor(e,t,i,r,s,n,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=r,this.from=s,this.elapsedMs=n,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=re,t.ensureSyncReportReadme=(0,v.lazy)((()=>(0,X.writeTextfile_)(re().nativePath,(0,E.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(Z)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=S.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,H.isCsvExt)(e)&&(0,_.gte)(e.mtimeMs(),t)))},t.syncReport=(0,v.lazy)((()=>new se));class se extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,r,"m",d).call(this)),R.EndableRanks.predb),r.add(this),s.set(this,void 0),n.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new x.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,s,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,b.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,q.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,D.toS)(e.path),state:e.state,details:(0,D.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:t,at:new Date(t).toISOString(),...i,...(0,T.pick)(e,"from","elapsedMs","url")};(0,T.isEmptyObj)(e.meta)||(s.meta=(0,P.stringify)(e.meta)),(0,A.isTest)()&&process.stdout.write((0,P.stringify)(e)+Y.Newline),f(this,r,"m",u).call(this,s)}}maybeSystemData(e){(0,F.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:r}){const s=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const n=await r(),a=n.state??(null!=n.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+U.InternalErrorFlag,{path:e,result:n}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-s,...n,state:a}),n}catch(r){throw this.logger.warn("wrap_() caught error",{error:r}),this.onProgress({path:e,from:i,state:(0,B.ending)()||r instanceof L.AbortError?t.SyncFileStates.canceled:r instanceof k.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(r),elapsedMs:Date.now()-s}),r}}get output(){return f(this,n,"f")??f(this,r,"m",h).call(this)}async flushClose(){return f(this,r,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,n,"f");return m(this,n,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,s,"f")}}t.SyncReport=se,s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,r=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,r,"m",c).call(this,i):(f(this,r,"m",c).call(this,{...i,details:(0,w.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const r=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(r+Y.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,s,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,j.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,s,"f").nativePath),this.logger.info("Opening new report: "+f(this,s,"f")),(0,A.isTest)()&&(0,O.stdoutWrite)({syncReport:f(this,s,"f").nativePath},!1),m(this,n,(0,g.createWriteStream)(f(this,s,"f").nativePath),"f"),f(this,n,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Y.Newline),f(this,n,"f")}},89966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const s=r(i(48161)),n=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+s.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,n.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,n.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,n.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,n.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const s=r(i(44652)),n=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const r=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,n.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(s.default.utimes(r,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(n){if(!i||"ENOENT"!==n.code)throw n;await(0,c.thenOrTimeoutError)(s.default.ensureFile(r),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},79847:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrUnlinkFileUri=t.trashOrUnlinkFileUris_=void 0;const o=n(i(51455)),l=a(i(49378)),u=i(40958),c=i(22573),d=i(13538),h=i(83104),f=i(45255),m=i(31562),p=i(98314),g=i(34102),y=i(28874),v=i(45200),w=i(63870),b=i(16287),S=i(74128),P=i(84258),_="fs.Trash";async function T(e){const t=Date.now(),i=(0,w.commandTimeoutMs)(),r=(0,c.toNotBlank)(e.nativePath)??await(0,d.thenOrTimeout)((0,v.uri2nativePath)(e.uri,e.mountpoint),i);if((0,c.blank)(r)||r===h.Timeout)return(0,S.syncReport)().onProgress({from:_,state:"failed",details:"Could not convert URI to native path",path:e.uri,elapsedMs:Date.now()-t}),{uri:e.uri,unlinked:!1};const s=await(0,b.statMaybe)(r);if(null==s)return(0,S.syncReport)().onProgress({from:_,state:"noop",details:"Failed to delete: no such file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(!s.isFile())return(0,S.syncReport)().onProgress({from:_,state:"noop",details:"Failed to delete: not a file",path:r}),{uri:e.uri,nativePath:r,unlinked:!1};if(y.Settings.trySoftDeletes.valueOrDefault)try{if(await(0,d.thenOrTimeoutError)((0,l.default)(r,{glob:!1}),i),await function(e){return(0,m.untilTrue)((async()=>null==await(0,b.statMaybe)(e)),{timeoutMs:f.ShortCommandTimeoutMs})}(r))return(0,S.syncReport)().onProgress({from:_,state:"deleted",details:"Moved file to trash",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0};(0,P.logger)().warn("soft-delete("+r+") didn't seem to work: the file is still there?")}catch(e){(0,S.syncReport)().onProgress({from:_,state:"note",details:"Failed to soft-delete file to trash: "+(0,p.errorToS)(e),path:r,elapsedMs:Date.now()-t}),(0,P.logger)().warn("Tried to soft-delete, but that failed. We'll try to hard-delete.",{error:e})}try{return await(0,d.thenOrTimeoutError)(o.unlink(r),i),(0,g.ee)().emit("fileChanged",r),(0,P.logger)().info("unlink("+r+") successful"),(0,S.syncReport)().onProgress({from:_,state:"deleted",details:"Permanently deleted file",path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!0}}catch(i){return(0,S.syncReport)().onProgress({from:_,state:"failed",details:"Could not move file to trash or delete: "+(0,p.errorToS)(i),path:r,elapsedMs:Date.now()-t}),{uri:e.uri,nativePath:r,unlinked:!1}}}t.trashOrUnlinkFileUris_=async function(e){const t=[];for(const{uri:i,mountpoint:r}of(0,u.uniqBy)(e,(e=>e.uri)))try{t.push(await T({uri:i,mountpoint:r}))}catch(e){t.push({uri:i,unlinked:!1,error:e})}return t},t.trashOrUnlinkFileUri=T},70854:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryUidStore=t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=t.mkuid=void 0;const r=i(19851),s=i(41400),n=i(55835),a=i(92782),o=i(37805),l=i(46292),u=i(34102),c=i(55222),d=i(28874),h=i(87128),f=i(95696);function m(){return(0,a.safeRandomUid)({radix:c.TokenRadix,chars:24,splitEveryN:4})}t.mkuid=m;class p extends h.JsonFileStore{constructor(e,t){super(e.join("."+t+"-uid.json"),(()=>({uid:m(),version:o.version,type:this.type,createdAt:Date.now()})),(e=>e.hide())),this.rootDir=e,this.type=t,this.readUid_=(0,r.lazy)((async()=>(await this.read_())?.uid))}}function g(e=d.Settings.libraryDir.valueOrDefault){return(0,n.map)(f.PosixFile.forMaybe(e),(e=>new p(e,"library")))}t.UIDStore=p,t.SystemUIDStore=(0,r.lazy)((()=>(0,n.map)((0,l.configDir)(),(e=>new p(f.PosixFile.for(e),"system"))))),t.LibraryUIDStore=(0,r.lazy)(g),t.libraryUidStore=g,(0,s.later)((()=>{(0,u.ee)().on("clearCache",(()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()})),d.Settings.libraryDir.watchLater((()=>t.LibraryUIDStore.unset()))}))},84258:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=n(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const r of(0,l.toA)(e))try{null!=r&&await a.unlink((0,c.toNativePath_)(r))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+r,{error:e})}}},5545:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const s=r(i(76760)),n=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,n.toS)(i.path??s.default.sep)}},70257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")}},58722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{constructor(e){super(e),this.deferred=new s.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},73428:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const s=r(i(44652)),n=r(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=n.default.dirname(e);await(0,c.mkdirp_)(i),await s.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=n.default.dirname(e);(0,c.mkdirpSync_)(i),s.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await S(e,t)).toString()}async function b(e,t,i){const r=[],n=[s.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>r.push(e)))];if(e.toLowerCase().endsWith(".gz")?n.push((0,o.createGunzip)().on("error",(e=>r.push(e)))):e.toLowerCase().endsWith(".br")&&n.push((0,o.createBrotliDecompress)().on("error",(e=>r.push(e)))),n.push(t),await(0,a.pipeline)(n),(0,u.isNotEmpty)(r))throw new f.WrappedError("zPipe("+e+") failed",{causes:r,path:e})}async function S(e,t){const i=new y.WritableToBuffer;return await b(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await S(e))}async function _(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=b,t.zCopyToBuffer_=S,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await _(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},60526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(47783),a=i(63335),o=i(18454);t.exiftoolHealthCheck=(0,s.defer)((()=>o.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifTool…",settings:[],later:async()=>{const e=await(0,n.exiftoolVersion_)();return{level:"ok",msg:["ExifTool is OK","ExifTool "+(0,a.ver)(e),(0,r.tt)((0,n.exiftool)().options.exiftoolPath)],meta:{exiftoolVersion:e}}}})))},19652:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=void 0;const a=i(51455),o=n(i(22915)),l=i(40958),u=i(82950),c=i(22573),d=i(45599),h=i(12168),f=i(50213),m=i(79960),p=i(32551),g=i(98314),y=(0,d.defer)((()=>(0,f.mkLogger)("health.externalDirectoryCheck")));t.externalDirectoryCheck=async function(){const e=(0,l.uniq)([(0,p.homeDir)(),o.getHomeFolder(),o.getPicturesFolder(),o.getVideosFolder(),o.getDesktopFolder(),await(0,m.defaultApplePhotosLibrary)()]).sort(),t=new Map,i=(0,l.uniq)(e.filter(c.notBlank)).sort();for(const e of i)try{await(0,a.readdir)(e,{withFileTypes:!0})}catch(i){if(["ENOTDIR","ENOENT"].includes(i?.code))continue;t.set(e,i)}const r=0===t.size?{level:"ok",msg:["Default media directories are OK","The following directories are readable:",(0,u.li)(i.map(u.tt))]}:{level:"warn",msg:["Error reading "+(0,h.plur)(t.size,"media directory")+":",(0,u.li)([...t.entries()].map((([e,t])=>(0,u.tt)(e)+":"+(0,g.errorToS)(t,{maxLen:80}))))]};return y().tap({msg:"externalDirectoryCheck",result:r})}},79483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(45599),s=i(45969),n=i(19652),a=i(18454);t.externalDirsHealthCheck=(0,r.defer)((()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",pendingMsg:"Checking default photo directories…",settings:[],later:n.externalDirectoryCheck})))},63664:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRemoteOrLocalHealthSummarySync=t.getRemoteOrLocalHealthSummary=t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0;const r=i(22573),s=i(45599),n=i(41400),a=i(50268),o=i(98553),l=i(50213),u=i(23560),c=i(45255),d=i(5916),h=i(28874),f=i(34238),m=i(51140),p=i(4988),g=i(18454),y=(0,s.defer)((()=>(0,l.mkLogger)("health.GetHealthSummary")));t.getRemoteHealthSummary=(0,d.lazyAsync)({desc:"health.getRemoteHealthSummary",later:async()=>{try{if((0,u.isWebService)())return;const e=await(0,p.get_)(f.URI.from({scheme:"http",authority:"127.0.0.1:"+h.Settings.httpPort.valueOrDefault,path:"/api/health"}),{timeoutMs:c.ShortCommandTimeoutMs}),t=(0,o.parseJSON_)(e.data);if(m.HttpStatusIs.ok(e.statusCode)&&(0,a.isHealthCheckSummary)(t))return"ready"===t.state&&(0,r.toNotBlank)(t.libraryDir)!==(0,r.toNotBlank)(h.Settings.libraryDir.valueOrDefault)&&(y().error("getHealthSummary(): libraryDir mismatch! Switching to that library directory...",{local:h.Settings.libraryDir.valueOrDefault,remote:t.libraryDir}),h.Settings.libraryDir.value=t.libraryDir),y().debug("getHealthSummary()",{response:e}),t;y().warn("getHealthSummary(): invalid response",{response:e})}catch(e){y().warn("Failed to get health check summary from web service",{error:e})}}}),t.getLocalHealthSummary=(0,d.lazyAsync)({desc:"health.getLocalHealthSummary",later:()=>g.HealthCheck.awaitSettled()}),(0,n.later)((()=>{h.Settings.healthCheckIntervalMs.watch((e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)}))})),t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()}},87408:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStatusSummary=void 0;const r=i(63870),s=i(18454),n=i(89035),a=i(82638);t.getStatusSummary=async function(e={}){return(0,a.summarizeHealthChecks)({healthChecks:[...s.HealthCheck.allCritical(),(0,n.memoryHealthCheck)()],errors:s.HealthCheck.lastErrors(),timeoutMs:(0,r.commandTimeoutMs)(),skipPending:!0,...e})}},18454:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v,w,b,S,P,_=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},T=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const M=i(19851),E=i(40958),k=i(76790),D=i(22573),x=i(41400),C=i(50357),A=i(26905),F=i(50268),I=i(55835),O=i(68708),L=i(30976),R=i(51926),N=i(13538),B=i(42279),j=i(59455),z=i(54993),V=i(48884),W=i(89788),U=i(22454),q=i(50213),H=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Y=i(77740),X=i(98314),Z=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),re=i(33866),se=i(21525),ne=i(82638),ae=(0,M.lazy)((()=>(0,q.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{_(this,s,"f",l).push(e+": failed: "+(0,X.errorToS)(t)),this.onResultChange()})),_(this,s,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return _(this,s,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){_(this,s,"f",l).push((0,R.isString)(e)?e:(0,X.errorToS)(e)),this.onResultChange()}static lastErrors(){return _(this,s,"f",l).toA()}static addLoadingMsg(e){_(this,s,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,E.compact)((0,j.toA)(e)).map(z.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:_(this,s,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[_(this,s,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=_(this,s,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>_(this,s,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?re.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,s.reset()}static findById(e){return _(this,s,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,F.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=_(this,s,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=s.summary();if(e.pendingCount>0){const t=await Promise.all(s.testResultsCritical());e=s.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){s.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,A.shortStack)());else{this.onResultChange(),_(this,s,"f",l).clear(),_(this,s,"f",d).clear(),_(this,s,"f",h).clear(),_(this,s,"f",c).clear(),this.summary.clear(),T(this,s,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new s(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return _(this,s,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,n,o,l,u,c,d,h,f,m,S,P=ee.commandTimeoutMs){r.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=n,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=S,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),w.set(this,(0,M.lazy)((async()=>{await _(this,p,"f").prior(),(0,C.eql)(_(this,g,"f"),_(this,r,"m",v).call(this))||(this.onReset?.(),await this.refresh(),_(this,w,"f").unset())}))),this.refresh=(0,M.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await _(this,p,"f").prior();const e=_(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,q.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[F.HealthCheckSections.ordinal(this.section),l??999,this.id],T(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>_(s,s,"f",a).enqueue({name:this.id,l:()=>_(this,r,"m",b).call(this,o)}),ttlMs:S}),"f"),this.isCritical&&_(this,p,"f").watchLater({onChange:s.onCriticalResult,onError:s.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>_(this,w,"f").call(this)))}isStale(){return _(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return _(this,p,"f").settledCount()}reset(){return _(this,p,"f").unset(),this.onReset?.(),T(this,g,{starting:!0},"f"),this}setTTL(e){_(this,p,"f").setTTL(e)}result(){return _(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return _(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return _(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??_(this,r,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,E.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),r={};return(0,E.isNotEmpty)(i)&&(r.links=(0,E.uniqBy)(i)),(0,E.isNotEmpty)(t)&&(r.buttons=(0,E.uniqBy)(t)),r}t.HealthCheck=oe,s=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,w=new WeakMap,r=new WeakSet,o=function(){return(0,E.filterInPlace)(_(this,s,"f",n),(e=>!e.isPending)),_(this,s,"f",n)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,ne.summarizeHealthChecksSync)({errors:_(this,s,"f",l),skipPending:_(this,s,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&T(this,s,!0,"f",u),i.state!==_(this,s,"f",c).last?.state&&_(this,s,"f",c).push({state:i.state,ts:Date.now()}),i},v=function(){return(0,O.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},b=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,A.shortStack)()}),T(this,g,_(this,r,"m",v).call(this),"f");try{if((0,Y.getDevEnvFlag)("PS_SLOMO")&&await(0,x.delay)((0,L.randomInt)(.3*i,.7*i)),this.isSkipped())return _(this,r,"m",S).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const s=await(0,N.thenOrTimeoutError)(e(),i);return _(this,r,"m",S).call(this,{test:s,elapsedMs:Date.now()-t})}catch(e){return _(this,r,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},S=function({test:e,src:t="#toResult",elapsedMs:i}){var r,n;const a=s.normalizeMsg(e.msg),o=e.level??((0,z.toS)(a).toLowerCase().includes("error")?"error":(0,z.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,E.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(T(this,y,(n=_(this,y,"f"),r=n++,n),"f"),r),(0,$.ending)()?u:this.logger.tap({level:se.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const s=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,D.toNotBlank)((0,X.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,Z.isFatalError)(e)&&s.toLowerCase().includes("warn")?"warn":"error"),_(this,r,"m",S).call(this,{test:{msg:s,level:t},src:"#toErrorResult",elapsedMs:i})},n={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new U.CountingSet},f={value:[]},oe.all=(0,M.lazy)((()=>Object.freeze((0,k.sortBy)(_(s,s,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,H.debounce)((()=>{ae().info("onCriticalResult()",s.summary.refresh())}),250),oe.summary=(0,M.lazy)((()=>_(s,s,"m",m).call(s))),oe.resetDebounced=(0,H.debounce)((()=>s.reset()),50)},85021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckCommand=void 0,t.HealthCheckCommand="--health"},33866:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}}},88625:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=t.testHealthCheck=void 0;const r=i(19851),s=i(82950),n=i(45599),a=i(50268),o=i(50213),l=i(7282),u=i(44198),c=i(34102),d=i(2858),h=i(60526),f=i(79483),m=i(18454),p=i(39214),g=i(86403),y=i(42482),v=i(35675),w=i(89035),b=i(31974),S=i(20752),P=i(85200),_=i(37301),T=i(65756),M=i(15024),E=i(3956),k=i(29332),D=i(61274),x=i(38372),C=i(49913),A=i(84728),F=i(7245),I=i(16264),O=(0,n.defer)((()=>(0,o.mkLogger)("health.HealthCheckSetup")));t.testHealthCheck=(0,n.defer)((()=>m.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,settings:[],pendingMsg:"Test check…",later:async()=>{const e=a.HealthCheckLevels.validOrElse((0,u.env)().PS_TEST_HEALTH_CHECK_LEVEL,a.HealthCheckLevels.ok);return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,s.b)("details")}:`,(0,s.li)("alpha",(0,s.tt)("bravo"),"charlie")]}}}))),t.healthCheckSetup=(0,r.lazy)((()=>{(0,h.exiftoolHealthCheck)(),(0,p.heifHealthCheck)(),(0,y.libraryDirectoriesCheck)(),(0,v.libraryFreeSpaceCheck)(),(0,E.settingsEnvHealthCheck)(),(0,D.settingsSystemHealthCheck)(),(0,k.settingsLibraryHealthCheck)(),(0,f.externalDirsHealthCheck)(),(0,w.memoryHealthCheck)(),(0,b.nodejsHealthCheck)(),(0,S.notInDMGHealthCheck)(),(0,P.osHealthCheck)(),(0,_.powershellHealthCheck)(),(0,x.sharpHealthCheck)(),(0,g.jpegtranHealthCheck)(),(0,M.securityHealthCheck)(),(0,T.sqliteHealthCheck)(),(0,C.systemLoadHealthCheck)(),(0,F.videoHealthCheck)(),(0,I.volumeHealthCheck)(),(0,A.versionHealthCheck)(),(0,l.isProd)()||(0,t.testHealthCheck)();let e=(0,d.libraryHasSettings)();d.libraryHasSettings.watchLater((t=>{null!=t&&e!==t&&(O().info("libraryHasSettings changed. Resetting health checks.",{newValue:t}),e=t,m.HealthCheck.resetDebounced())}));for(const e of["volumesChanged","mountpointsChanged","error"])(0,c.ee)().on(e,(()=>{O().debug("Clearing health check cache",{event:e}),m.HealthCheck.resetDebounced()}));(0,c.ee)().on("fatal",(e=>m.HealthCheck.addError(e)))}))},39214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(41400),a=i(55835),o=i(34102),l=i(277),u=i(45969),c=i(63335),d=i(18454);t.heifHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-heif",pendingMsg:"Checking HEIF/HEIC tooling…",settings:["heifConvertPath"],links:[{text:"Read how to set up HEIF support with PhotoStructure",url:"https://photostructure.com/getting-started/heif-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getHeifSupportDetails)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["HEIF images will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.heifHealthCheck.prior()?.reset()))}))},86403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testJpegtran_=t.jpegtranHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(55835),a=i(98314),o=i(89966),l=i(51210),u=i(76280),c=i(63335),d=i(18454);async function h(){const e=await(0,o.jpegtranNativePath_)(),t=await(0,l.jpegtranVersion_)();return{nativePath:e,version:t,satisfies:(0,u.semverSatisfies)(t,">=1.5")}}t.jpegtranHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,pendingMsg:"Checking "+(0,r.tt)("jpegtran")+"…",settings:[],later:async()=>{try{const e=await h();return{level:"ok",msg:["jpegtran is OK",(0,n.map)(e.version,c.ver),(0,n.map)(e.nativePath,r.tt)]}}catch(e){return{level:"error",msg:["Something's amiss with jpegtran",(0,a.errorToS)(e)]}}}}))),t.testJpegtran_=h},42495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},42482:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(98553),o=i(31586),l=i(94174),u=i(87290),c=i(98314),d=i(29882),h=i(45969),f=i(43334),m=i(28874),p=i(2858),g=i(59107),y=i(18454),v=i(42495);async function w(){const e=await(0,u.setupLibraryDirs_)();return(0,p.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,r.li)(...e.map((e=>(0,r.tt)(e))))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}t.libraryDirectoriesCheck=(0,n.defer)((()=>y.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directories…",settings:["libraryDir","originalsDir","previewsDir","cacheDir"],ttlMs:s.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,h.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],okLinks:[{type:"button",text:"Run library maintenance jobs",url:"/admin/run-maintenance",method:"POST",icon:"handyman"}],later:async()=>(await(0,p.readSettings)(),(0,h.isDocker)()?async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,r.tt)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,r.tt)(m.Settings.libraryDir.toEnvLine(m.Settings.libraryDir.defaultValue))}`]};const t=await(0,g.mountpoints_)(),i=(0,d.bestMountpointForDir)(e,t);if(null==i||"/"===i)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,r.tt)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[v.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,r.tt)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`];return null!=t&&(0,o.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,r.tt)(t.uid)+", groupid "+(0,r.tt)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[v.DockerVolumeLink]}}return await w()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,l.userDesc)()}.`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[v.DockerVolumeLink]}}}():async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"no-library",msg:["No PhotoStructure library is open",(0,a.stringify)(m.Settings.libraryDir.getState())]};if(!(0,p.libraryHasSettings)())return{level:"no-library",msg:["No PhotoStructure library is open",m.Settings.libraryDir.hasValue()?(0,r.tt)(m.Settings.libraryDir.toEnvLine()):void 0]};try{return await e.isReadWriteExecutable_()?await w():{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(t){return{level:"no-library",msg:[`Your library directory, ${(0,r.tt)(e)}, can't be set up for ${await(0,l.userDesc)()}`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}())})))},35675:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(31586),l=i(68708),u=i(12168),c=i(87290),d=i(77740),h=i(28874),f=i(7014),m=i(18454);t.libraryFreeSpaceCheck=(0,a.defer)((()=>(0,l.tap)(m.HealthCheck.for({section:"Library",id:"library-free-space",settings:["libraryDir","minDiskFreeGb","originalsDir","previewsDir","cacheDir"],pendingMsg:"Checking free space on library volume(s)…",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,c.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.tt)(e)} is not a directory`};const t=[];for(const e of await(0,c.setupLibraryDirs_)()){const i=await(0,f.bestVolumeForPath)(e);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.tt)(e)}`};let r=t.find((e=>e.vol.mountpoint===i.mountpoint));null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*u.GB,n=[];for(const{vol:e,paths:a}of t){const t=(0,s.b)(`Volume ${(0,s.tt)(e.mountpoint)} has ${(0,u.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.li)((0,r.uniq)(a).sort().map(s.tt))}`;if(e.available{for(const t of["minDiskFreeGb","libraryDir","originalsDir","configDir"])h.Settings[t].watchLater((()=>e.reset()))}))))},89035:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){return s.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,n.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},31974:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(1708)),n=i(82950),a=i(45599),o=i(26033),l=i(63335),u=i(18454);t.nodejsHealthCheck=(0,a.defer)((()=>u.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.js…",settings:[],links:[{text:"Read about PhotoStructure NodeJS support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e="You're running Node.js "+(0,l.ver)(s.default.versions.node)+".\nPhotoStructure requires "+(0,n.tt)(o.RequiredNodeRange)+".";return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",e]}:{level:"warn",msg:["Node.js is not a supported version",e]}}})))},20752:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(45599),s=i(43899),n=i(43334),a=i(18454);t.notInDMGHealthCheck=(0,r.defer)((()=>n.isMac&&n.isElectron?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure installation directory…",settings:[],later:async()=>s.ProjectPath.isInDMG()?{level:"error",msg:"PhotoStructure cannot run directly from a DMG disk image. Please drag and drop the PhotoStructure icon onto your Applications folder to install.",checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure isn't running directly from a DMG disk image"}}):void 0))},85200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const r=i(45599),s=i(96175),n=i(18454);t.osHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating system…",settings:[],links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,s.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,s.osFullName)()]}:{level:"warn",msg:["Operating system is not supported",(0,s.osFullName)()+" was detected, but only "+e+"."]}}})))},37301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(98314),a=i(43334),o=i(24399),l=i(63335),u=i(18454);t.powershellHealthCheck=(0,s.defer)((()=>a.isWin?u.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShell…",settings:["powerShellArgs"],ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,o.checkPowerShell_)();return{level:"ok",msg:["PowerShell is OK",(0,l.ver)(e)],meta:{version:e}}}catch(e){return{level:"error",msg:"PowerShell failed: "+(0,n.errorToS)(e)}}}}):void 0))},65756:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(27180),a=i(98314),o=i(63335),l=i(18454);t.sqliteHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLite…",settings:[],links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await n.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,r.li)(["embedded: "+(0,o.ver)(e.libraryVersion),(0,r.tt)(e.sqliteNativePath)+": "+(0,o.ver)(e.toolVersion)])]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,a.errorToS)(e)}}}})))},15024:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(31586),o=i(94174),l=i(77740),u=i(44198),c=i(59958),d=i(43334),h=i(18454);t.securityHealthCheck=(0,n.defer)((()=>{const e=d.isWin?"an administrator":"root";return h.HealthCheck.for({section:"System",id:"proc-not-superuser",pendingMsg:"Checking user permission level…",settings:[],later:async()=>{if("0"===(0,u.env)().PUID)return{level:"disabled",msg:`Admin health check is disabled (${(0,s.tt)("PUID=0")}).`};const t=(0,r.compact)([(0,a.gte0)((0,o.userid)())?"Current user id: "+(0,s.b)((0,s.tt)((0,o.userid)())):void 0,(0,a.gte0)((0,o.groupid)())?"Current group id: "+(0,s.b)((0,s.tt)((0,o.groupid)())):void 0,"Current user name: "+(0,s.b)((0,s.tt)(await(0,o.username)()??"(unknown)"))]);return!0===await(0,o.isRootUser)()||(0,l.getDevEnvFlag)(c.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK)?{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]}:{msg:["PhotoStructure is not running as "+e,...t],level:"ok"}}})}))},3956:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(12168),a=i(28874),o=i(63225),l=i(18454);t.settingsEnvHealthCheck=(0,s.defer)((()=>l.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settings…",settings:[],links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,a.allSettings)())if(t.hasValue()&&null!=t._envValue()){const i=!0===t.opts.sensitive?"********":t.toEnvValue(t._envValue());null!=i&&e.push((0,r.tt)(t.key+"="+i))}const t=[(0,n.plur)(e.length,"environment setting"),(0,r.li)(e)],i=(0,o.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,r.li)(i.map((e=>(0,r.tt)(e.envKey)+": "+e.msg))),"---",...t]}:{level:"ok",msg:t}}})))},29332:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(45599),s=i(2858),n=i(18454),a=i(61274);t.settingsLibraryHealthCheck=(0,r.defer)((()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settings…",settings:["libraryDir"],links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")})))},61274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=t.validateSettingsToml=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(12168),o=i(81168),l=i(98314),u=i(95696),c=i(2858),d=i(32707),h=i(18454);async function f(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.tt)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.tt)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,a.plur)(i.settings.length,t+" setting override"),(0,s.b)("Source:"),(0,s.tt)(e),(0,s.b)("Settings:"),(0,s.li)(i.settings.map((e=>(0,s.tt)(e.key+"="+e.toEnvValue(e.value)))))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,l.errorToS)(t)}}}t.validateSettingsToml=f,t.settingsSystemHealthCheck=(0,n.defer)((()=>h.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settings…",settings:[],links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>f(u.PosixFile.forMaybe((0,d.systemSettingsFile)()),"system")})))},38372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpHealthCheck=void 0;const r=i(45599),s=i(98314),n=i(21473),a=i(18454);t.sharpHealthCheck=(0,r.defer)((()=>a.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharp…",settings:[],later:async()=>{try{return await(0,n.testSharp_)(),{level:"ok",msg:["Sharp is OK","Image processing is working as expected."]}}catch(e){return{level:"error",msg:["Something's amiss with Sharp",(0,s.errorToS)(e)]}}}})))},82638:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,n.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:r}){const s=new Map;for(const e of t??[])s.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),r))s.set(t.id,t);return[...s.values()]}t.summarizeHealthChecks=async function(e){return b({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function b(e){const t=(0,r.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),n=i.length,a=i.map((e=>e.id)),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter((e=>e.level===i));if((0,r.isNotEmpty)(s)){const e=t.filter((e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+s.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map((e=>e.id)),ts:Date.now(),msg:(0,r.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...e].map((e=>e.msg[0])))])},meta:{checks:s.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=b},49913:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(31586),o=i(28874),l=i(14854),u=i(18454);t.systemLoadHealthCheck=(0,n.defer)((()=>u.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system load…",settings:["cpuBusyPercent"],ttlMs:s.minuteMs,later:async()=>{if(o.Settings.cpuBusyPercent.valueOrDefault<=0)return{level:"ok",msg:["CPU utilization is not monitored",(0,r.tt)(o.Settings.cpuBusyPercent.key)+" is set to <= 0"]};const e=l.CpuUsage.instance().busyPct(),i=(0,l.isTooBusy)();return(0,t.systemLoadHealthCheck)().setTTL((i?6:60)*s.secondMs),{level:i?"stop-sync":"ok",msg:"CPU utilization is "+(0,a.fmtPct)(e)+"\n"+(i?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause if CPU utilization exceeds")+" "+(0,r.tt)(o.Settings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(o.Settings.cpuBusyPercent.valueOrDefault)}}})))},84728:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(40044),a=i(18454);t.versionHealthCheck=(0,s.defer)((()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure version…",settings:["autoUpdateCheck","configDir","libraryDir","optOut"],ttlMs:r.hourMs,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:n.checkVersion_})))},7245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(41400),a=i(55835),o=i(34102),l=i(66106),u=i(45969),c=i(63335),d=i(18454);t.videoHealthCheck=(0,s.defer)((()=>d.HealthCheck.for({section:"Tools",id:"tools-video",pendingMsg:"Checking video tooling…",settings:["ffmpegPath"],links:[{text:"Read how to set up video support with PhotoStructure",url:"https://photostructure.com/getting-started/video-support/",icon:"docs"}],warnLinks:(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}],later:async()=>{const e=await(0,l.getVideoToolDetails_)();return null!=e&&!1!==e.isSupportedVersion?{level:"ok",msg:["Videos will be imported",(0,a.map)(e.version,c.ver),(0,a.map)(e.path,r.tt)]}:{level:"warn",msg:["Videos will not be imported","No video tooling was found."]}}}))),(0,n.later)((()=>{(0,o.ee)().on("clearToolCache",(()=>t.videoHealthCheck.prior()?.reset()))}))},16264:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(13538),l=i(83104),u=i(12168),c=i(48884),d=i(45255),h=i(43334),f=i(69108),m=i(48165),p=i(63870),g=i(7014),y=i(18454);t.volumeHealthCheck=(0,a.defer)((()=>y.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,pendingMsg:"Checking volumes…",settings:[],links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:h.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=Date.now(),i=await(0,o.thenOrTimeout)((0,g.volumes)(),(0,p.commandTimeoutMs)());if(i===l.Timeout){const i=await(0,o.thenOrTimeout)(h.isWin?(0,m.getLocalVolumesWin_)():(0,f.dfPosixRawLocal_)(),d.ShortCommandTimeoutMs);return(0,t.volumeHealthCheck)().logger.warn("volumes() timed out, retrying in 5m"),setTimeout((()=>(0,t.volumeHealthCheck)().refresh()),5*n.minuteMs),{level:"warn",msg:[i===l.Timeout?"Something seems wrong with your computer's volumes":"Something seems wrong with one or more remote filesystem mounts","Gathering volume metadata took longer than "+(0,n.fmtAgo)(e,"")+"."]}}const a=i.filter((e=>!1===e.ok));if((0,r.isNotEmpty)(a))return{level:"warn",msg:["One or more volumes are not healthy","Check the following:",(0,s.li)(a.map((e=>(0,s.tt)(e.mountpoint))))]};const[y,v]=(0,c.partition)(i,(e=>!0===e.remote)),w=["Storage volumes are OK"];return(0,r.isNotEmpty)(v)&&w.push((0,s.b)((0,u.plur)(v.length,"local volume")+":"),(0,s.li)(...v.map((e=>(0,s.tt)(e.mountpoint))))),(0,r.isNotEmpty)(y)&&w.push((0,s.b)((0,u.plur)(y.length,"remote volume")+":"),(0,s.li)(...y.map((e=>(0,s.tt)(e.mountpoint))))),{level:"ok",msg:w}}})))},95242:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),v=i(57159),w=i(83278),b=i(95696),S=i(62105),P=i(84258),_=i(38156),T=i(69589),M=i(28874),E=i(47783),k=i(29990),D=i(16047),x=i(42725),C=i(4192),A=i(32876),F=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,E.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class O{constructor(e,t,i){r.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,T.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(r=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=b.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,S.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await n(this,r,"m",s).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:s,width:n,height:a,sha:l,mimetype:u}=t;if(null==s||null==n||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,k.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:s,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:r,filesize:i,width:n,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(x.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),s=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,k.equivalentFitSizes)(r,s)){const n=(0,k.fitSizes)(e,e.mimetype),a=(0,o.diff)(r,s);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=n.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:n});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=O,s=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),r=await this.priorIfValid_(t,i);if(null!=r)return r;const s=new _.PushProgressObserver({path:e.nativePath,op:"Building previews"},x.ImageSize.sq().length+x.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),a=await(0,F.sharpReadable_)({src:e,minDim:x.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,F.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,D.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,k.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=x.ImageSize.largestSq(),b=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,S=(0,h.pick)(t,"width","height");{let e=o.clone(),t=S;for(const[i,r]of l){const n=Date.now(),a=t,o=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===b&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&r.reducer===A.Fit&&M.Settings.includePreviewTags.valueOrDefault&&m.push(o),await r.toJpeg({path:o.nativePath,sh:e,outputSize:i}),s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-n)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:S,bestFitNameForSq:b}),g=o,p=S):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:b});let e=!1;for(const t of x.ImageSize.sq()){const i=Date.now(),r=p,n=t.outputSize(p??S);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=M.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const a=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,g),p=n,await t.toJpeg({path:a.nativePath,sh:g,outputSize:n}),s.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(r)+" -> "+(0,u.fmtDim)(n)+" in "+(Date.now()-i)+" ms")}}try{await(0,C.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(n.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,r){return`Download ${t} ${e.ext} ${i} (${(0,s.fmtDim)(r)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,s.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),v=i(70417),w=i(35721);t.AssetPreviews=class{constructor(e,t){r.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),s=(0,p.splitEvery)(i,3);this.basename=s.pop()+"-",this.parent=e.join(...s)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:n(this,r,"m",s).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,o.isEmpty)(r))return r;const s=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=s,await this.writeInfo(t)),s}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},r=new WeakSet,s=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},33106:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const s=r(i(9288)),n=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(e);for(let i=0;is?1:0);return n}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:s.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,n.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)?(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,n.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter((e=>u(c(t,e),i)===r))}},89782:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const r=i(19851),s=i(31586),n=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,r.lazy)((()=>(0,n.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,s.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const r=i(40958),s=i(33374),n=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),r=[];let l=(0,n.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,s.dmegapixels)(a)-(0,s.dmegapixels)(l)>2.5)&&(l=a,r.push([a,n])))}return r},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(l),(0,r.compactBlanks)(t).map(l))}},277:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,n.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function b(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,r.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=b,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await b()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,s.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,r.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,s.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,r.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?n.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const r=i(22573),s=i(54993),n=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,r.blank)(e)&&n.test((0,s.toS)(e))}},13940:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const r=i(51455),s=i(19851),n=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),b=(0,s.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,s.lazy)((()=>(S(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const S=(0,s.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,r){const s=await(0,t.imageCacheDir_)();i??(i=e.name),r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r}){return(await P(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*n.minuteMs})},t.withImageCache_=async function(e,t,i,r){try{const s=await P(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const s=r(i(9288)),n=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),v=i(88561),w=i(95696),b=i(17217),S=i(50213),P=i(23624),_=i(28874),T=i(12089),M=i(16170),E=i(1078),k=i(33106),D=i(86580),x=i(78011),C=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const A=(0,n.lazy)((()=>(0,S.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,b.toNativePath_)(e))}catch(t){return void A().warn("imageHash() failed for "+e,t)}};const F=(0,n.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=w.PosixFile.for(e),i=await(0,E.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const r=(0,D.fitToResolution)(i.dimensions,Math.round(_.Settings.dominantColorPixels.valueOrDefault)),n=await(0,C.sharpReadable_)({src:t,minDim:r});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const r=(0,S.mkLogger)("ImageHash("+e+")");if(null==t)return r.throw("Cannot build readable stream");const n=(0,D.fitToResolution)(i.dimensions,_.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,M.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:s.default.fit.outside,...n,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,s.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,s.default)(o,{raw:{...l,channels:3}}),v=await(p?x.meanDiffHash:x.meanDiffHashCIELAB)(y()),w=await(p?k.dctHash:k.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,M.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:n,sizeInfo:i})))}function O(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,T.shim1)({name:"img.imageHash",cache:F,impl:I}),t._imageHash_=I,t.isImageHash=O,t.toImageHash=function(e){if(null!=e){if(O(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(O(t))return t}}},t.HashDim=8},80361:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageHashSimilarity=t.isVerySimilarComparison=t.isVerySimilarImageHash=t.isSimilarImageHash=t.isVerySimilarImage=t.compareImageHashes=t.isSimilarImage=t.hammRatio=t.meanHashVariants=t.isGreyscaleMeanHash=t.labsCorr2=t.isImageHashComparison=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(33374),l=i(57924),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(21605),m=i(48884),p=i(50213),g=i(97352),y=i(85810),v=i(3048),w=i(32848),b=i(82647),S=i(38812),P=i(70417),_=i(23624),T=i(28874),M=i(86580),E=i(48368),k=i(2090),D=(0,r.lazy)((()=>(0,p.mkLogger)("img.ImageHashComparison")));t.isImageHashComparison=function(e){return null!=e&&(0,E.isImageHash)(e.a)&&(0,E.isImageHash)(e.b)&&[e.imageCorr,e.colorCorr,e.aRotation].every(c.isNumber)},t.labsCorr2=function(e,t){const i=(0,s.sum)(e,(e=>(0,v.diffCIECorr)(e,(0,y.closestLab)(t,e))))+(0,s.sum)(t,(t=>(0,v.diffCIECorr)(t,(0,y.closestLab)(e,t)))),r=Math.max(e.length,t.length,i);return(r-i)/r};const x=/A{20}=?$/;function C(e){return null!=e&&((0,g.within)(7,12,e.length)||null!=e?.match(x))}function A(e,t,i=E.HashDim){const r=(0,_.b64decode)(e).toString(2).split("").map((e=>"1"===e?1:0)),s=i*i;for(;r.length%s!=0;)r.unshift(0);return r.length===s||t?r.slice(0,s):r.slice(0,s).map(((e,t)=>4*e+2*r[t+s]+r[t+2*s]))}function F({a:e,b:t,greyscale:i,dim:r=E.HashDim,rotationsToCheck:a}){if((0,n.blank)(e)||(0,n.blank)(t))return{hammRatio:0,bRotation:0};if(e===t)return{hammRatio:1,bRotation:0};const o=A(e,i,r),l=A(t,i,r);(0,s.isEmpty)(a)&&(a=[0]);const u=a.map((e=>({bRotation:e,hammRatio:(0,c.sigFigs)((0,g.hammRatioIntArrays)(o,(0,S.rotateSquareMatrix)(l,e),i?1:3),2)})));D().debug("hammRatio()",{results:u,rotationsToCheck:a});const d=(0,m.greatestBy)(u,(e=>[(0,c.sigFigs)(e.hammRatio,1),-f.Rotations.indexOf(e.bRotation)]));return{bRotation:d.bRotation,hammRatio:(0,c.sigFigs)(d.hammRatio,2)}}async function I(e,t,i="debug",r={}){return D().tap({msg:`isSimilarImage(${e},${t})`,level:i,result:L(await(0,E.imageHash)(e),await(0,E.imageHash)(t),r)})}function O(e,t,i={}){const r=(0,E.toImageHash)(e),s=(0,E.toImageHash)(t);if(null==r||null==s)return;const n=(0,a.isTrue)(i.capturedAtIsFuzzy),h=!(0,a.isTrue)(i.forceColor)&&((0,a.isTrue)(i.forceGreyscale)||(r.isGreyscale??C(r.meanHash))||(s.isGreyscale??C(s.meanHash))),f=F({a:r.meanHash,b:s.meanHash,greyscale:h,rotationsToCheck:i.rotationsToCheck??(0,M.validRotations)(r,s)}),m=F({a:r.diffHash,b:s.diffHash,greyscale:h,rotationsToCheck:[]}),p=F({a:r.dctHash,b:s.dctHash,greyscale:h,rotationsToCheck:[]}),g=(0,w.dominantColorCorrelation)(r.dominantColors,s.dominantColors);if(null==g)return void D().debug("imageHashCompare(): missing color correlation");const y=r.mimetype===s.mimetype,v=(0,M.aspectRatio)(r),S=(0,M.aspectRatio)((0,o.maybeDimSwap)(s,f.bRotation)),P=null!=v&&null!=S&&!(0,o.isCloseAspectRatio)(v,S);let _=0,x=0;n&&(x+=T.Settings.imageHashFuzzyDateDelta.valueOrDefault,_+=T.Settings.imageHashFuzzyDateDelta.valueOrDefault),y||(x+=T.Settings.imageHashDifferentMimetypesDelta.valueOrDefault,_+=T.Settings.imageHashDifferentMimetypesDelta.valueOrDefault),h&&(_+=T.Settings.imageHashGreyscaleDelta.valueOrDefault,x+=T.Settings.imageHashGreyscaleDelta.valueOrDefault);const A=R((_+(i.minImageCorr??T.Settings.minImageCoeffPct.valueOrDefault))/100),I=R((x+(i.minColorCorr??T.Settings.minColorCoeffPct.valueOrDefault))/100),O=[];P&&O.push(`aspect ratio mismatch (${(0,k.fmtAspectRatio)(v)} vs ${(0,k.fmtAspectRatio)(S)})`);const L=[],N=new b.Average;N.push(f.hammRatio),f.hammRatioN.push(e))),(0,u.map)(p?.hammRatio,(e=>N.push(e))),(0,c.lt)(m?.hammRatio,A)&&L.push("gradient"),(0,c.lt)(p?.hammRatio,A)&&L.push("DCT")),L.length>0&&O.push("different image content ("+(0,l.andList)(L)+")");const j=g>=I,z=j&&N.avg>=A;j||O.push("different dominant colors");const V={meanHashCorr:(0,c.sigFigs)(f.hammRatio,2),diffHashCorr:B?void 0:(0,u.map)(m,(e=>(0,c.sigFigs)(e.hammRatio,2))),dctHashCorr:B?void 0:(0,u.map)(p,(e=>(0,c.sigFigs)(e.hammRatio,2))),hashCorrAvg:N.avg,minImageCorr:A,imageCoeffDelta:_,colorCorr:(0,c.sigFigs)(g,2),minColorCorr:I,colorCoeffDelta:x,isGreyscale:h,bRotation:f.bRotation,aAspectRatio:v,bAspectRatio:S,isSimilar:z,whyNotSimilar:z?void 0:(0,l.andList)(O)};return D().info("compareImageHashes",{a:(0,d.pickCompact)(r,"uri","id","assetId"),b:(0,d.pickCompact)(s,"uri","id","assetId"),...V}),{a:r,b:s,...V}}function L(e,t,i){return O(e,t,i)?.isSimilar??!1}function R(e){return(0,c.sigFigs)((0,c.clamp)(0,1,e),3)}function N(e){return null!=e&&(0,c.gte)(e.meanHashCorr,.9)&&(0,c.gte)(e.colorCorr,.9)}t.isGreyscaleMeanHash=C,t.meanHashVariants=function(e,t=!1,i=E.HashDim){const r=(t=t||null!=e.match(x))?(0,h.padding)("0",2*i*i):"",s=A(e,t,i);return f.Rotations.map((e=>(0,_.b64encode)(BigInt("0b0"+(0,S.rotateSquareMatrix)(s,e).map((e=>e.toString(2))).join("")+r))))},t.hammRatio=F,t.isSimilarImage=I,t.compareImageHashes=O,t.isVerySimilarImage=async function(e,t,i="debug",r={}){return I(e,t,i,{rotationsToCheck:[0],...r,minImageCorr:.92,minColorCorr:.92})},t.isSimilarImageHash=L,t.isVerySimilarImageHash=function(e,t,i={}){return N(O(e,t,i))},t.isVerySimilarComparison=N,t.imageHashSimilarity=function(e,t){return(0,u.map)(O(e,t),(e=>(0,P.avg)([e.meanHashCorr,e.colorCorr])))}},42725:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return n(this,r,"f",s).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return n(this,r,"f",s).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...n(this,r,"f",s)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},n(r,r,"f",s).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,r=m,s={value:[]},m.UHD8k=new r("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new r("uhd5k",5120,2880,h.Fit,!1),m.UHD=new r("uhd4k",4096,2160,h.Fit),m.QHD=new r("qhd",3120,1440,h.Fit),m.FHD=new r("fhd",1920,1080,h.Fit),m.HD=new r("hd",1280,720,h.Fit),m.WVGA=new r("wvga",720,480,h.Fit),m.QVGA=new r("qvga",320,240,h.Fit),m.QQVGA=new r("qqvga",160,120,h.Fit),m.S480=new r("s480",480,480,h.Square),m.S240=new r("s240",240,240,h.Square),m.S120=new r("s120",120,120,h.Square),m.S60=new r("s60",60,60,h.Square)},4192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},66778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.matchAndWriteRotation_=t.matchRotation=void 0;const r=i(19851),s=i(68708),n=i(21605),a=i(50213),o=i(56038),l=i(47783),u=i(67083),c=i(95141),d=i(48368),h=i(80361),f=(0,r.lazy)((()=>(0,a.mkLogger)("img.MatchRotation")));async function m(e,t){return(0,o.time)("img.matchRotation",(async()=>{const i=await(0,d.imageHash)(e),r=await(0,d.imageHash)(t),s=(0,h.compareImageHashes)(i,r);if(null!=i&&null!=r&&null!=s)return f().tap({level:"info",msg:"matchRotation()",result:{rotation:s.bRotation,exemplarImageHash:i,destImageHash:r,imageHashComparison:s},meta:{src:e,dest:t}});f().warn("failed to compute image hashes",{a:e,b:t})}))}t.matchRotation=m,t.matchAndWriteRotation_=async function(e,t,i=0){const r=await m(e,t);if(null==r)return;const a=(0,n.normalizeRotation)(r.destImageHash.rotation+r.rotation+i);if(f().info("matchRotation() computed newRotation",{currentRotation:r.destImageHash.rotation,additionalRotation:i,rotationToMatch:r.rotation,newRotation:a}),null==a)return void f().warn("Can't compute final orientation",{newRotation:a,file:t.nativePath,r});const o=(0,c.rotationToWriteTag)(a);if((0,s.isEmptyObj)(o))return void f().warn("rotationToWriteTag() returned null",{newRotation:a,mimetype:r.destImageHash.mimetype,file:t.nativePath});const d=await(0,u.ensureHistoryRecords)(await t.sidecar(),(0,u.mkHistoryRecords)(u.Actions.set,o));return await(0,l.writeTags_)(t,o),f().tap({level:"info",msg:"matchAndWriteRotation_()",result:{...r,writtenTags:o,rotation:a,historyRecords:d},meta:{exemplar:e,dest:t}})}},78011:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const s=r(i(9288)),n=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,r)=>t>=(0===r?e[i]:r%i==0?e[r-i]:e[r-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:s.default.fit.fill,width:t,height:t}).raw().toBuffer(),r=(0,o.rgb2labArray)(i);return{meanHash:(0,n.flatten)(r.map(c)),diffHash:(0,n.flatten)(r.map(d))}}},52121:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const r=i(19851),s=i(78923),n=i(95696),a=i(50213),o=i(28874),l=i(12089),u=i(16170),c=i(13940),d=i(4192),h=i(5733),f=i(50961),m=(0,r.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=n.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,s.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},48604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,r.lazy)((()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const r=i(40958),s=i(33374),n=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,n.isNumber)(e)?e:((0,n.toGt0)(e.width)??0)/((0,n.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const r=Math.abs(e-t);return r>i?void 0:r}))??e))}function c(e,i,r=t.RatioEpsilon){return(0,a.lt)((0,n.absdiff)(u(e),u(i)),r)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const r=Math.abs(t.i-e);return r[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,s.maybeDimSwap)(e.dimensions,e.rotation),(0,s.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,n.sigFigs)(e,3))}},34943:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const r=i(19851),s=i(31586),n=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,r.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,r.lazy)((()=>new n.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,r,n,a]=e.split("\t"),o=(0,s.toGt0)(n),l=(0,s.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:r,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const s=r(i(9288)),n=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,n.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,s.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,n.lazy)((()=>{s.default.simd(l.Settings.enableSIMD.valueOrDefault),s.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),s.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const s=i(77988),n=r(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),v=i(56519),w=i(56038),b=i(57159),S=i(95696),P=i(17217),_=i(28874),T=i(47783),M=i(16170),E=i(95141),k=i(54979),D=i(1078),x=i(63870),C=i(86580),A=i(277),F=i(16047),I=i(13940),O=i(5733),L=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,T.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await z(e,t))?.nativePath}async function j(e,t,i,r,a){const o=t?.[i];if(!(o instanceof s.BinaryField))return;const l=o.bytes<_.Settings.maxEmbeddedBuffer.valueOrDefault;try{const t=await B(e,i,l);if(null==t)return;const s=(0,n.default)(t,{failOn:_.Settings.imageFailOn.valueOrDefault}),o=await s.metadata(),u=(0,C.aspectRatio)(o);if(null!=a&&null!=u&&!(0,h.closeTo)(a,u,.2))return void N().info("imgFromExif("+e+", "+i+"): rejecting (aspect ratio mismatch)",{fileAspectRatio:a,renderedAspectRatio:u});const c=(0,C.lteBoth)(r,o);return N().debug("imgFromExif("+e+", "+i+")",{valid:c,minDim:r,useBuffer:l,fileAspectRatio:a,renderedAspectRatio:u,dim:(0,f.pick)(o,"width","height")}),c?{sharp:s,file:(0,m.isString)(t)?S.PosixFile.for(t):void 0}:void 0}catch(t){return void N().info("Failed to read image from EXIF tag "+i,{src:e,error:t})}}async function z(e,t){const i=t.toLowerCase().endsWith("tiff")?".tiff":".jpg";try{const r=await(0,I.tmpImageFile_)({src:e,tag:t,ext:i});return await r.applyIfEmpty_({retries:2,fn_:i=>(0,T.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,x.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=j,t.toSharp=function(e){const t=e;if((0,O.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,n.default)(t.file.nativePath,{failOn:_.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const r=N().addParameterContext(e.nativePath);(0,O.setupSharp)();const n=await(0,k.readMimeType)(e);if((0,u.blank)(n))return r.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,D.extractSizeInfoFromFile)(e);if(null==a)return void r.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,M.isVideoMimeType)(n),S=(0,M.isLibrawMimeType)(n),P=a.dimensions,x=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==x?.width||null==x?.height)return r.throw(e+" is not supported (missing dimensions)",{dim:x,doNotSend:!0,mimetype:n,isRaw:S,isVideo:g});const I=(0,C.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),z=(0,M.isSharpMimeType)(n)&&null==t,V=(0,E.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||z||V)r.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:z,isMirrorOrientation:V});else{const i=!1,n=await(0,T.readRawTags)(e,i);if(null==n)r.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[..._.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(..._.Settings.embeddedThumbnails.values);const a=x.width*x.height*.2,u=x.width*x.height*.05,d=(0,l.sortBy)(i.filter((e=>n[e]instanceof s.BinaryField)),(e=>{const t=n[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){r.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>j(e,n,t,x,I)))}}}(0,M.isSharpMimeType)(n)&&f("sharp",(async()=>({file:e}))),(0,F.isHeifMimeType)(n)&&await(0,A.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,A.heif2img)(e),(e=>({file:e}))))),S&&f("raw2tiff",(()=>(0,v.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,L.isVideoSupported)())try{return await(0,v.thenMap)((0,L.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new b.WrappedError("Failed to extract video frame for "+e,t)}else r.warn("video file, but video support is missing",{src:e.nativePath,mimetype:n,minDim:t})}));const W=[];for(const i of d)try{const s=await(0,w.time)("img.read."+i.desc,i);if(null!=s)return r.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:s.file?.nativePath}),{desc:i.desc,rot:m,mimetype:n,...s};r.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){r.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new b.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=z},21473:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=void 0;const s=r(i(34589)),n=i(76760),a=r(i(9288)),o=i(50357),l=i(98553),u=i(68708),c=i(23560),d=i(43899),h=i(28874),f=i(5733);t.testSharp_=async function e(t){try{(0,f.setupSharp)();const e=t??(0,n.join)(d.ProjectPath.Public(),"images","logo@5x.png"),i=(0,a.default)(e,{failOn:"error"}),r=await i.resize(24,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,o.eql)((0,u.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:24,height:32,channels:3}),"Unexpected sharp output: "+(0,l.stringify)(r.info))}catch(i){if(!(0,c.isWorkerService)()&&h.Settings.enableSIMD.valueOrDefault)return h.Settings.enableSIMD.envValue=!1,e(t);throw i}}},181:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const s=r(i(9288)),n=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),v=i(54979),w=i(63870),b=i(5733),S=i(50961),P=i(66106),_=i(51210),T=(0,n.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void T().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),r=T().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(r)&&T().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const M=(0,n.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return M().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:M,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(T().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,_.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))T().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,S.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,s.default)(i.file.nativePath,{failOn:t});if((0,b.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,s.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,r.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,r.lazy)((()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,n.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),v=i(56038),w=i(31562),b=i(98314),S=i(34102),P=i(88561),_=i(95696),T=i(17217),M=i(74128),E=i(31843),k=i(70417),D=i(33847),x=i(28874),C=i(94678),A=i(43207),F=i(47783),I=i(16170),O=i(95141),L=i(1078),R=i(63870),N=i(89782),B=i(13940),j=i(34592),z=(0,r.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,n.isTrue)(e?.ignoreffmpeg)?void 0:await(0,j.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,r.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return z().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,S.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,E.lerp2d)(e,{x:76800,y:x.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:x.Settings.transcodeBitrateUHD.valueOrDefault}),2);const U=(0,r.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function q(e){return await(0,t.isVideoSupported)()?_.PosixFile.for(await(0,t._extractVideoFrame_)((0,T.toNativePath_)(e))):void 0}async function H(e,t){const i=V("extractVideoFrame",e),r=_.PosixFile.for(e);if(!(0,n.isTrue)(t?.useFfmpeg)&&!await(0,j.isFFmpegSupported)())return i.throw("no video implementation");const s=await(0,B.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const o=await r.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,F.readRawTags)(r,!1);if(null==l)return i.throw("no tags");const u=(0,O.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,L.extractSizeInfoFromTags)(l,u)?.dimensions,d=await s.stat(),h=null==d?void 0:await(0,N.dimensions)(s);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:c,destDim:h}),s.nativePath;const f=(0,A.extractDurationSec)(l),m=Math.min(f??0,x.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:m,...c};await(0,j.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,F.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function G(){return x.Settings.transcodeVideos.valueOrDefault&&await(0,j.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,F.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const n=(0,A.extractDurationSec)(i);if(!(0,c.gt)(n,x.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:n}});const a=(0,s.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,s.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(x.Settings.doNotTranscodeMimeTypes.values,r);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:r,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=q,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:U,impl:e=>H(e)}),t.__extractVideoFrame_=H,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,r){if(!await G())return;const n=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,F.readTags)(e),h=(0,L.extractSizeInfoFromTags)(d),m=(0,A.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===r?.force)await i.unlink();else if(await async function(e,t){const i=await(0,F.readRawTags)(t),r=await(0,F.readRawTags)(e),s=(0,A.extractDurationSec)(r),n=(0,A.extractDurationSec)(i);return z().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const r=V("extractMaxBitrate",e),s=x.Settings.minVideoDimension.valueOrDefault,n=i.ImageWidth;if(null!=n&&!(0,u.gte)(n,s))return r.throw("invalid width: "+n,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,s))return r.throw("invalid height: "+a,{ignorable:!0});const o=(0,C.extractBitrateKbps)(i)??x.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(n,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:n,height:a,videoBitrateKbps:l};return r.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,v.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:r.halt,...g},m=x.Settings.transcodeMaxDim.valueOrDefault,p=(0,k.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,j.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,M.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-n})}catch(t){throw(0,M.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:Date.now()-n}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await q(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,j.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),v=i(84258),w=i(28874),b=i(76280),S=i(63870),P=i(19769),_=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function T(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:w.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=T;const M=/ffmpeg version n?(?\S+)/i,E=(0,u.lazy)((async()=>{const e=await T();if(null==e)return void _().info("failed to find ffmpeg in $PATH",{ffmpegPath:w.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=M.exec(t.result)?.[1];return _().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semverSatisfies)(i,">=3.2")}}));function k(){E.unset(),t.ffmpegVersionDescription.unset()}function D(e){const t=e?.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}function x(e){const t=[...w.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(w.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),r=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+r),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function A(e){const t=w.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(E(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",k),(0,g.ee)().on("clearToolCache",k)})),t.ffmpegVersion_=async function(){return await E.prior()??E.refresh()},t.isFFmpegSupported=async function(){return null!=await E()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await T(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=x,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await T(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...x(t),...A(t),...D(t),"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){_().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,v.unlink)(t.dest,"debug");const r=(0,p.errorToS)(i,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(r))return _().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return _().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await T(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const r=i(19851),s=i(42659),n=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,r.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const r=await(0,c.jpegtranNativePath_)();if(!(0,n.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(r,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:s.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:s.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),v=i(89782),w=i(13940),b=i(42725),S=i(19769),P=(0,r.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,w.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>k(e,t)})};const _=["-T"],T=["-Z","-"],M=["-o","1"],E=["-t","0","-j"];async function k(e,t){const i=await(0,v.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=b.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[..._,...T,...M,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],w={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:w});const k=(0,c.execFile)(g,y,void 0,w),D=[];function x(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});D.push(r)}}if(k.on("error",x),k.stderr.on("data",x),await t.writeStream_(k.stdout),(0,s.isNotEmpty)(D))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:D,path:e.nativePath});(0,c.endProcess)(k)}t.dcraw_emu_=k},36192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,r.lazy)((async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},45657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.r=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(45599),l=i(98553),u=i(55835),c=i(34666),d=i(50213),h=i(37628),f=i(37805),m=i(46292),p=i(95696),g=i(93756),y=i(28874),v=i(63870),w=i(71706),b=i(81674),S=i(33603),P=i(70114),_=(0,o.defer)((()=>(0,d.mkLogger)(T().l))),T=(0,r.rolazy)((()=>(0,w.j)("G8oAKIzTFfOihHWPgG6m/h0h65IqCWu72UHSOixdfW12GgbIbSdJW2sLEmvLsqcHfOPXk00SqojDRomicXUE+MuLfPaoTzFWZPq8AdmWyQVUWERkBLoYBhqafaAvY27+LDra0blcQ4Vnjn/ukQh/C4o0cd0B")));async function M(e){const t=await(0,S.sids)({timeoutMs:(0,v.commandTimeoutMs)()});if((0,s.isEmpty)(t))return _().warn("no-op: empty sids");const i=(0,l.stringify)({uids:[...t,e],coupon:y.Settings.coupon.valueOrDefault,version:f.version}),r={...T().r,body:i},n=await(0,g.request)(T().u,r);_().info(T().u,{req:r,response:n}),n.ok?await(0,P.writeLicense)(JSON.parse(n.body)?.[T().a],(0,v.commandTimeoutMs)()):_().warn(T().u,{req:r,response:n})}t.r=(0,r.rolazy)((async()=>{const e=T().s+": ";try{if(!y.Settings[T().s].valueOrDefault)return _().debug(e+"no-op (settings disabled)");const t=(await(0,b.m)()).filter((e=>null!=e.l&&(0,n.notBlank)(e.s))),i=new Date,r=t.find((e=>e.ok&&(0,c.gt)(i,e.l?.exp)));if(null!=r)return _().debug(e+"no-op: ",{current:r});const s=await(0,u.map)((0,m.configDir)(),(e=>p.PosixFile.for(e).join(T().s+"-v"+f.version).mkdirp_()));for(const r of t){if((0,n.blank)(r.s)||null==r.l||ie.startsWith("cu:")));if(null!=t){if(await(s?.join((0,h.shortFsStringSha)(r.s,14)+".txt").applyIfEmpty_({fn_:async i=>{await M(t),await i.writeJson_({l:r.l,at:Date.now()}),_().warn(e+"requested",r)},timeoutMs:(0,v.commandTimeoutMs)()})),await(0,b.p)())break}else _().debug(e+"skipping (no cu)",r)}}catch(t){_().warn(e+"failed",t)}}),15*a.minuteMs)},71706:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=void 0;const r=i(38522);t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))}},42042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEmail=void 0;const r=i(22573),s=i(28874),n=i(81674);t.getEmail=async function(){const e=s.Settings.email.value;if((0,r.notBlank)(e))return e;for(const e of await(0,n.m)())if((0,r.notBlank)(e.l?.sub))return e.l?.sub}},83950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{static for(e){return new this(e.str,e.l,e.sids,e.src)}constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map((e=>(0,c.prefix2scheme)(e)))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.p=t.l=t.t=t.b=t.m=t.vok=t.v=t.v_=t.k=void 0;const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),v=i(50213),w=i(56519),b=i(76596),S=i(46292),P=i(87290),_=i(77740),T=i(34102),M=i(83278),E=i(28874),k=i(37692),D=i(71706),x=i(83950),C=i(72042),A=i(33603),F=i(48132);t.k=(0,y.rolazy)((()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw==")));const I=(0,a.defer)((()=>(0,v.mkLogger)((0,t.k)().l)));async function O(e){const i=await(0,C.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,b.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,b.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,_.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function L(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:x.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,A.sids)({timeoutMs:r}),src:i})}catch(i){return I().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{err:i}}})}}async function R(e,t){const i=[],r=await(0,w.sortByAsync)({name:"rawLicenseFromDir("+e+")",arr:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await L((0,m.toA)(await e.readLines()).map((e=>e.trim())).join(""),e.nativePath,F.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function B(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.v_=O,t.v=L,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await L(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof x.L?r:void 0},t.m=(0,y.rolazy)((async()=>{if((0,_.getDevEnvFlag)((0,t.k)().x))return[];const e=await(0,A.sids)({timeoutMs:F.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),(e=>M.BaseFile.for(e))),s=(n=(0,l.flatten)((await(0,w.someOrTimeout)([()=>function(e){return L(E.Settings[(0,t.k)().L].value,"Settings",F.UserTimeoutMs,e)}(e),()=>R(i?.join((0,t.k)().d),e),()=>R((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>R(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:F.UserTimeoutMs})).filter((e=>!(e instanceof Error)))),(0,r.sortBy)(n.filter((e=>null!=e&&((0,f.isError)(e)&&I().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l))),(e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)])));var n;return I().tap({msg:(0,t.k)().d+"()",result:s})})),(0,o.later)((()=>{(0,T.ee)().on("clearCache",(()=>t.m.unset())),(0,T.ee)().on((0,t.k)().c,(()=>t.m.unset())),k.stateEvents.on((0,t.k)().c,(()=>t.m.unset()))})),t.b=N,t.t=B,t.l=async function(){try{return await B()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await B()===(0,t.k)().g}catch{return!1}}},72042:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.V=t.l=void 0;const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)((()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))),t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find((e=>e.k===s));if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)}},84194:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.isValidUid=t.toUID=t.UidLength=t.prefix2scheme=t.sortUids=t.getScheme=t.S=void 0;const n=i(40958),a=i(76790),o=i(22573),l=i(45599),u=i(50989),c=i(54993),d=i(22454),h=i(19851),f=i(50213),m=i(37628),p=i(55222),g=i(71706),y=(0,l.defer)((()=>(0,g.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA==")));function v(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,u.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl"),t.getScheme=v,t.sortUids=function(e){return(0,a.sortBy)((0,n.uniq)(e.filter(S)),(e=>[t.S.indexOf(v(e))??t.S.length+1,e]))},t.prefix2scheme=function(e){return y()[e]};const w=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15,t.toUID=function(e,i){try{const r=(0,c.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,o.blank)(r)||w.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,m.shortStringSha)(r,t.UidLength,p.Radix58)}catch(t){return void(0,f.mkLogger)("toUID").warn("failed",{pfx:e,err:t})}};const b=(0,l.defer)((()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`)));function S(e){return null!=e&&null!=b().exec(e)}t.isValidUid=S,t.SchemeCounts=class{constructor(e){r.set(this,new Set),this.schemeCounts=(0,h.lazy)((()=>{const e=new d.CountingSet;for(const t of s(this,r,"f")){const i=v(t);null!=i&&e.incr(i)}return e})),null!=e&&this.addUids(e)}get size(){return s(this,r,"f").size}addUids(e){for(const t of e)null==v(t)||s(this,r,"f").has(t)||(s(this,r,"f").add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}},r=new WeakMap},33603:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearSids=t.addSids=t.sids=t.win_machineGuid_=t.readInfo=t.k=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(45599),o=i(96249),l=i(68708),u=i(51926),c=i(59455),d=i(54993),h=i(50213),f=i(7282),m=i(56519),p=i(84777),g=i(84542),y=i(19254),v=i(45879),w=i(70854),b=i(57902),S=i(72308),P=i(43334),_=i(24399),T=i(7014),M=i(30933),E=i(71706),k=i(84194);t.k=(0,a.defer)((()=>(0,E.j)("G9ABYIzDOIZ8NLQ4t7qW8tNrmrOzz+qFGfAxl8jW4E2tLxwWRZT5TueCnPcwgTzT1DN3veRB+e7EYGlYHg6nhjBDQv7zI6EcYWk35z6QuZC3Q0itjrLCbmgd0iED0BvGiYLBJwRU1O9/3Agbl8IfG6ITVFWDRwyTw3rbUMo/XMyAVW7R23mkwUx0l4/7iA13RV/nmPuJFKp5BvJW7SoXJZoWEfdSNYYhN5UCtkbC7O1AaPIbU3P6uRLmEyb4TaHWzFigvrlmZVUzzp9j/Mz55vqN88ewd1Nrfh7gkVRQ7TtB7Ztz3XJxYC3ogdJHg8HGsG4=")));const D=(0,a.defer)((()=>(0,h.mkLogger)((0,t.k)().n)));async function x(e=(0,t.k)().pc){if(P.isLinux)try{const t=await(0,y.fileGrep_)(e,/^\s*(?:hardware|revision|serial|model)\s*[:=]\s*[a-z\d]{6}.*$/i),i=(0,r.compactBlanks)((0,g.splitLines)(t).map((e=>e.replace(/\s+/g," ")))).sort();return i.some((e=>null!=e.match(/^serial/i)))?i:void 0}catch{return}}t.readInfo=x;const C=(0,a.defer)((()=>(0,m.thenMap)(x(),(e=>(0,k.toUID)(k.S.lc,e.join(",")))))),A=/o\.e\.m\./i;async function F(e){return(0,r.uniq)(await Promise.all((0,t.k)()[e].map((e=>(0,v.readFileMaybe)(e,b.LogLevels.trace))))).map(d.toS).filter((e=>(0,s.notBlank)(e)&&null==e.match(A)))}async function I(){return P.isLinux?(await F("lm")).map((e=>(0,k.toUID)(k.S.lm,e))):void 0}async function O(){return P.isLinux?(await F("lp")).map((e=>(0,k.toUID)(k.S.lp,e))):void 0}async function L(){return P.isLinux?(await F("lb")).map((e=>(0,k.toUID)(k.S.lb,e))):void 0}async function R(){if(P.isMac)try{return(0,l.entries)(await async function(){const e=await(0,p.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*n.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map((([e,t])=>(0,k.toUID)(e,t)))}catch(e){return void D().warn((0,t.k)().i+" failed",e)}}async function N(){return(await _.PowerShell.instance().executeJson((0,t.k)().w))?.MachineGuid}async function B(){return P.isWin?(0,k.toUID)(k.S.wm,await N()):void 0}t.win_machineGuid_=N;const j=(0,a.defer)((()=>(0,k.toUID)(k.S.cm,(0,M.cpuInfo)()[0].model)));async function z(){return P.isLinux?(0,k.toUID)(k.S.bm,(0,r.compactBlanks)(await F("bm")).map((e=>e.trim())).join("\n")):[]}async function V(){return(0,k.toUID)(k.S.li,await((0,w.LibraryUIDStore)()?.readUid_()))}async function W(){return(0,k.toUID)(k.S.si,await((0,w.SystemUIDStore)()?.readUid_()))}function U(){return(0,S.networkMacAddresses)().map((e=>(0,k.toUID)(k.S.nm,e)))}async function q(){return(0,c.toA)(await(0,T.volumes)()).map((e=>(0,k.toUID)(k.S.vl,e.uuid)))}const H=new Set;t.sids=async function({timeoutMs:e}){const t=Date.now(),i=[j,C,R,V,W,z,I,O,L,B,U,q],r=(0,o.flatten)(await(0,m.someOrTimeout)(i,{timeoutMs:e})).filter(u.isString);for(const e of r)H.add(e);return D().tap({msg:"sids()",result:(0,k.sortUids)([...H,...r]),meta:{timeoutMs:e,elapsedMs:Date.now()-t}})},t.addSids=function(e){if((0,f.isTest)())for(const t of e)H.add(t)},t.clearSids=function(){(0,f.isTest)()&&H.clear()}},48132:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},70114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveIfBetter=t.licensesInDirectory=t.writeLicense=void 0;const r=i(45599),s=i(55835),n=i(50213),a=i(23560),o=i(37628),l=i(56519),u=i(46292),c=i(87290),d=i(34102),h=i(83278),f=i(37692),m=i(83950),p=i(81674),g=(0,r.defer)((()=>(0,n.mkLogger)("writeLicense")));async function y(e,t){return(await(0,l.mapAsyncSerial)({name:"read",arr:e.childFiles(),f:async e=>(0,p.vok)(await e.readTextFile(),e.nativePath,t)})).filter((e=>e.ok&&e instanceof m.L))}async function v(e,t,i){if(null!=t)if((await y(t,i)).some((t=>t.cmp(e)>=0)))g().info("saveIfBetter(): no-op for "+t);else{const i=t.join((0,o.shortFsStringSha)(e.s)+".txt");try{return await i.writeFile_(e.s),(0,d.ee)().emit("reloadLicenses"),(0,a.isWebService)()&&(0,f.addStateEvent)("reloadLicenses"),g().info("saveIfBetter(): wrote to "+i),i}catch(e){return void g().error("saveIfBetter(): failed to save license to "+t,e)}}}t.writeLicense=async function(e,t){const i=await(0,p.vok)(e,"candidate",t);if(null==i)return g().error("!ok",e);await v(i,(0,c.libraryDataDirPosixFile)()?.join((0,p.k)().d),t),await v(i,(0,s.map)((0,u.configDir)(),(e=>h.BaseFile.for(e).join((0,p.k)().d))),t),await p.m.refresh()},t.licensesInDirectory=y,t.saveIfBetter=v},34474:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allRecentLogEntries=t.recentLogFiles=void 0;const r=i(40958),s=i(42659),n=i(41400),a=i(96249),o=i(68708),l=i(34666),u=i(20214),c=i(71371),d=i(50213),h=i(42638),f=i(31562),m=i(98314),p=i(89968),g=i(28874),y=i(4904),v=i(57902),w=i(89241),b=i(83954);function S(e=10*s.minuteMs){const t=Date.now()-e;return(0,u.thenMap)(p.DirectoryEntry.for(g.Settings.logDir.valueOrDefault),(e=>e.filterDescendantFiles((async e=>[".log",".log.gz"].includes(e.ext)&&(0,l.gte)(e.mtimeMs(),t)))))}t.recentLogFiles=S,t.allRecentLogEntries=async function(e=50){(0,b.writeRecentLogEntries)();const t=(0,o.fromEntries)(v.LogLevels.values.map((t=>[t,new c.BoundedGreatestSet(e,y.logEntrySorter)]))),i=Date.now()-s.hourMs,p=(0,d.mkLogger)("allRecentLogEntries()");return await(0,u.thenMap)(S(),(e=>(0,h.withBoundedConcurrency)({name:"allRecentLogEntries()",laters:e.map((e=>async()=>{try{const a=[],o=new w.LogReader(e,(e=>a.push(e)));for(await(0,f.untilTrue)((()=>o.ready()),{timeoutMs:10*s.secondMs});!o.complete()&&!o.hasErrors();){const e=o.shift();null==e?await(0,n.delay)(5):e.ts>i&&t[e.l]?.add(e)}(0,r.isNotEmpty)(a)&&(p.warn("Read error(s) for "+e,a),a.some((e=>"Z_BUF_ERROR"===e.code||(0,m.errorToS)(e).includes("unexpected end of file")))&&(0,l.lt)(e.mtimeMs(),Date.now()-s.minuteMs)&&(p.warn("Unlinking corrupt logfile "+e),await e.unlink_()))}catch(t){p.warn("Failed to read entries from "+e,t)}}))}))),(0,a.flatten)((0,o.values)(t).map((e=>e.vacuum()))).sort(((e,t)=>(0,l.cmp)(e.ts,t.ts)))}},49794:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,s.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,n.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:r})}}},32105:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(19851),s=i(23560),n=i(66184),a=i(72210);class o{log(e,t,i,r){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,s.processName)(),ctx:t,msg:i,meta:r})}enabled(e,t){return(0,n.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,r.lazy)((()=>new o))},14593:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const r=e.result(),s=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const r of this.loggers())r.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const r=i(50213),s=i(43705);t.currentFileLogger=function(){return(0,r.rootLoggers)().find((e=>e instanceof s.LogWriter))}},28981:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)((()=>new s.PlaintextLogFormatter))},31256:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,r.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,n.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,s.uniq)((0,s.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},51576:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const n=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),b=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),S=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&b().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),r.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,n.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{b().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){b().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),s(this,r,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))try{const a=this.socket;null==a?s(this,r,"f").call(this):a.write(this.logFormatter.format(e,t,i,n)+S)}catch(r){b().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:n,error:r})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}r=new WeakMap},20839:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const r=i(76760),s=i(42659),n=i(28874);t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))}},12495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogDirCleanup=void 0;const r=i(19851),s=i(42659),n=i(23560),a=i(79267),o=i(32144),l=i(28874);t.LogDirCleanup=(0,r.lazy)((()=>(0,n.isBillingService)()?void 0:a.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:s.weekMs,isPrunable:e=>(0,o.isLogExt)(e.ext)})))},4904:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const r=i(76790),s=i(31586),n=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,s.isNumber)(e?.ts)&&(0,n.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,r.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const r=i(19851),s=i(57902);class n{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=n,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,r.lazy)((()=>new n(s.LogLevels.warn))),t.defaultLogLevel=(0,r.lazy)((()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){r.add(this),this.setting=e,this.silent=!1,s.set(this,[]),n.set(this,(0,l.lazy)((()=>{o(this,s,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,s,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,n,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,r,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,r,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){if(null==e||0===o(this,s,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,s,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const r=i(31586),s=i(50989),n=i(28874);t.LogLevels=(0,s.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,r.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=n.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,r).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-r).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},89241:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogReader=void 0;const d=i(73024),h=i(38522),f=i(4001),m=i(14977),p=i(33456),g=i(92322),y=i(4904),v=i(98192);t.LogReader=class{constructor(e,t){if(r.add(this),this.f=e,this.start=Date.now(),this.lines=new g.SortedSet(y.logEntrySorter),s.set(this,!1),n.set(this,!1),a.set(this,!1),this.from=(0,f.stripCopySuffixFromName)(e.name),this.fileStream=(0,d.createReadStream)(e.nativePath,{autoClose:!0}),!(0,m.isExtOrCompressedExt)(e.ext,".log"))throw new Error(e+" is not a logfile");this.stream=(e.ext.toLowerCase().endsWith(".gz")?this.fileStream.pipe((0,h.createGunzip)()):e.ext.toLowerCase().endsWith(".br")?this.fileStream.pipe((0,h.createBrotliDecompress)()):this.fileStream).pipe(new p.LineReader).on("error",(e=>{t(e),u(this,a,!0,"f")})),this.stream.on("data",c(this,r,"m",o).bind(this)),this.stream.on("close",(()=>{this.fileStream.resume(),u(this,s,!0,"f")})),this.stream.on("end",(()=>{u(this,s,!0,"f")}))}toString(){return"LogReader("+this.f.nativePath+")"}status(){return{hasErrors:c(this,a,"f"),ended:c(this,s,"f"),destroyed:this.stream.destroyed,lines:this.lines.length,paused:c(this,n,"f")}}hasErrors(){return c(this,a,"f")}get ended(){return c(this,s,"f")}ready(){return this.ended||this.lines.length>32}complete(){return this.ended&&0===this.lines.length}peek(){return this.ready()?this.lines.at(0):void 0}shift(){const e=this.lines.shift();return null!=e&&c(this,r,"m",l).call(this),e}shiftLte(e){const t=this.lines.shiftLte(e);return t.length>0&&c(this,r,"m",l).call(this),t}},s=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakSet,o=function(e){if(null===e)u(this,s,!0,"f");else{const t=(0,v.chunkToLogEntry)(e);null!=t&&this.lines.add({...t,from:this.from}),this.lines.length>10240&&!c(this,n,"f")&&(this.fileStream.pause(),u(this,n,!0,"f"))}},l=function(){this.lines.length<1024&&c(this,n,"f")&&(this.fileStream.resume(),u(this,n,!1,"f"))}},24068:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const r=i(73024),s=i(76760),n=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),b=i(38836),S=i(99331),P=i(42638),_=i(76596),T=i(98314),M=i(89968),E=i(29882),k=i(28874),D=i(28981),x=i(20839),C=i(21727),A=i(66184),F=i(57902),I=i(72210),O=i(98192);function L(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=L;class R extends b.EndableWrapper{constructor(e=void 0,t=L){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,k.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,E.mkdirp_)(e),this.root=await M.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=s.sep+(0,p.serviceName)()+"-"+n.pid+"-",n.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),x.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),n.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,S.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,A.ifLog)(F.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,r.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,s.join)(e,i))}))}catch(t){return void(0,A.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,T.errorToS)(t))))}}))}async scan(e=!1){if((0,S.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,_.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,S.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,E.mkdirp_)(t),this.watchDir(t)}catch(e){(0,A.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,T.errorToS)(e))))}(0,S.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await M.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const r=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(r,i))return;await(0,f.thenMap)((0,O.readLogEntries)(e,{start:r,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,A.ifLog)(F.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,T.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const r=i(92322),s=i(82328),n=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new r.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,s.stdoutEnded)()||console.log((0,n.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),b=i(23560),S=i(81168),P=i(78406),_=i(25764),T=i(20197),M=i(14977),E=i(36868),k=i(28874),D=i(32105),x=i(20839),C=i(21727),A=i(66184),F=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,r){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}enabled(){return!0}end(){}async flush(){}};class O extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*x.DefaultLogFlushMs),rank:_.EndableRanks.logger,unref:!0,onEnd:()=>c(this,s,"f").call(this)}),r.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,s.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,r,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:x.DefaultLogFlushMs,processName:b.processName,logFilter:A.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,r,"m",n).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,r);else{const s={ts:Date.now(),l:e,ctx:t,msg:i};null!=r&&(s.meta=(0,F.prepMeta)(r)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(s)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=O,s=new WeakMap,r=new WeakSet,n=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,r,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),s=e.splice(0,i);this._linesSinceRotate+=s.length,t.write(s.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,r,"m",a).call(this,e,t),c(this,r,"m",u).call(this))},l=async function(){await c(this,r,"m",u).call(this);const e=(0,S.stripAnsiEsc)(this.logOpts.processName()),t=await(0,T.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,r,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,E.endStream)(e.stream),k.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,M.gzip_)(e.nativePath))}catch(e){c(this,r,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,(e=>(0,r.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const r=i(22573),s=i(84542),n=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,r.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,n.stripCopySuffixFromName)(e.name),r=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,s.splitLines)(o)){const t=l(e);null!=t&&r.push({...t,from:i})}return r},t.chunkToLogEntry=l},22662:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const r=i(19851),s=i(76790),n=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,r.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,r.lazy)((()=>(0,n.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,n.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,n.values)(l()))e.push(...t.toA());return(0,s.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const r=i(76760),s=i(41400),n=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),b=i(24068),S=i(43705),P=i(51879);function _(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),T();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,r.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new S.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,n.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&b.LogTail.instance()}function T(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=_,t.setupLogFormatter=T,(0,s.later)((()=>{h.Settings.logStdout.watchLater(_),h.Settings.logDir.watchLater(_),h.Settings.tailLogs.watchLater(_),h.Settings.logColor.watchLater(T),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},83954:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeRecentLogEntries=void 0;const r=i(89179);t.writeRecentLogEntries=function(){return(0,r.currentFileLogger)()?.writeRecentLogEntries()}},82647:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const r=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...r),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...r]),i}}constructor(e=20){r.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(r=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return n(this,r,"m",s).call(this,-1)}get p29(){return n(this,r,"m",s).call(this,-.5)}get p38(){return n(this,r,"m",s).call(this,-.25)}get p69(){return n(this,r,"m",s).call(this,.5)}get p84(){return n(this,r,"m",s).call(this,1)}get p98(){return n(this,r,"m",s).call(this,2)}get p99(){return n(this,r,"m",s).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,s=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,((e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,n.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max)),s=this.clampValue(e);let n=0;for(let e=0;ea?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map((e=>e.min)),r=this.dims.map((e=>e.max));for(let s=0;s(i[e]+r[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,n.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;in?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,r.sum)(e,((i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0))}},76752:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtEstimate=t.ETA=void 0;const r=i(42659),s=i(75240),n=i(31586),a=i(97352),o=i(82647);function l(e){return(0,n.gt0)(e)?e<=r.minuteMs?"less than a minute remains":"about "+(0,s.fmtDuration)(e,1,{plural:"remains",singular:"remain"}):void 0}t.ETA=class{constructor(){this.taskMillis=new o.Average(10)}push(e){(0,a.mapGt0)(e,(e=>this.taskMillis.push(e)))}clear(){this.taskMillis.clear()}avg(){return this.taskMillis.p69}etaMs(e){const t=this.avg();if(null==t)return;const i=t*e;return i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const r=i(76790),s=i(93973);t.kmeans=function(e,t,i){const n=s(e,t,i);return{...n,centroids:(0,r.sortBy)(n.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const r=i(76790);function s(e,t,i=.5){return(1-i)*e+i*t}t.lerp=s,t.lerp2d=function(e,...t){const i=(0,r.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[n,a]=(0,r.sortBy)(i,(e=>e.x)),o=a.x-n.x,l=(e-n.x)/o;return s(n.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t(0,s.mapFinite)(e[t],(e=>n+=e*e)))),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,(t=>(0,s.mapFinite)(e[t],(e=>n.push(e))))),(0,o.mode)(n)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,(e=>r.push(e))),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,(i=>(0,r.stepRange)(0,t.col,o,(r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},(t=>(0,s.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},36372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stableContentShuffle=t.stableIndexShuffle=t.factors=t.primeSeeds=t.primeInt=t.primes=t.prng=t.prngOrderByClause=void 0;const r=i(76790),s=i(42659),n=i(31586),a=i(97238),o=i(50597),l=i(9103),u=i(55222);function c(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e),u=(s*i*i+n*i)%r,c=(a*i+o)%r;return Math.round((u*c+l)%r)}function d(e){return(0,u.encodeDigits)(a.PrimesPerBin,e,a.PrimeBins).map(((e,i)=>t.primes[i][e]))}t.prngOrderByClause=function(e,i,r){const[s,n,a,o,l]=(0,t.factors)(e);return`(((${s}*${i}*${i}+${n}*${i})%${r})*((${a}*${i}+${o})%${r})+${l})%${r}`},t.prng=c,t.primes=[[353868013,472882027,479001599,517294153],[1012573,1230587,1355297,1572751],[756065159,812182027,899809343,989450477],[3959297,4514113,4823201,5133127],[573259391,666101999,694847533,746151647],[2275327,2770513,3073703,3511973],[173313197,182557181,203457869,222230231],[6054613,6189107,7752103,9852103]],t.primeInt=[1012573,1101689,1183811,1196089,1230587,1355297,1419641,1483733,1572751,2275327,2770513,3010349,3073703,3118691,3174823,3511973,3959297,4514113,4690451,4823201,5133127,5375327,6019889,6054613,6189107,7752103,7752103,9852103],t.primeSeeds=d,t.factors=(0,l.memoize)((e=>{const[i,r,s,o,l,u,c,h]=d(e%a.SeedCount),f=[i/r,s/o,l/u,c/h].map((e=>(0,n.sigFigs)(e,7)));return f.push(t.primeInt[e%t.primeInt.length]),f}),{maxSize:128,ttlMs:s.minuteMs}),t.stableIndexShuffle=function(e,t=1){return(0,r.sortBy)(e,((i,r)=>c(t,r,e.length)))},t.stableContentShuffle=function(e,t=1){return(0,r.sortBy)(e,(e=>(0,o.numericSha)(String(e)+t)))}},55222:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const r=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,r.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)}},38812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SquareMatrix=t.rotateSquareMatrix=void 0;const r=i(21605);t.rotateSquareMatrix=function(e,t){return 0===(0,r.normalizeRotation)(t)?e:new s([...e]).rotate(t).m};class s{constructor(e,t=1){if(this.m=e,this.ary=t,this.rows=Math.sqrt(e.length/t),this.rows!==Math.floor(this.rows))throw new Error(`Only square tuple matrices are supported: ${1===this.ary?"":this.ary}(${this.rows}×${this.rows}) != ${e.length}`)}index(e,t){return this.ary*(t+e*this.rows)}swap(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const r=i(77598),s=i(65713);function n(){const e=(0,r.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=n,t.safeUUID=function(){return(0,s.decuss)(n)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,r=0;for(const s of e){if(null!=s){const e=t(s,i);(0,u.isNumber)(e)&&(r+=e)}i++}return r}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){r.set(this,0),s.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,s,null==n(this,s,"f")?e:n(this,s,"f")*n(this,r,"f")/(n(this,r,"f")+1)+e/(n(this,r,"f")+1),"f"),a(this,r,(t=n(this,r,"f"),++t),"f"))}get mean(){return n(this,s,"f")}}function b(e){const t=new w;for(const i of e)t.push(i);return t.mean}function S(e){const t=b(e);if(null==t)return;let i=0,r=0;for(const s of e)(0,u.isNumber)(s)&&(r++,i+=(s-t)*(s-t));return i/r}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function _(e,t){let i=0;for(let r=0;r(1-t)*e+t*(i+a*(e-s)/n)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=b(t);if(null!=i){const e=(t.length-1)/2,r=v(t,((t,r)=>(t-i)*(r-e))),s=v(t,(e=>(e-i)**2));return 0===s?0:r/s}},t.variance=S,t.stdDev=function(e){return(0,l.map)(S(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const r of e)i=null==i?r:i*t+r*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let r=0;re[r]))));return i},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const r=i(38522),s=i(22573),n=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,s.mapNotBlank)(e,(e=>(0,s.mapNotBlank)(t,(t=>(0,n.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},39471:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableServer=void 0;const r=i(27395),s=i(25764),n=i(36868);t.EndableServer=class{constructor(e,t){this.name=e,this.server=t,this._ended=!1,(0,r.addEndable)(s.EndableRanks.service,this)}get ended(){return this._ended}end(){return this._ended=!0,(0,n.closeStream)(this.server)}}},49076:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const s=r(i(48161)),n=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,n.lazy)((()=>u.Settings.hostname.value??s.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??s.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},93756:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.request=void 0;const s=r(i(44708)),n=i(22573),a=i(55835),o=i(97352),l=i(57159),u=i(63870),c=i(43205);t.request=async function(e,t={}){return null==t.headers&&(t.headers={}),(0,n.blank)(t.headers["user-agent"])&&(t.headers["user-agent"]=await(0,c.userAgent)()),new Promise(((i,r)=>{const n=s.default.request(e.toString(),t);n.setTimeout((0,a.orElse)(t.timeout,(0,u.commandTimeoutMs)()),(()=>{r(new l.WrappedError("Timeout fetching <"+e+">",{doNotSend:!0,retriable:!0}))})),n.on("response",(e=>{const t=[];e.setEncoding("utf8"),e.on("data",(e=>t.push(e))),e.on("end",(()=>{i({ok:(0,o.within)(200,399,e.statusCode),headers:e.headers,body:t.join(""),statusCode:e.statusCode,statusMessage:e.statusMessage})}))})).on("error",(e=>{r(e)})),(0,a.map)(t.body,(e=>n.write(e))),n.end()}))}},43205:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemUserAgent=t.simpleUserAgent=t.userAgent=void 0;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c},72308:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLocalhost=t.isLoopback=t.myExternalIp4Addresses=t.myExternalIpAddresses=t.networkMacAddresses=t.myIpAddresses=void 0;const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter((e=>!g(e)))}t.myIpAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.address))))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)((()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map((e=>e.mac)))).filter((e=>"00:00:00:00:00:00"!==e))),o.minuteMs),t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter((e=>!e.includes(":")))};const m=(0,s.lazy)((()=>(0,d.mkLogger)("net.ip"))),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map((e=>(0,u.toInt)(e)));return 4!==t.length||t.some((e=>null==e||!(0,u.within)(0,255,e)))?void 0:t}(e)?.[0]||p.some((t=>null!=t.exec(e))))}t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})}},96128:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),b=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==b.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const S=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=S.exec(e)}function _(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=_,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,n.blank)(e)){if(null!=_(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void T().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const T=(0,s.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=_(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return T().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(T().warn("No name found for "+e),e):i}catch(t){return T().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,n.blank)(e)&&!(0,n.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(r.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,n.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,s.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)((()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(76760),s=i(19851),n=i(54993);t.isPacked=(0,s.lazy)((()=>!(0,n.toS)(__filename).includes((0,r.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)((()=>(0,s.mkLogger)("platform.Pacman")));t.hasPacman=(0,r.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(n.default.env.APPIMAGE)||(0,a.notBlank)(n.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(n.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(n.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,n.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,n.lazy)((()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const r=i(22573),s=i(51926),n=i(83556);t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const r=i(58587),s=i(59455),n=i(31562);t.existingPids=function(e){return(0,s.toA)(e).filter(r.pidExists)},t.waitForPidExit=function(e,t){return(0,n.untilTrue)((()=>!(0,r.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),b=i(54993),S=i(54557),P=i(19851),_=i(50213),T=i(88158),M=i(409),E=i(78406),k=i(25764),D=i(99331),x=i(56519),C=i(46292),A=i(8769),F=i(83278),I=i(32144),O=i(29882),L=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),j=10*p.secondMs;function z(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),r=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(r)&&Math.abs(i-r){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,O.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??L.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,f.isEmpty)(s))return B().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],o=await(0,N.pidInfos)(s);if(null!=o){for(const s of r){const r=await s.readJson();if(null==r){B().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const l=r.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:l}),await s.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!z(r,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,y.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:r}),a.push(W(l,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,A.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,s,"f").delete(l),o(this,s,"f").getOrSet(l,(async()=>{const i=o(this,r,"m",n).call(this,e.pid),s=(0,v.opt)((0,T.Try)((()=>(0,O.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:s,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,s,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,r,"m",n).call(this,e);return(0,x.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new E.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:k.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=U,s=new WeakMap,a=new WeakMap,r=new WeakSet,n=function(e){return this.pidsDir.join(e+".json")},U.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new U(F.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return U.instance()?.addPid_(e,t)}},58261:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const s=i(31421),n=i(48161),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),b=i(56519),S=i(84777),P=i(8103),_=i(45879),T=i(43334),M=i(24399),E=i(45643),k=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function x(e){if(T.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,_.readFileMaybe)("/proc/"+i+"/stat")));return k().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,E.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,T.isWin?I:N)).filter((e=>D(e)&&t.includes(e.pid)));return k().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=D,t.pidInfo=async function(e){return(0,b.thenMap)(x([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,b.thenMap)((0,E.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=x;const C="Get-Process",A="| Select-Object -Property Id,ProcessName,StartTime";function F(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(M.PowerShell.instance().ended)return R(e);const t=[C,"-Id",F(e),"-ErrorAction SilentlyContinue",A].join(" ");return(0,b.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const O={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},L=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",L.join(","));const i=await(0,S.stdoutResult_)((0,P.wmic)(),t,O),r=(0,d.onlyReqValued)((0,p.parseFixed)(L,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return r.find((e=>e.pid===a.default.pid))||r.push({pid:a.default.pid,start:new Date(v.StartTs),cmd:"node "+a.default.title}),r}async function N(e){return t=(await(0,S.stdoutResult_)("ps",["-p",F(e),"-wwwo","pid,lstart,command"],{...O,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(T.isLinux)return(0,c.toGt0)((0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){k().warn("clk_tck failed",{error:e})}return 100})),j=(0,g.lazy)((()=>Date.now()-(0,n.uptime)()*u.secondMs)),z=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=z.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),r=t?.comm,s=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(r)&&(0,c.gt0)(s)?{pid:i,cmd:r,start:new Date(j()+s/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const r=i(19851),s=i(42659),n=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,r.lazy)((()=>new o.TTLMap(15*s.secondMs))),t.recentDone=(0,r.lazy)((()=>new o.TTLMap(2*s.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,n.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,s=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:s,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s,this.start=Date.now(),this.onInterval=(0,n.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,s.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,s.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,r.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,s.emitProgressEvt)({...this.context,pct:(0,r.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),b=i(31562),S=i(84777),P=i(34102),_=i(43334),T=i(28874),M=i(63870),E="{ready}",k=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>x.instance.prior()?.clearMockResults()))));class x extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:()=>(0,S.execFile)("powershell",T.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(T.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:E,fail:"Error",exitCommand:"exit",maxProcs:T.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),T.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(T.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,k),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new r.Task(e,((i,r,s)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),r,s)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,k),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=x,x.instance=(0,s.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new x})),t.checkPowerShell_=async function(){const e=x.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const r=i(50989);t.AggregateTypes=(0,r.strEnum)("union","intersection")},71988:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map((t=>(0,s.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||(0,r.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:(0,r.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(70488),s=i(91655),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration})}get valueOrDefault(){return(0,r.decodeDuration)(super.valueOrDefault)}get value(){return(0,r.decodeDuration)(super.value)}set value(e){super.userValue=(0,r.decodeDuration)(e)}get humanValue(){return(0,s.fmtFullDuration)(this.value)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,r.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:r.encodeDuration,fromEnv:r.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,r.decodeDuration)(this.defaultValue)}get fileValue(){return(0,r.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874),l=(0,n.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,s.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,s.pick)(e??{},"retries","halt","path"),...(0,s.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},86941:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAndArchiveSystemSettingsDir_=t.mergeUserDataDirs_=void 0;const r=i(19851),s=i(59455),n=i(72993),a=i(46292),o=i(95696),l=i(50213),u=i(83179),c=i(28874),d=i(2858),h=i(84438),f=(0,r.lazy)((()=>(0,l.mkLogger)("settings.MergeConfigDirs")));async function m(e,t){let i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+e.baseWithGrandparent+" => "+t.baseWithGrandparent+")");const r=await e.resolve_(),n=await t.resolve_();if(null==r||null==n||n.nativePath===r.nativePath)return void i.info("no-op, missing or same directory",{priorResolvedConfigDir:r?.nativePath,currentResolvedConfigDir:n?.nativePath});if(i=(0,l.mkLogger)("mergeAndArchiveSystemSettingsDir_("+r.baseWithGrandparent+" => "+n.baseWithGrandparent+")"),!await r.isDirectory())return void i.info("no-op, prior directory doesn't exist");{const e=r.join(h.SettingsToml);if(await e.isNonEmptyFile()){const t=n.join(h.SettingsToml);await(0,d.readSystemSettings)(e),i.info("read prior settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.readSystemSettings)(t),i.info("read current settings.toml",(0,u.settingsToObj)((0,c.persistedSystemSettings)())),await(0,d.writeSystemSettings_)(t)}}{const e=r.join("licenses"),t=n.join("licenses");for(const r of(0,s.toA)(await e.childFiles())){const e=t.join(r.base);if(await e.notExists())try{await r.copyFile_(e),i.info("Copied license "+r.base)}catch(e){i.warn("Failed to copy license "+r.base,e)}}}const a=n.join("old");try{const e=await r.renameYMDHMS_({subdir:a.nativePath});i.info("merged and archived to "+e)}catch(e){i.warn("Failed to archive to "+a,e)}}t.mergeUserDataDirs_=async function(){const e=(0,a.configDir)();if(null==e)return;const t=o.PosixFile.for(e);for(const e of[t.join((0,n.AppName)()),t.join((0,n.AppName)().toLowerCase()),t.parent().join((0,n.AppName)().toLowerCase())])try{await m(e,t)}catch(i){f().error("Failed to merge "+e+" and "+t,i)}f().info("done")},t.mergeAndArchiveSystemSettingsDir_=m},4175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const r=i(19851),s=i(22573),n=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,r.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){_(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&T()},t.handleDeprecatedSettings=async function(){if((0,n.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,s.blank)(m.Settings.assetPathnameFormat.value)&&(0,s.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const b=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],S={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function _(e){for(const t of b)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:S;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function T(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=_,t.disableExternalNetworkRequests=T},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const r=i(22573),s=i(53265),n=i(87652);class a extends n.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,r.blank)(e)?void 0:(0,s.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},4936:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathToLibraryAsset=void 0;const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(55835),l=i(51926),u=i(50213),c=i(81168),d=i(79842),h=i(21330),f=i(51275),m=i(29882),p=i(28874),g=(0,s.lazy)((()=>(0,u.mkLogger)("settings.PathToLibraryAsset")));function y(e){return(0,a.blank)(e)?"":"'"+e.replace(/'/g,"′")+"'"}t.pathToLibraryAsset=function(e,t){const i=(0,d.datedToDateTime)(e)??(0,o.map)((0,h.datedToISO)(e),(e=>r.DateTime.fromISO(e)));if(null==i||!i.isValid)return g().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:i}});const s=(0,f.hasZone)(e),a=p.Settings.assetPathnameFormat.valueOrDefault,u=(0,c.splitKeep)(a,/((?:GRAND)?PARENT|BASE|NAME|EXT|ISO)/g);for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const r=i(51926),s=i(83556);t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),b=i(44198),S=i(96706),P=i(34102),_=i(28283),T=i(81075),M=i(98778),E=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){r.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?n(this,r,"m",s).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?n(this,r,"m",s).call(this,e??t)+": "+i:null==this.fromEnv(e)?n(this,r,"m",s).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,S.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,b.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return T.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,b.env)(),r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),null==e&&S.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,b.env)(),r=this.toEnvValue(t);return null!=r&&(i[this.key]=r,null==e&&S.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,S.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],E.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],E.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const r=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+r],E.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:E.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},r=new WeakSet,s=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const r=i(58587),s=i(51168),n=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),b=i(7282),S=i(12801),P=i(4328),_=i(70488),T=i(84248),M=i(5531),E=i(99315),k=i(34365),D=i(34580),x=i(96706),C=i(50274),A=i(33866),F=i(52086),I=i(48584),O=i(45969),L=i(43334),R=i(24540),N=i(70379),B=i(71300),j=i(33209),z=i(48987),V=i(68268),W=i(61208),U=i(99023),q=i(30577),H=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Y=i(71988),X=i(38483),Z=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),re=i(55948),se=i(57039),ne=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(b.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function be(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new X.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new X.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new X.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new se.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:be}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new X.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:be}),useFsWatch:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new se.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>H.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:H.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>H.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>L.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new se.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new X.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new X.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,O.isDocker)()}),cspReportOnly:new X.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new X.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new X.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!L.isElectron}),minDelayBetweenSpawnMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new se.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>L.isMac?"100ms":L.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new se.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new ne.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>S.PriorityClasses.BelowNormal,strEnum:S.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new X.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:T.AutoVacuumModes,defaultValue:T.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:k.SynchronousModes,defaultValue:k.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:E.RepairModes,defaultValue:E.RepairModes.dump}),maxBusyDbMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new se.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new Z.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new X.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new X.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,O.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:A.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new X.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new X.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>L.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new X.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:q.UpdateChannels}),autoUpdateCheck:new X.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new X.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new X.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new X.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new X.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new X.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new X.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new X.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":s.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new X.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new X.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new ne.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:re.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new X.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new X.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:F.CropStrategies.attention,strEnum:F.CropStrategies}),videoFrameAtSec:new ne.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new X.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(L.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new X.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new Z.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new X.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>j.DefaultIncludedPreviewTags}),disableAllFilters:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new X.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>z.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new se.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new ne.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new X.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new ne.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:U.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,O.isDocker)()}),tagDisplayNameFSLabels:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new se.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new X.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new X.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function Se(e){const i=((0,u.blank)(e)?"":e).split(n.delimiter);return(0,O.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(n.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=Se,t.pathWithDefaults=(0,a.lazy)((()=>Se((0,x.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(31586),n=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,r.lazy)((()=>{w.Settings.configDir.opts.defaultValue=o.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,n.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,n.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,s.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),b=i(81168),S=i(83556),P=i(87290),_=i(98314),T=i(34102),M=i(83278),E=i(95696),k=i(60865),D=i(4175),x=i(83179),C=i(81075),A=i(28874),F=i(41692),I=i(84438),O=i(32707),L=i(6707),R=i(98778),N=i(55018),B=i(10357),j=(0,r.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function z(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,O.systemSettingsFile)()){if(null!=e)return Z(M.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,L.readTomlFile_)((0,O.systemSettingsFile)()))?.[A.Settings.libraryDir.name])}catch{return}}function U(e){return(0,L.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function q(){return U((0,O.systemSettingsFile)())}function H(e){return U(z(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=z(e);return j().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:A.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void j().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==s&&(s=t,r.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,T.ee)().emitDebounced("settingsChanged")}(s,i),j().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,x.settingsToObj)(i),wip:r}),r){const t=await(0,L.readTomlFile_)(s),i=await(0,L.readTomlFile_)(e);(0,u.eql)(t,i)?(j().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(j().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function K(e=(0,O.systemSettingsFile)()){const t=E.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,A.persistedSystemSettings)()),t}function Y(e){return Z(z(e))}async function X(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,A.Settings.libraryDir.value));const i=z(e);return j().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,A.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Z(e){if(null==e)return[];const t=j().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,s.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,_.errorToS)(e)),[]}}async function Q(e){const t=j().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const r=await(0,L.readTomlFile_)(e);if(null==r)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,s.compact)((0,p.entries)(r).map((([e,t])=>{if("version"===e)return;const i=(0,A.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,A.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}})));return t.info("loaded",{settings:(0,x.settingsToObj)(a),warnings:(0,s.toNotEmpty)(n)}),await(0,D.handleDeprecatedSettings)(),(0,D.handleMetaSettings)(a),{settings:a,warnings:n}}t.librarySettingsFile=z,t.readSettings=(0,r.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Y()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return A.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=q,t.librarySettingsVersion=H,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await q()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await H()&&await X()},t.libraryHasSettings=(0,r.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{j().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,T.ee)().on("clearCache",G),(0,T.ee)().on("settingsChanged",G),A.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,r.lazy)((()=>(0,k.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(E.PosixFile.for(e),(0,A.persistedSettings)())},t.readLibrarySettings=Y,t.writeLibrarySettings_=X,t._readSettings=Z,t.importFileSettings_=Q;const ee=(0,r.lazy)((()=>new Set([A.Settings.noNetwork,A.Settings.httpPort,A.Settings.license,A.Settings.logStdout,A.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(A.Settings))ee().has(e.key)||e.unset();(0,T.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,b.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),A.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(E.PosixFile.forMaybe((0,O.systemSettingsFile)())?.unlink("trace")),await(E.PosixFile.forMaybe(z())?.unlink("trace")),(0,T.ee)().emit("clearCache"),F.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${k.versionMajorMinor}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,n.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,n.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let r="";t.forEach((e=>{const t=`${(0,b.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const n=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,s.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,b.capitalize)((0,S.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,s.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",n.length),n,(0,g.padding)("-",n.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=s},72564:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,n.map)(e,(e=>(0,s.stringify)((0,r.uniq)(e)))),fromEnv:t=>function(e,t){return(0,r.compact)((0,a.splitStringArray)(e)?.map((e=>t.getCI(e))))}(t,e.strEnum),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const r=i(76760),s=i(55835),n=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,s.map)((0,n.configDir)(),(e=>(0,r.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},6707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const r=i(90858),s=i(44652),n=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,n.blank)(t)?void 0:(0,r.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,n.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,s.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,n.mapNotBlank)(e,(async e=>f(await(0,s.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,s.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const r=i(98553);t.valueToS=function(e){return(0,r.stringify)(e,void 0,2)}},63225:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=void 0;const r=i(68708),s=i(81168),n=i(44198),a=i(59958),o=i(28874);t.verifyPsEnvSettings=function(e=(0,n.env)(),t=.25){const i=[];for(const n of(0,r.keys)(e).filter((e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!a.IgnorableEnvKeys.includes(t)}))){const r=e[n],a=(0,o.ciSettings)().lookup(n);if(null!=a){const e=a.value.whyInvalidEnvValue(r);null!=e&&i.push({envKey:n,msg:e})}else{const e=(0,o.ciSettings)().lookupNearest(n,t);null==e?i.push({envKey:n,msg:`No setting was found like "${n}"`}):(0,s.equalsIgnoreCase)(e.key,n)||i.push({envKey:n,msg:`Did you mean setting "${e.value.key}"?`})}}return i}},10357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const r=i(54993),s=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const n=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,s.extractFloat)(e);if(null==t)return;const i=(0,r.toS)(e).toLowerCase();for(const e of n)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const r=i(4001),s=i(81168);t.bname=function(e,t=!0){let i=(0,s.isString)(e)?e:e.name;return t&&(i=(0,r.stripCopySuffixFromName)(i)),i=(0,s.trimLeftPadding)((0,r.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),v=i(81168),w=i(76596),b=i(79842),S=i(66649),P=i(21330),_=i(98725),T=i(928),M=i(54261),E=i(89724),k=i(17415),D=i(88600),x=i(51275),C=i(29882),A=i(17217),F=i(68284),I=i(57902),O=i(28874),L=i(65162),R=i(71300),N=i(14036),B=i(61424),j=(0,s.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function z(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,b.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=z,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class U{static fromAssetFile(e){return(0,d.map)((0,E.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>U.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof U?e:W(e)?new U(e):void 0}constructor(e){var t;this.nativePath=(0,A.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,E.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,b.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(O.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,S.datedToMillis)(e.mtime)??(0,F.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:U.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,_.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,k.fmtOffsetMinutes)});return null==t?void 0:new U({...e,date:t})}spread(e){return new U({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,k.fmtOffsetMinutes)(this.offset)}get isFromTags(){return z(this.src)}get isInferred(){return!z(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,E.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,w.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,x.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,M.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,T.getMillisecond)(this.date))}toMillis(){return(0,S.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,r.offsetMinutesToZoneName)(this.offset)??(0,x.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,k.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?O.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,b.datedToStartDateTime)(this.date)??(0,b.datedToDateTime)(this.date);if(null!=i)return{start:(0,E.datedToLocal)(i.minus(t)),end:(0,E.datedToLocal)(i.plus(t))};j().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:O.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return j().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,b.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}}function q(e,t){if(null==e)return;const i=(0,n.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>U.for(e))));for(const r of t){let t=e[r],s=r;if((0,D.isValidDate)(t)){if((0,k.isValidZone)(e.tz)&&(!(0,x.hasZone)(t)||R.OverrideUTCZoneTags.includes(s))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,v.stripPrefix)(e.tzSource,"from ");s+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,E.datedToLocalSec)(t),date:t,src:s,precisionMs:(0,b.datedToPrecisionMs)(t),rawValue:e[r]?.rawValue})}}const r=(0,p.leastBy)(i,(e=>(0,b.datedToStartTs)(e.date)));if(null==r)return;const s=i.filter((e=>(0,u.eql)(e.date,r.date)||e.precisionMs<=r.precisionMs&&(0,b.datedOverlap)({a:e.date,b:r.date,aPrecisionMs:e.precisionMs,bPrecisionMs:r.precisionMs}))),a=(0,p.leastBy)(s,(e=>[Math.floor(e.localSec/1e6),(0,x.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return j().debug("capturedAtFromTags()",{least:r,overlapsWithLeast:s,earliest:a}),a}function H(e,t){if(O.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,n.uniq)([(0,L.bname)(e,!0),(0,L.bname)(e,!1)])){const e=(0,_.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,b.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(O.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,_.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(O.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=U,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const r=await e.mtimeMs();function s(t,i){return W(i)?U.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?U.for({nativePath:e.nativePath,date:i.date,local:(0,E.datedToLocal)(i.date),src:(0,v.uniqPath)([t,i.src]),mtime:r,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const n=function(e,t){return null==e||t||!O.Settings.usePathsToInferDates.valueOrDefault||!O.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:O.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=s("tags",q(t,O.Settings.capturedAtTags.values))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??s("tags",q(t,O.Settings.capturedAtTagsFallback.values))??(n?void 0:s("stat+bname",await(0,B.extractStatBname)(e)))??(n?void 0:s("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:s("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(n?void 0:s("bname",H(e,t)))??(n?void 0:s("path",G(e)))??(O.Settings.useStatToInferDates.valueOrDefault?s("stat",await $(e)):void 0);return j().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return q(e,O.Settings.capturedAtTags.values)},t.capturedAtFromBasename=H,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(50989);t.DateTagFormats=(0,r.strEnum)("y","ym","ymd","")},71300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const r=i(31586),s=i(97352),n=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const s=i(77988),n=r(i(76760)),a=r(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),v=i(12168),w=i(56038),b=i(4867),S=i(36557),P=i(98247),_=i(21330),T=i(98725),M=i(23467),E=i(88561),k=i(95696),D=i(17217),x=i(16287),C=i(50213),A=i(17921),F=i(7282),I=i(88158),O=i(23560),L=i(28874),R=i(12089),N=i(81168),B=i(63870),j=i(15674),z=i(28544),V=i(43207),W=i(72180),U=i(75767),q=i(12788),H=i(80495),G=i(14036),$=i(67083),J=i(3432),K=i(28630),Y=i(15912),X=i(30748),Z=i(16170),Q=i(95141),ee=i(7330),te=i(54979),ie=i(1078),re=i(61424),se=i(8791),ne=(0,o.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return L.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new S.BatchClusterObserver("ExifTool",new s.ExifTool({useMWG:L.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:L.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,S.batchClusterOptions)((0,F.isTest)()?8:(0,O.isSyncService)()?L.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,b.thenOrTimeoutError)({p:le().version(),timeoutMs:L.Settings.statTimeoutMs.valueOrDefault})},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,b.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,B.commandTimeoutMs)()})))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new E.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return L.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,N.includesIgnoreCase)(L.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ne().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,te.readMimeType)(e),s=await e.sidecar(),n=(0,Z.isImageMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Z.isVideoMimeType)(r)&&L.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=L.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return ne().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const r=k.PosixFile.for(e);if(r.isSidecar()&&(i=!1),!await r.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(r.nativePath),void ne().debug("readRawTags("+r+"): invalid file, returning null.");const s=await(0,t._readRawTags)(r.nativePath);if(null==s||!i)return s;ne().trace("readRawTags()",{pf:r,pickedFileTags:(0,f.pick)(s,"tz","tzSource",...L.Settings.capturedAtTags.values)});const n=[];for(const e of await r.jsonSidecars())n.push([e,(0,K.readJsonSidecar)(e,s.tz)]);for(const e of await r.existingExifSidecars())n.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(s.MIMEType,Z.normalizeMimetype),...s},o=[];for(const[e,i]of n){if(null==i)continue;const r=await i;if(null==r)continue;const s=(0,f.omit)(r,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(s))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(r.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(s))),(0,f.assignFields)(a,s),ne().debug("readRawTags() sidecar had values",{sidecar:e.base})):ne().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),ne().debug("readRawTags() final",{pf:r,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...L.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,r=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Z.normalizeMimetype);if((0,u.blank)(r))return void ne().debug("No mimetype for "+i);const n={...t.inferred??{},...t};if(n.inferred??(n.inferred={}),n.original??(n.original={}),L.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values]){const t=n[e];if((0,p.isString)(t)){const i=(0,T.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ne().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),n[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,n,o);if(ne().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=n.tzSource!==s.defaultVideosToUTC&&void 0;for(const t of[...L.Settings.capturedAtTags.values,...L.Settings.capturedAtTagsFallback.values])if(!(0,W.isUtcTagName)(t)){const i=n[t];i instanceof s.ExifDateTime&&(n[t]=(0,_.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(n.original,n,"tz","tzSource"),(0,f.assignFields)(n,l)}const c=o?(0,X.extractMakeAndModel)(n):await(0,re.inferMakeAndModel)(e,n);c.Make!==(0,X.make)(n.Make)&&(n.original.Make=n.Make,n.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,n.Model)&&(n.original.Model=n.Model,n.inferred.Model=c.Model),!(0,u.blank)(L.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(n.Copyright)&&(n.Copyright=L.Settings.defaultCopyright.valueOrDefault);const d=(0,Y.extractLensMakeModel)(n),h=await(0,z.extractCapturedAt)(e,n,o);if(null==h)return void ne().info("No capturedAt for "+e);!o&&h.isInferred&&(n.inferred.capturedAt=h);const m=(0,H.extractExposureSettings)(n),g=await(0,ie.extractSizeInfoFromFile)(e,n);if(null==g)return void ne().info("No size info for "+i);const y={...c,mimetype:r,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(n),...d,cameraId:(0,U.cameraIdFromTags)(n),imageId:(0,U.imageIdFromTags)(n),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(n,"LensSerialNumber")}),...g,duration:(0,V.extractDurationSec)(n),tz:n.tz,rating:(0,ee.extractRating)(n)};(0,F.isTest)()&&(y.__parsedBy__=a.default.pid);const v={...n,...y};return ne().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:n.inferred,original:n.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ne().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,M.eqlAsync)(e.sha(),t.sha())||await(0,M.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=k.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ne().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("exiftool.overwriteTags:"+e,(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){ne().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("exiftool.writeTags:"+e,(async()=>{const r=new h.MultiMap;for(const[s,n]of(0,f.entries)(t)){const t=await me(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=k.PosixFile.for(t),s=(0,f.fromEntries)(i);ne().info("writeTags()",{src:e,dest:t,t:s}),await le().write(r.nativePath,s,await fe(r)),L.Settings.overwriteOriginal.valueOrDefault||await he(r),r.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,x.nativePathIsFile)(e))return ne().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ne().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...L.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,G.isVideoExt)(n.default.extname(e))?[]:["-fast"]],r=await(0,w.time)("exiftool.read()",(()=>le().read(e,i).catch((t=>{ne().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==r)return;ne().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(r,"tz","tzSource",...L.Settings.capturedAtTags.values)}),r.MIMEType=(0,u.mapNotBlank)(r.MIMEType,Z.normalizeMimetype),r.GPSDateTime??(r.GPSDateTime=(0,P.concatDateTime)(r.GPSDateStamp,r.GPSTimeStamp));for(const e of(0,f.keys)(r)){const t=r[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete r[e])}const s=(0,l.compactBlanks)([r.Error,...r.errors??[],r.Warning].map(y.toS));return(0,l.isNotEmpty)(s)&&(r.problems=s),ae&&(r.__instance=(0,A.safeUUID)()),r}}),t.parseTags=ge},75767:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function b(e){const t=null==e?[]:e.filter((([,e])=>!(0,n.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function S(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,r=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(s=e[a])||(0,n.blankish)(s)||(0,l.isNumber)(s)&&(0===s||1===s)||null!=t.zeroesRe.exec((0,h.toS)(s)))continue;const o=e[a],u=S(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}r.push([a,(0,l.gt0)(o)?o:u])}var s;return b(r)}function _(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function T(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([_(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(_)):(0,u.compactBlankValues)(t)}function M({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==n||null==a||(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function E(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,r.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const r of t)e.set(r,i)}return e})),t.Tag2Synonyms=(0,r.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=b,t.renderExifUidId=P,t.decodeExifUid=T,t.findInequalFields=function(e,i){const r=T(e),n=T(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=r[e],i=n[e];if(S(t)!==S(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,s.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>M({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>M({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>M({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>M({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return E({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=E,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,n.toInt)(e)));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const r=i(19851),s=i(40958),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,r.lazy)((()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e})),m=(0,r.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,r.lazy)((()=>(0,s.uniq)((0,n.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,r.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),r=(0,c.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(p(i)?.includes(r)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const r=i(22573),s=i(45599),n=i(68708),a=i(50213),o=(0,s.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,n.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:s}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,r.blank)(e[i])&&!(0,r.blank)(t[s])&&(t[i]=t[s]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,n.pick)(e,"Directory","FileName"));for(const t of(0,n.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),v=i(50213),w=i(81168),b=i(66649),S=i(17415),P=i(29882),_=i(95696),T=i(17217),M=i(28874),E=i(47783);function k(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=k,t.mkHistoryRecord=D,t.InferAction="infer";const x=(0,s.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function A(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function F(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,S.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,r){if(null==e||(0,o.blank)(e))return void x().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,T.toNativePath_)(e),a=await(0,E._readRawTags)(s),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...r??{}};if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void x().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});x().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=_.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>r.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=A(e);(0,o.blank)(r.nativePath)||(0,P.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:x().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=A,t.inferredToTags=F,t.ensureInferredHistoryRecords=async function(e,i,r){const s=k(t.Actions.infer,r),n=(M.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?F(r):void 0)??{};return M.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),x().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),I(i,s,n)},t.ensureHistoryRecords=I},3432:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const s=r(i(53705)),n=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),w=i(14245),b=i(61424),S=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,w.omitInvalidGeolocationTags)(t);{const e=_(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=T(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function _(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return S().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return S().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function T(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTags.values){const s=(0,u.toDated)(t[r]);if(null==s||(0,f.isValidDate)(s))continue;const n=Math.round(15*i.diff(s,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(n),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return S().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,c.datedToISO)(s),rawTzoffsetMinutes:n,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return S().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=_,t.inferTzOffsetMinutesFromFilename=T},28630:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=(0,p.normalizeZone)(e?.formatted),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??t??r.UnsetZone});if(!0===n?.isValid)return n}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,n.toNotBlank)(e.title),Description:(0,n.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,s.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function b(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(b)):w(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,n.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=b;const P=/^\(?none\)?$/i;function _(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function T(e){return Array.isArray(e)&&e.every(T)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(T))}function M(e){if(null==e)return[];if(Array.isArray(e)&&e.every(T))return(0,h.flatMap)(e,M);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,M).map((t=>[e.Keyword,...t]))}t.parseCategories=_,t.isKeywordStruct=T,t.parseKeywordStruct=M,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=_(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(T(i)?t.push(...M(i)):t.push(...Array.isArray(i)?i:b(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],b),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==b(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function b(e){if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=b,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,r.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??b(e.Software)??b(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function b(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=b;const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},38010:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=t.revisionToResourceEvent=t.resourceEventToRevision=t.isSetRevision=t.isPrimitiveRevision=t.isBaseRevision=void 0;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(50213),g=i(84885),y=i(66649),v=i(98725),w=(0,s.lazy)((()=>(0,p.mkLogger)("tags.MergedTags")));function b(e){return(0,u.isNumber)(e?.createdAt)&&(0,o.notBlank)(e?.field)}function S(e){return null==e?.op&&b(e)}function P(e){return e?.sourceIsPrimary??e?.shown??!1}function _(e){return e?.sourceModifiedTime??e?.mtime??0}t.isBaseRevision=b,t.isPrimitiveRevision=S,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&b(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return w().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,o.blank)(t))return w().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,o.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return w().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,y.datedToMillis)((0,v.parseDated)({input:e.When}));return null==r?w().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,o.blank)(e.Action)?w().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):w().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,g.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}},t.MergedTags=class{constructor(e){this.name=e,this.revisions=[],this.tags=[],this.logger=(0,p.mkLogger)(`MergedTags(${e})`)}addRevision(...e){this.revisions.push(...e)}addTag(...e){this.tags.push(...e),(0,a.sortBy)(this.tags,(e=>[!P(e),-_(e)]))}get(e){const t=(0,a.sortBy)(this.revisions.filter((t=>t.field===e)),(e=>e.createdAt)),i=this.tags.find((t=>null!=t[e]));let r=i?.[e];const s=[];var l;null!=r&&(0,o.mapNotBlank)((l=i,l?.SourceFile??l?.uri),(e=>s.push(e)));const u=t.every(S)&&this.tags.every((t=>!Array.isArray(t[e])));if(u){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{revision:i}):(r=i.newValue,s.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:s}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)s.push(`Revision@${i.createdAt}`),(0,n.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){s.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,n.remove)(e,t)}return{value:e,source:s}}}}},16170:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const r=i(22573),s=i(54993),n=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,s.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,s.toS)(e))},t.isImageMimeType=function(e){return(0,s.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("western","eastern")},66039:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderNameTag=t.parseName=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(75020),u=i(59455),c=i(50213),d=i(68852),h=i(81168),f=i(70417),m=i(28874),p=(0,r.lazy)((()=>(0,c.mkLogger)("tags.Names")));function g(e){return(0,d.matchQuotes)((0,d.escapeRegExp)(e))}const y=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,v=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,w=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,b=/^[()[\]/.\-_]+$/;function S(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,o.map)((0,h.spliceCapture)(t,y),(e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,"")))),r=(0,o.map)((0,h.spliceCapture)(t,v),(e=>(t=e.unmatched.trim(),e.captured.trim()))),l=[],c=[],b=[];for(const e of m.Settings.tagNamesGiven.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(l.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`(${(0,d.escapeRegExp)(e.charAt(0))}\\s*[^${(0,d.escapeRegExp)(e.charAt(0))}]+\\s*${(0,d.escapeRegExp)(e.charAt(1))})`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(c.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let S;function _(e){(null==S||S>e.matchedIndex)&&(S=(0,f.min)([S,e.matchedIndex]))}if(m.Settings.tagNamesCapitalizedAsFamily.valueOrDefault){let e;do{e=(0,h.spliceCapture)(t,w),null!=e&&(_(e),b.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(m.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&p().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map((e=>new RegExp(`${(0,d.escapeRegExp)(e.charAt(0))}\\s*([^${(0,d.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,d.escapeRegExp)(e.charAt(1))}`,"i")))}()){let i;do{i=(0,h.spliceCapture)(t,e),null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(m.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(S=void 0,b.push(t.substring(0,e).trim()),l.push(t.substring(e+1).trim()),t="")}for(const e of m.Settings.tagNamesSurnames.values.map((e=>new RegExp("\\b("+g(e)+")\\b","i")))){const i=(0,h.spliceCapture)(t,e);null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}for(const e of(0,u.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(m.Settings.tagNamesSurnamePrefixes.values),(e=>(0,n.sortBy)(e,(e=>-e.length)).map((e=>new RegExp(`\\b(${g(e)}\\s+\\S+)`,"i"))))))){const i=(0,h.spliceCapture)(t,e);null!=i&&(_(i),b.push(i.captured),t=i.unmatched.trim())}null!=S&&t.length>S&&(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(S).split(/\s+/)),(e=>{b.push(...e),t=t.slice(0,S)}));const T=(0,s.compactBlanks)(t.split(/\s+/)),M=l.length,E=b.length;if(T.length>0)if(0===M&&E>0)l.push(...T);else if(0===E&&M>0&&1===T.length)b.push(...T);else if(1===T.length)l.push(...T);else{const e="western"===m.Settings.tagNamesOrder.valueOrDefault;b.push(e?T.pop():T.shift()),l.push(...T)}return{givenNames:P([...l,...c]),modifier:r,lifespan:i,familyNames:P(b),minFamilyNameIndex:S}}function P(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter((e=>null==b.exec(e))))}function _(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function T(e,t,i){return _("western"===m.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}t.parseName=S,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=m.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=S(e);if(null==t)return[];{const e=_([t.modifier,t.lifespan]),r=_(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[m.Settings.tagNamesDefaultFamily.valueOrDefault])).map((t=>[l.TagRoots.Who,t,i?_([r,e]):T(t,r,e)]))}}return[[l.TagRoots.Who,e.trim()]]}},95141:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const r=i(21605),s=i(54993),n=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,n.isVideoMimeType)(e.MIMEType)?(0,r.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,r.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,s.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,r.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,r.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,r.map)(e?.favorited,(e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const r=i(19851),s=i(22573),n=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,r.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,s.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,n.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const r=i(16928),s=i(40958),n=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,s.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const r=(0,a.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=s(e.slice(r.length)),l=s(i.slice(r.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const r=i(19851),s=i(22573),n=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),v=(0,r.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,r.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:n.minuteMs})));async function b(e,t){if(null==e)return;const i=null==t||(0,s.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const r=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return S(i,r,await(0,h.rawInfo)(e));const n=S(i,r);if(null!=n)return n;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await b(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function S(e,t,i){t??(t=(0,y.extractRotation)(e));const r=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==r)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:r}});const s=(0,a.maybeDimSwap)(r,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,d.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>b(i,t)))},t.extractSizeInfoFromTags=S},3127:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tag_fts_path=t.tag_fts_root=void 0;const r=i(54993),s=i(42231);t.tag_fts_root=function(e){const t=(0,r.toS)(e).indexOf(s.TagSep);return-1===t?"":e.substring(0,t)},t.tag_fts_path=function(e){return(0,r.toS)(e).split(s.TagSep).filter((e=>null!=e&&""!==e.trim())).join(" ")}},61424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),v=i(79842),w=i(21330),b=i(98725),S=i(51275),P=i(35280),_=i(19748),T=i(88561),M=i(95696),E=i(65238),k=i(17217),D=i(57902),x=i(28874),C=i(80496),A=i(65162),F=i(28544),I=i(47783),O=i(88840),L=i(30748),R=i(16170),N=(0,n.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function j(e){return x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+x.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(x.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,E.isSlowDir)(e.nativePath)&&!await(0,E.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function z(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of r){const r=(0,L.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(r.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:r});else if((0,f.definedAndNotEql)(r.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:r});else if(null!=r.Make&&null!=r.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:r,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await j(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,S.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,S.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,n.lazy)((()=>new T.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await H(e),i=await z(t?.younger),r=await z(t?.older);return null==i||null==r?void 0:{before:i,after:r,index:i.index,slots:i.index+r.index+1}}))}t.beforeAfterCapturedAt=W;const U=(0,_.extFilter)(O.ExtTypes.AssetFile);function q(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function H(e,t=7,i=!0){if(!await j(e.parent()))return;const r=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(U(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==r)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=(0,o.sortBy)(r,(e=>(0,A.bname)(e))),n=(0,k.findFileIndex)(e,s);if(n<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),H(e,t,!1)):void 0;const l=x.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[s.slice(n-2*t,n),s.slice(n+1,n+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=H,t.nearestSiblingTzOffset=async function(e){if(!await j(e.parent()))return;const t=q(await H(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==r.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)]),i=(0,b.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const r=await e.stat();if(null!=r){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:r[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:r}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:r}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,b.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const r=i[e];if(null!=r&&!0===(0,v.datedOverlap)({a:t,b:r}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:s.DateTime.fromJSDate(r)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function w(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),(e=>(0,r.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map((e=>y(e))));return(0,r.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,s.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const r=i(40958),s=i(22573),n=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,r.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,s.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,r.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function b(e){const t=await w(e);return(0,s.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function S(e,t){if((0,n.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,n.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=b,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(S(e,t),b))),(0,s.uniq)(i)},t.uri2nativePath=S,t.uriExists=async function(e,t){const i=await S(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const r=i(76760),s=i(57975),n=i(57160),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return M(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===r?r=this.path:null===r&&(r=g),void 0===s?s=this.query:null===s&&(s=g),void 0===n?n=this.fragment:null===n&&(n=g),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new S(t,i,r,s,n)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new S(g,g,g,g,g);const r=i[2]||g,s=x(i[4]||g),n=(i[5]||g).split("/").map(x).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=x(i[9]||g);return new S(r,s,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new S("file",t,e,g,g)}static from(e){return new S(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(r.win32.join(M(e,!0),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return E(this,e)}toJSON(){return this}[s.inspect.custom](){return this.toString()}}t.URI=w;const b=h.isWinPortable?1:void 0;class S extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=M(this,!1)),this._fsPath}toString(e=!1){return e?E(this,!0):(null==this._formatted&&(this._formatted=E(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=b),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function _(e,t){let i,r=-1;for(let s=0;s=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.substr(0,s));const t=P[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function T(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function E(e,t){const i=t?T:_;let r="";const{scheme:s,query:n,fragment:o}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=y,r+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.substr(0,e),!1),r+=":",r+=i(t.substr(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.substr(0,e),!1),r+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}r+=i(u,!0)}return(0,a.mapNotBlank)(n,(e=>r+="?"+e)),o&&(r+="#",r+=t?o:_(o,!1)),r}function k(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+k(e.substr(3)):e}}t.encodeURIComponentFast=_,t.uriToFsPath=M;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function x(e){return e.startsWith("xn--")?(0,n.toUnicode)(e):e.match(D)?e.replace(D,(e=>k(e))):e}t.percentDecode=x,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const r=i(19851),s=i(40958),n=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,r.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),r=(0,c.toURI)(t);return i.scheme===r.scheme&&i.authority===r.authority&&f(i.path,r.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,n.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,s.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const r=i(76760),s=i(22573),n=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,r.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,s.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,s.blank)(t.uuid))return;const i=(0,l.native2posix)(e),r=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(r.normalize()))return;const u=(0,n.ensurePrefix)(i.slice(r.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,s.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?r.win32.sep:r.posix.sep,n=(0,s.notBlank)(t)&&!t.includes(i);if(n&&!(0,s.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):n&&(0,s.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,s.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,s.blank)(t))return;const i=(0,r.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,n.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,n.stripPrefix)(e.path,"/"),r=t.join(i);if(r.isFileSync())return r.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return r.nativePath}},12228:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=n(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),r=i[0];if((0,o.blank)(r))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const s=i.slice(1),n=await(0,p.volumes)();for(const t of(0,u.toA)(n))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,r)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...s);return await(0,h.isReadableDirectory)(t)?a.join(t,...s):void 0}},85087:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(9103),a=i(37628);t.volsha=(0,n.memoize)((e=>(0,r.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:s.minuteMs})},50036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=void 0;const r=i(46292),s=i(95696);t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")}},60865:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const r=i(37805),s=i(30577);t.channel=function(){return(0,s.extractUpdateChannel)(r.version)},t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const r=i(38064),s=i(22573),n=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof r.SemVer)return e.version;const t=n.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,s.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,r.satisfies)(e,t,i))return!0;const n=a(e);return null!=n&&(0,r.satisfies)(n,t,i)},t.toSemver=function(e){try{return e instanceof r.SemVer?e:(0,r.parse)(e,{loose:!0})??void 0}catch{return}}},27274:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.semverGte=t.semverLatest=void 0;const r=i(54993),s=i(48884),n=i(76280),a=i(30577);function o(e){const t=(0,n.toSemver)(e),i=a.UpdateChannels.ordinal((0,a.extractUpdateChannel)((0,r.toS)(e)));return null==t?void 0:[t.major,t.minor,t.patch,i,...t.prerelease.slice(1)]}function l(...e){return(0,s.greatestBy)(e,o)}t.semverLatest=l,t.semverGte=function(e,t){return l(e,t)===e}},38244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUpdateChannelVersion=void 0;const r=i(68708),s=i(51926),n=i(30577);t.isUpdateChannelVersion=function(e){return(0,r.isObject)(e)&&n.UpdateChannels.has(e.channel)&&(0,s.isString)(e.version)}},30577:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const r=i(50989);t.UpdateChannels=(0,r.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},63335:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=void 0;const r=i(22573);t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v|ver|version)?\s*/,"version ")}},40044:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=t.checkVersion_=t.currentChannel=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(75240),l=i(17344),u=i(50213),c=i(37805),d=i(5916),h=i(46292),f=i(16287),m=i(43205),p=i(28874),g=i(63870),y=i(89372),v=i(50036),w=i(60865),b=i(27274),S=i(38244),P=i(30577),_=i(63335),T=(0,a.defer)((()=>(0,u.mkLogger)("VersionCheck")));t.currentChannel=function(){const e=[p.Settings.updateChannel.valueOrDefault,(0,w.channel)()].map((e=>P.UpdateChannels.ordinal(e))).sort()[0];return P.UpdateChannels.values[e]??p.Settings.updateChannel.valueOrDefault},t.checkVersion_=async function(e){if(p.Settings.noNetwork.valueOrDefault)return{level:"disabled",msg:["PhotoStructure version checking is disabled","Set "+(0,s.tt)(p.Settings.noNetwork.toEnvLine(!1))+" to enable."]};if(!p.Settings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===p.Settings.optOut.value?e.push("Set "+(0,s.tt)(p.Settings.optOut.toEnvLine(!1))+" to enable."):!1===p.Settings.autoUpdateCheck.value?e.push("Set "+(0,s.tt)(p.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.tt)(p.Settings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,h.configDir)();if(null==i||!await(0,f.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const u=e?.installedVersion??c.version,d=(0,P.extractUpdateChannel)(u),m=(0,P.eligibleForChannel)(d),g=a.versions.filter((e=>m.includes(e.channel))).map((e=>e.version)),y=e?.latestVersion??(0,b.semverLatest)(...g);if(null==y)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+p.Settings.updateChannel.toEnvLine()]};const v=(0,P.extractUpdateChannel)(y),w="You are running "+(0,l.EditionName)()+" "+(0,_.ver)(u),S="The latest published "+(0,s.tt)(v)+" build is "+(0,_.ver)(y),T=v===d?void 0:"You should consider switching to the "+(0,s.tt)(v)+" channel.",M=Date.now()-a.updatedAt,E="Last checked "+(M{const e=(0,v.channelVersionsCache)(),i=await(0,y.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",headers:{"User-Agent":await(0,m.userAgent)()},cache:e,ttlMs:n.dayMs,preCacheTransform:e=>({versions:e,updatedAt:Date.now(),updatedByVersion:c.version})}),r=i.data;if(null==r||!Array.isArray(r.versions)||0===r.versions.length||r.versions.some((e=>!(0,S.isUpdateChannelVersion)(e)))||r.updatedByVersion!==c.version){if(i.fromCache)return T().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();T().throw("getChannelVersions_(): Invalid response",{result:r})}return T().tap({msg:"getChannelVersions_()",result:r})}})},8540:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const r=i(40958),s=i(9595),n=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,r.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,s.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,n.pathIsRoot)(t))&&(0,n.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},42233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.currentVolumeRoots=void 0;const r=i(45200),s=i(98770),n=i(7014);t.currentVolumeRoots=(0,s.lazyFsAsync)("currentVolumeRoots",(async function(){const e=[],t=[];for(const i of await(0,n.volumes)()){t.push(i.mountpoint);const s=(await(0,r.nativePath2uri)(i.mountpoint,i))?.toString();null!=s&&e.push(s)}return{uris:e,mountpoints:t}}))},1485:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const r=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,r.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const r=i(19851),s=i(22573),n=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),r=(0,g.isExcludedMountpoint)(e.mountpoint),s=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),n=t&&(i||r||s);return y().tap({msg:"acceptPosixVolume()",result:!n,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:r,excludedDir:s}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,n.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,s.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,n.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,s.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],r=m(e["1024-blocks"])??0;if(0===r)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const s=m(e.Used)??0,n=m(e.Available)??0;if(0!==s||0!==n)return{filesystem:t,mountpoint:i,size:d.isMac?s+n:r,used:s,available:n};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:r,used:s,available:n})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const r=["-k","-P"];if(!0===e&&r.push("-l"),r.push(...(0,s.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",r,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,n.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),b=i(24541),S=i(60224),P=i(63870),_=(0,r.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const T=/([a-z]+)(?::\\)?/i;function M(e){return e?.match(T)?.[1]?.toUpperCase()}function E(e){return(0,l.map)(M(e),(e=>e+":\\"))}function k(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(M(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,S.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function x(e){return`Get-Volume ${(0,f.toS)(M(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=E,t.getPsDriveCommand=k,t.getVolumeCommand=x,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(x())};const C=/\{([-a-z\d]{7,})\}/i;function A(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function F(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void _().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=E(e.DriveLetter);if(null==t)return void _().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,s.compact)([A(e.HealthStatus,"healthy"),A(e.OperationalStatus,"OK")]).join("; "),r=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return _().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(n=e.UniqueId,_().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(n)),(e=>e[1])),meta:{s:n}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:r,status:i},meta:{input:e}});var n}async function I(){const e=(0,s.uniq)((0,h.toA)(await(0,b.mountpointsWin)()).map(E)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,s.compact)((0,o.flatten)(t).map(D)),r=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(x(e)).catch((t=>(_().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,s.compact)((0,o.flatten)(r).map(F)),l=(0,s.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,n.sort)((0,s.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));_().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=F,t.volumeInfoWin=I},68884:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),b=i(16287),S=i(45969),P=i(43334),_=i(69108),T=i(98770),M=i(44224),E=i(63870);t.isGioSupported=(0,r.lazy)((async()=>{if(!P.isLinux||(0,S.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,E.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const k=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,r.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?k().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,M.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),b.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):k().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,s.isEmpty)(e)?[]:(k().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,E.mountpointsTtlMs)(),f:async e=>{const t=await(0,_.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void k().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const r=await D(i.mountpoint);return null==r?i:{remote:!0,...i,...r}}}))},timeoutMs:(0,E.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,T.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,E.commandTimeoutMs)()})).split(/[\r\n]+/),r=(0,n.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(r,(e=>e.hostname)),remoteShare:(0,u.opt)(r).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(n.notBlank).get()}}catch(t){return void k().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const r=i(19851),s=i(5233),n=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,r.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,s.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,n.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),b=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>b().warn("lsblk failed",{error:e}))),r=await(0,t.localVolumes_blkid_)().catch((e=>b().warn("blkid failed",{error:e})));if(null==i&&null==r)return;const n=(0,c.sortIgnoreCase)((0,s.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of n){const s=e.find((e=>e.mountpoint===t)),n=i?.find((e=>e.mountpoint===t)),o={...s,...n},u=r?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];b().info("backfilling mountpoint",{info:n,vol:s,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const S=/lsblk from util-linux ([\d.]+)$/i,P=(0,r.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return S.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),_=(0,r.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await _()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,n.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),r=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=r?{used:i,available:r,size:i+r}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return b().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,n.toNotBlank)(e.PARTLABEL)??(0,n.toNotBlank)(e.LABEL),uuid:(0,n.toNotBlank)(e.PARTUUID)??(0,n.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const r=i(57272),s=i(19851),n=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,s.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,n.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),s=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of s)try{const t=(0,r.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const r=i(19851),s=i(40958),n=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),b=i(8769),S=i(34102),P=i(17217),_=i(16287),T=i(43334),M=i(28874),E=i(8540),k=i(68884),D=i(44224),x=i(24541),C=i(69375),A=i(63870),F=(0,r.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function O(e=(0,A.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function L(){I()}t.localMountpointSetup=(0,r.lazy)((async()=>{M.Settings.libraryDir.watchLater(I),M.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&M.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(T.isMac&&(e.info("Setting up Mac diskutil activity watcher"),O((0,A.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),T.isLinux){const i=(0,D.maybeWatchProcMounts)();await(0,k.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),O((0,A.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),O((0,A.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,r.lazy)((()=>{}));t.mountpoints_=(0,r.lazy)((async()=>{{const e=M.Settings.mountpoints.values;if((0,s.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",T.isWin?x.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,s.isEmpty)(e))return F().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,n.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,A.commandTimeoutMs)(),f:async e=>!(!(0,E.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||M.Settings.validateMountpoints.valueOrDefault&&!await(0,_.isReadableDirectory)(e)&&(F().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,r.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,b.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(T.isWin)return!1;const i=await(0,t.mountpoints)()??[],r=(0,P.toNativePath_)(e);return T.isMac?(0,m.includesIgnoreCase)(i,r):i.includes(r)},(0,o.later)((()=>{(0,S.ee)().on("clearCache",(()=>{k.gioVolumes.unset(),I()})),M.Settings.mountpointsTtlMs.watch(O)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>L(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:k.GioCommand,args:k.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(k.gioVolumes.unset(),L()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,r.lazy)((async()=>{if(!T.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,A.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,r.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>L(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const r=i(19851),s=i(40958),n=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),b=i(68884),S=i(59107),P=i(69375),_=(0,r.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await k()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,b.isGioSupported)())try{await(0,c.thenMap)((0,b.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){_().warn("Failed to fetch gio volumes",e)}return e};const T="/proc/mounts";function M(e){return!v.Settings.excludedFilesystemTypes.has(e)}function E(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function k(e=T,t=M,i=E){if(y.isLinux)try{const r=await(0,f.readLines_)(e),n=(0,s.compact)(r.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:n,f:async([e,r])=>{const s=t(e),n=await i(r);return _().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:s&&n,meta:{fs:e,mp:r,fsOK:s,mpOK:n}})}});return _().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void _().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=M,t.readProcMounts=k,t.maybeWatchProcMounts=(0,r.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(T)?new h.FileWatcher(T,{recursive:!1,persistent:!1},(()=>{_().info("detected change in "+T),(0,d.setUnrefTimeout)((()=>S.mountpoints.refresh()),n.secondMs)})):void 0))},24541:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const r=i(19851),s=i(42659),n=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,r.lazy)((async()=>{try{return await(0,n.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*s.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const r=i(19851),s=i(22573),n=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,r.lazy)((()=>(0,n.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,s.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,s.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],r=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(r)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const r=i(22573),s=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,n=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,r.blank)(e))return;const i=s.exec(e)?.groups;if(null!=i&&!(0,r.blank)(i.remoteHost)&&!(0,r.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(n,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,r.blank)(e)&&!(0,r.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const r=i(40958),s=i(22573),n=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await M()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],b=["NETUSE","get",w.join(",")],S=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function _(e){if(!(0,s.blank)(e))return(0,o.opt)(e).flatMap((e=>S.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,s.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(s.notBlank).getOrElse((()=>"/"))}))))).get()}async function T(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,b,{timeoutMs:15*n.secondMs}),i=(0,u.parseFixed)(w,t);return(0,r.compact)(i.map((e=>(0,a.map)(S.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=_,t._netInfoWinWmic=T;const M=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?T():(0,r.compact)(e.filter((e=>(0,s.notBlank)(e.LocalName))).map((e=>(0,a.map)(_(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(r=>({mountpoint:(0,h.ensureSuffix)(r[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const r=i(42659),s=i(12168),n=i(28874);t.mountpointsTtlMs=function(){return n.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return n.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=s.MiB/r.secondMs},86848:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),b=i(28874),S=i(59107),P=i(63870),_=i(68995),T=(0,s.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),M=(0,s.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function E(e){return(0,a.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,r.basename)(e.mountpoint)}function k(e){if((0,n.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=k(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function x(e){if(b.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of b.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),r=await D(i).catch((e=>T().info("Failed to read "+i,{error:e})));if(null!=r)return T().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountpoint}})}const t=(0,r.join)(e.mountpoint,(0,_.volumeUuidSubpath)());if("/"===e.mountpoint)return T().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(b.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return T().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(b.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,_.writeVolumeUuid)(e);if(!(0,n.blank)(t))return T().tap({msg:"readVolumeUUID(): wrote new "+(0,_.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return T().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>M.clear())),S.mountpoints.watchLater((()=>M.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(E(e))return;if((0,a.isFalse)(e.ok))return;const t=await M().getOrSetAsync(e.mountpoint,(async()=>x(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>T().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=E,t.toVolumeUUID=k,t.readUuidFile_=D,t.readVolumeUUID=x},7014:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),b=i(50213),S=i(7282),P=i(23560),_=i(28850),T=i(45255),M=i(81168),E=i(56519),k=i(4867),D=i(49776),x=i(9595),C=i(77740),A=i(44198),F=i(96706),I=i(8769),O=i(57159),L=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),j=i(17217),z=i(16287),V=i(49076),W=i(96128),U=i(45969),q=i(43334),H=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Y=i(27461),X=i(66840),Z=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),re=(0,a.lazy)((()=>(0,b.mkLogger)("volumes.Volumes"))),se=s.default.platform(),ne=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const r=i.get(e);null!=r&&(0,p.gt)(r.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,ne),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,x.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){re().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),ne.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,E.mapAsync)({name:"readCachedVolumes",arr:(0,E.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,M.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const r=Date.now(),s=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,U.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:r,os:se}))),n=new Map;for(const e of s)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))n.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:T.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of n.entries()){const r=e.join(t+".json");try{await r.writeJson_(i)}catch(e){re().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:r.nativePath,vol:i}),await r.unlink()}}}));re().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:s.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,Z.mountpoints)()),r=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,H.Settings.volumeMetadataTtlMs.valueOrDefault),s=0!==H.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,r))),n=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return re().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:s,priorIsMissingMountpoints:n}),s||n?void 0:e}async function me(e,i){const r=(0,m.map)(e,j.toNativePath_);if((0,u.blank)(r))return;const s=await(0,L.actualPath)(r);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(s,t.map((e=>e.mountpoint)));if(null==i)continue;const r=t.find((e=>e.mountpoint===i));if(null!=r)return re().trace("bestVolumeForPath()",{nativePath:s,result:r.mountpoint,src:e.name}),r}return re().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:s}})}async function pe(e,t,i){const r=i.filter((e=>(0,M.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(r))return;const s=r.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,M.equalsIgnoreCase)(e,t.remoteHost)));if(null!=s)return s;const n=await(0,W.friendlyname)(e);return(0,E.asyncFind)(r,(async e=>(0,M.equalsIgnoreCase)(n,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,S.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,v.toA)(await(0,Z.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),r=(0,o.isNotEmpty)(i)?i:e.filter((e=>se===e?.os));return re().tap({msg:"cachedVolumes()",level:"trace",result:r.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,k.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return re().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,k.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,O.toWrappedError)("volumes() failed",{cause:e}))}return re().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,_.shim0)({name:"fs.volumes",impl:async function(){if((0,S.isTest)()){const e=(0,p.toInt)((0,A.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(re().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void re().throw("PS_FAIL_VOLUMES")}const e=await(0,k.thenOrTimeoutError)({p:q.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void re().warn("df failed");const t=H.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,E.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,z.isReadableDirectory)(e.mountpoint))return e;re().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){re().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,k.thenOrTimeoutError)({p:q.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(q.isWin?t:q.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Y.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const r=(0,l.sortBy)(i,(e=>e.mountpoint));return re().debug("_volumes(): final result",{sorted:r}),r.forEach(ue),await he(r),Object.freeze(r)}}),t.rootPath=(0,a.lazy)((()=>q.isWin?(0,g.opt)((0,F.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,M.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(n.default.sep),t.split(n.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(re().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,E.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const r=i(76760),s=i(19851),n=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,s.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,n.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,r.join)(e,f());t=(0,n.toNotBlank)(t)??(0,c.safeUUID)();const s=(0,r.dirname)(i);if(await(0,l.isReadWriteableDirectory)(s))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},72901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkEventStream=void 0;const r=i(22573),s=i(98553),n=i(65211);t.mkEventStream=function(...e){let t="";for(const i of e)null!=i&&((0,r.blank)(i.event)||(t+="event: "+i.event+"\n"),t+="id: "+(i.id??(0,n.uid)())+"\n",t+="data: "+(0,s.stringify)(i.data)+"\n",t+="\n");return t}},55111:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},89372:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=void 0;const r=i(45599),s=i(98553),n=i(31586),a=i(50213),o=i(51140),l=i(4988),u=(0,r.defer)((()=>(0,a.mkLogger)("web.HttpGet")));t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,n.gt0)(await t.size())&&(0,n.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await(0,l.get_)(e.url,{headers:e.headers});o.HttpStatusIs.success(r.statusCode)||u().throw("Failed",{url:e.url,response:r});const a=(0,s.parseJSON_)(r.data),c=e.preCacheTransform?.(a)??a;return u().info("Fetch success. Caching",{args:e,json:c,cache:t}),await t.writeJson_(c),{data:c,updatedAt:Date.now(),fromCache:!1}}},49586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAjaxRequest=t.isHttpsRequest=t.parseForwarded=void 0;const r=i(22573),s=i(59455),n=i(81168),a=i(28874);function o(e){if((0,r.blank)(e))return{};let t=(0,s.toA)(e).join(";").trim().replace(/^[,;]/,"").replace(/[,;]$/,"");const i={};for(;t.length>0;){const e=t.indexOf("=");if(e<0)break;const r=(0,n.stripQuotes)(t.slice(0,e).trim().toLowerCase());if(t=t.slice(e+1).trim(),/^["']/.test(t)){const e=/['"]\s*(?:[;,]|$)/.exec(t.slice(1))?.index;if(null==e)break;const s=(0,n.stripQuotes)(t.slice(0,e+2).trim());i[r]=s,console.log("quoted",{k:r,v:s,s:t,vIdx:e}),t=t.slice(e+3).trim()}else{const e=/[;,]|$/.exec(t)?.index;if(null==e)break;const s=t.slice(0,e).trim();i[r]=s,console.log("unquoted",{k:r,v:s,s:t,vIdx:e}),t=t.slice(e+2).trim()}}return i}function l(e){return(0,r.blank)(e)||function(e){return Array.isArray(e)&&0===e.length}(e)?void 0:(0,s.toA)(e).join(";")}t.parseForwarded=o,t.isHttpsRequest=function(e){return null!=e&&"false"!==a.Settings.trustProxy.valueOrDefault&&((0,n.equalsIgnoreCase)("https",o(e.forwarded).proto??l(e["x-forwarded-protocol"])??l(e["x-url-scheme"]))||"on"===l(e["front-end-https"])||"on"===l(e["x-forwarded-ssl"]))},t.isAjaxRequest=function(e){return"application/json"===e?.["content-type"]}},51140:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},21404:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=void 0;const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238);t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])}},98604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkAssetUrl=t.mkFolderUrl=t.myWebUrl=void 0;const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(49076),l=i(72308),u=i(28874),c=i(42231),d=i(45200),h=i(34238),f=i(21404);function m(e=u.Settings.httpPort.valueOrDefault){const t=[u.Settings.localhost.valueOrDefault];u.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([(0,l.myExternalIp4Addresses)()[0],(0,o.hostname)()]));const i=(0,h.toURI)("http://a");return t.map((t=>i.with({authority:t+":"+e})))}t.default=m,t.myWebUrl=(0,r.lazy)((()=>m()[0])),t.mkFolderUrl=async function(e){const i=await(0,d.nativePath2uri)(e),r=(0,f.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,c.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0}},4988:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.httpRequest_=t.get_=t.HttpMethods=void 0;const a=n(i(37067)),o=n(i(44708)),l=i(22573),u=i(45599),c=i(50989),d=i(51926),h=i(50213),f=i(45255),m=i(22911),p=i(43205),g=i(34238),y=i(51140),v=(0,u.defer)((()=>(0,h.mkLogger)("net.get")));async function w(e,t){return b({...t,url:e})}async function b(e){const t=(0,g.toURI)(e.url),i=new m.Deferred("get "+t.toString()),r="http"===t.scheme?a.request:"https"===t.scheme?o.request:v().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??f.ShortCommandTimeoutMs,u={...e?.headers,"user-agent":await(0,p.userAgent)()},c=e?.method??"GET",h=e?.agent??!1,b=r(t.toString(),{method:c,headers:u,timeout:n,agent:h},(e=>{let r="";e.setEncoding("utf8").on("data",(e=>r+=e.toString())).resume().on("end",(()=>{const a={url:(0,l.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&y.HttpStatusIs.redirect(a.statusCode)&&!(0,l.blank)(e.headers.location)?(v().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(w(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(v().debug("complete",{...a,data:(0,d.ellipsize)(r,64),data_length:r.length}),i.resolve(a))}))})).on("error",(e=>i.reject(e)));return(0,l.blank)(e.body)||b.write(e.body),b.end(),i}t.HttpMethods=(0,c.strEnum)("GET","PUT","POST","PATCH","DELETE"),t.get_=w,t.httpRequest_=b},65713:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)((()=>(0,r.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,s.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,s.lazy)((()=>({trie:new n.MultiMap,small:[]}))),h=3;function f(e){const t=new n.MultiMap,i=[];for(const r of e)r.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tr.startsWith(e)));if(null!=s)return s}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,n.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,n.lazy)((()=>s.default.cpus()),5*a.minuteMs),t.cpuCount=(0,n.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},14854:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuUsage=t.isTooBusy=void 0;const d=c(i(48161)),h=i(42659),f=i(45599),m=i(55835),p=i(31586),g=i(68708),y=i(19851),v=i(50213),w=i(7282),b=i(78406),S=i(25764),P=i(38835),_=i(74128),T=i(82647),M=i(43334),E=i(28874),k=i(30933),D=i(15674),x=(0,y.lazy)((()=>(0,v.mkLogger)("work.CpuUsage"))),C=(0,y.lazy)((()=>{const e=A.instance().busyPct();(0,_.syncReport)().maybeSystemData({from:"cpuUsage",state:"note",details:"Current system load is too high to schedule more work",meta:(0,g.compactValues)({loadCpuPct:I(),cpuBusyPct:e})}),x().warn("Current system load is too high to schedule more work",{cpuBusyPct:e,max:E.Settings.cpuBusyPercent.valueOrDefault})}),((0,w.isTest)()?15:60)*h.secondMs);t.isTooBusy=function(){if(E.Settings.cpuBusyPercent.valueOrDefault<=0)return!1;const e=A.instance().busyPct(),t=(0,p.clamp)(1,150,Math.round(4*E.Settings.cpuBusyPercent.valueOrDefault/3));return(0,p.gte)(e,t)?(C(),!0):(C.unset(),!1)};class A extends b.EndableInterval{constructor(){super({name:"CpuUsage()",callback:()=>l(this,r,"m",o).call(this),intervalMs:((0,D.singleThreadedMode)()?60:M.isWin?20:10)*h.secondMs,rank:S.EndableRanks.first}),r.add(this),s.set(this,new T.Average(5)),n.set(this,new F),(0,p.mapFinite)(I(),(e=>l(this,s,"f").push(e))),l(this,r,"m",o).call(this)}get cpuCount(){return l(this,n,"f").cpuCount}idlePct(){return(0,m.map)(this.busyPct(),(e=>100-e))}busyPct(){return l(this,s,"f").sampleAvg??I()}}t.CpuUsage=A,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(e){(0,p.gte0)(e)&&l(this,s,"f").push(e)},o=function(){l(this,r,"m",a).call(this,I());const e=new F;l(this,r,"m",a).call(this,e.busyPct(l(this,n,"f"))),u(this,n,e,"f")},A.instance=(0,f.defer)((()=>new A));class F{constructor(e=d.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){const t=this.busyMs-e?.busyMs,i=this.idleMs-e?.idleMs,r=t+i;return e?.cpuCount===this.cpuCount&&(0,p.gte0)(t)&&(0,p.gte0)(i)&&(0,p.gt0)(r)?(0,p.sigFigs)(t/r*100,3):void x().warn("busyPct(): Unexpected CpuTimes. If this continues, busyPct() will be incorrect."+P.InternalErrorFlag,{self:this,prior:e,busyMs:t,idleMs:i,totalMs:r})}}function I(){return M.isWin?void 0:(0,p.sigFigs)(d.default.loadavg()[0]/(0,k.cpuInfo)().length*100,3)}},73328:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyDoNotRun=t.doNotRun=void 0;const r=i(68708),s=i(99331),n=i(74128),a=i(63664),o=i(14854);t.doNotRun=function(e){return null!=u(e)};const l=["error","no-library","stop-sync"];function u(e){if(!0===e?.ended)return"endable ended";if((0,s.ending)())return"service is ending";if((0,o.isTooBusy)())return"system is too busy";const t=(0,a.getRemoteOrLocalHealthSummarySync)();if(null==t||!l.includes(t.level))return;const i=t.level+": "+t.msg.join("\n");return(0,n.syncReport)().maybeSystemData({from:"whyDoNotRun",state:"note",details:t.level,meta:(0,r.omit)(t,"links","buttons")}),i}t.whyDoNotRun=u},58444:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,n.lazy)((()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},69385:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveOnResume=t._setPaused=t.resume=t.pause=t.isPaused=void 0;const r=i(34102),s=i(37692);let n=!1;function a(){return n}function o(e=!0){l(e),(0,s.writeStateFile)({paused:e})}function l(e){e!==n&&(n=e,(0,r.ee)().emit(e?"pause":"resume"))}t.isPaused=a,t.pause=o,t.resume=function(){return o(!1)},t._setPaused=l;const u=Promise.resolve();t.resolveOnResume=function(){return a()?new Promise((e=>{(0,r.ee)().once("resume",e)})):u}},15674:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,r.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),s.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function b(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=b,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(b()*(0,f.cpuCount)())<=1},t.maxCpus=(0,r.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(b()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=w();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,v());return t=(0,a.clamp)(1,s,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:b(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,r.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},37692:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addStateEvent=t.writeStateFile=t.readStateFile=t.stateEvents=t.StateEvents=t.StateEventFns=void 0;const s=r(i(78474)),n=i(40958),a=i(76790),o=i(42659),l=i(45599),u=i(41400),c=i(68708),d=i(50989),h=i(87290),f=i(73787),m=i(19851),p=i(50213),g=i(28874),y=i(69385),v=(0,l.defer)((()=>(0,p.mkLogger)("work.SharedState")));let w;t.StateEventFns={checkTasks(){},reloadLicenses(){}},t.StateEvents=(0,d.strEnum)(...(0,c.keys)(t.StateEventFns)),t.stateEvents=new s.default;let b=0;function S(){const e=(0,h.libraryDataDirPosixFile)()?.join("state.json"),t=Date.now(),i=t-b>o.minuteMs;i&&(b=t);const r=e?.existsSync({refresh:i})??!1;return r&&null!=e&&e.eql(w?.nativePath)||(w?.close(),w=void 0),r&&null!=e&&(w??(w=new f.FileWatcher(e.nativePath,{encoding:"utf8",persistent:!1,recursive:!1},P))),e}(0,u.later)((()=>{g.Settings.libraryDir.watchLater(P)}));const P=(0,m.lazy)((()=>t.readStateFile.refresh()),25);t.readStateFile=(0,m.lazy)((()=>{const e=S()?.readJsonSync();for(const i of e?.events??[])_.get(i.e)!==i.ts&&(v().info("emitting event "+i.e),t.stateEvents.emit(i.e),_.set(i.e,i.ts));return(0,y._setPaused)(e?.paused??!1),e}));const _=new Map;function T(e){const i=S();if(null==i)v().error("overwrite(): failed: no library directory");else{const r=i?.readJsonSync(),s=function(e){const t=Date.now()-10*o.minuteMs;return(0,n.uniqByLast)((0,a.sortBy)((e??[]).filter((e=>e.ts>t)),(e=>e.ts)),(e=>e.e))}([...r?.events??[],...e.events??[]]),l={paused:e.paused??r?.paused??g.Settings.startPaused.valueOrDefault,events:s};(0,y._setPaused)(l.paused),t.readStateFile.set(l),i.writeJsonSync(l)}}t.writeStateFile=T,t.addStateEvent=function(e){const t=Date.now();_.set(e,t),T({events:[{e,ts:t}]})}},22751:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const r=i(58587),s=i(87997),n=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,n.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,n.lazy)((()=>new r.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,n.lazy)((()=>(0,s.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},83600:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.RequestTask=void 0;const a=i(58587),o=i(80875),l=i(19851),u=i(50213),c=i(34102),d=i(84542),h=i(87445),f=i(40958),m=i(26905),p=i(98553),g=i(31586),y=(0,l.lazy)((()=>(0,u.mkLogger)("worker.RequestTask")));class v extends a.Task{constructor(e){super((0,p.stringify)(e),(e=>n(this,r,"m",s).call(this,e))),r.add(this),this.request=e}}t.RequestTask=v,r=new WeakSet,s=function(e){for(const t of(0,f.compactBlanks)((0,d.splitLines)(e))){const e=(0,o.parseJSON)(t);if(null==e)y().warn("ignoring non-json line from worker",{line:t});else{if(null!=e.error)throw y().warn("worker threw error",{response:e}),(0,m.errorFromJson)(e.error);if((0,g.isNumber)(e.id))return e.id!==this.request.id?y().throw(`bad request: #parse given mismatching requests (${e.id} != ${this.request.id})`,{response:e,request:this.request}):e.response;(0,h.isProgressEvt)(e)?(0,c.ee)().emit("progress",e):y().warn("ignoring json line from worker",{response:e})}}return y().throw("bad request: #parse missing valid response")}},93493:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearShims=t.setupShimDelegates=void 0;const r=i(19851),s=i(5233),n=i(68708),a=i(13538),o=i(57206),l=i(50213),u=i(23560),c=i(70025),d=i(28874),h=i(15674),f=i(22751),m=i(83600),p=i(58800),g=i(24817),y=(0,r.lazy)((()=>(0,l.mkLogger)("worker.ShimDelegation")));let v=0;async function w(e,t){const i=d.Settings.taskTimeoutMs.valueOrDefault;return(0,s.retryOnReject_)((async()=>{y().throwIfAborted_();const r={id:v++,fn:e,args:t},s=new m.RequestTask(r),n=await(0,p.workerCluster)(),o=n?.t,l=null==n||null==o?g.WorkerFunctions[e](...t):n.awaitOrAbort(o.enqueueTask(s));return(0,a.thenOrOnTimeout)(l,i/3,(()=>{y().warn("soft timeout servicing work request",{request:r,timeoutMs:i}),(0,f.onTimeout)()})),(0,a.thenOrTimeoutError)(l,i)}),{maxRetries:d.Settings.maxRetries.valueOrDefault,timeoutMs:i,retryDelay:d.Settings.minDelayBetweenRetriesMs.valueOrDefault,errorIsRetriable:e=>!1!==(0,c.isRetriableError)(e)})}function b(){for(const e of(0,n.values)(g.WorkerFunctions))(0,n.maybeCall)(e,"clearShim")}t.setupShimDelegates=async function(){if((0,o.addDefaultJsonRevivers)(),(0,u.isWorkerService)())b(),y().warn("setupShimDelegates(): in worker service, skipping");else if((0,h.singleThreadedMode)())y().warn("setupShimDelegates(): single-threaded mode, clearing shims"),b(),await(0,p.endWorkerCluster)();else for(const[e,t]of(0,n.entries)(g.WorkerFunctions))t.setShim((t=>w(e,t)))},t.clearShims=b},24817:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequest_=t.isWorkRequest=t.mkWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=t.AllWorkerFunctionCandidates=void 0;const r=i(98553),s=i(31586),n=i(68708),a=i(50989),o=i(32639),l=i(13991),u=i(50597),c=i(48368),d=i(52121),h=i(48604),f=i(181),m=i(66106),p=i(47783),g=i(83966);t.AllWorkerFunctionCandidates={_extractVideoFrame_:m._extractVideoFrame_,_readRawTags:p._readRawTags,_readTags:p._readTags,assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkerFunctions={assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkRequestMethods=(0,a.strEnum)(...(0,n.keys)(t.WorkerFunctions));let y=0;t.mkWorkRequest=function(e,t){return{id:++y,fn:e,args:t}},t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,s.isNumber)(e.id)},t.handleWorkRequest_=async function(e){const i=t.WorkerFunctions[e?.fn];if((0,o.isFunction)(i))return i(e?.args);throw new Error("invalid method "+(0,r.stringify)(e))}},58800:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerCluster=t.endWorkerCluster=t.workerClusterPriorEnd=void 0;const r=i(58587),s=i(36557),n=i(19851),a=i(50213),o=i(71567),l=i(25764),u=i(84777),c=i(86335),d=i(38835),h=i(84542),f=i(87445),m=i(41944),p=i(15674),g=i(42659),y=i(98553),v=i(31586),w=i(67478),b=i(54993),S=i(27395),P=i(5916),_=i(55534),T=i(29325),M=i(28874),E=i(30933),k=i(41657),D=(0,n.lazy)((()=>(0,a.mkLogger)("worker.cluster")));t.workerClusterPriorEnd=async function(){return(await t.workerCluster.prior())?.t.closeChildProcesses()},t.endWorkerCluster=function(){return(0,S.end)(t.workerCluster.prior())},t.workerCluster=(0,P.lazyAsync)({desc:"worker.workerCluster",later:async()=>{const e=await(0,c.pathToService)("worker");if(null==e)return D().throw("Could not find worker.js"+d.FatalErrorFlag);D().info("worker.js found at "+e);const t={id:-1,fn:"ping",args:{}},i=new r.BatchCluster({processFactory:async()=>(D().info("Spawning new worker",{execPath:process.execPath,worker:e.nativePath,maxProcs:(0,p.maxCpus)()}),(0,u.spawn)(process.execPath,[e.nativePath],0,{env:await(0,k.workerEnv)()})),...(0,s.batchClusterOptions)((0,p.maxCpus)(),"worker.BatchCluster"),streamFlushMillis:0,versionCommand:(0,y.stringify)(t),healthCheckCommand:(0,y.stringify)(t),taskTimeoutMillis:M.Settings.taskTimeoutMs.valueOrDefault,maxProcAgeMillis:4*M.Settings.taskTimeoutMs.valueOrDefault,minDelayBetweenSpawnMillis:(0,T.isPacked)()?g.secondMs:1,pass:o.ReadyStr,fail:d.FatalErrorRe,exitCommand:_.ServiceExitCommand});return i.on("taskData",(e=>{for(const t of(0,h.splitLines)((0,b.toS)(e))){const e=(0,w.parseJSON)(t);(0,f.isProgressEvt)(e)&&(0,m.emitProgressEvt)(e)}})),p.maxCpus.watchLater((e=>{const t=(0,v.clamp)(1,(0,E.cpuCount)(),e??(0,p.maxCpus)());return D().warn("maxConcurrentImports changed",{maxProcs:t,newValue:e}),i.setMaxProcs(t)})),new s.BatchClusterObserver("worker",i,l.EndableRanks.first)}})},41657:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.workerEnv=void 0;const r=i(9727),s=i(28874),n=i(59107);t.workerEnv=async function(){const e={};return s.Settings.libraryDir.addToEnv(e),s.Settings.mountpoints.addToEnv(e,await(0,n.mountpoints)()),(0,r.childEnv)({overrides:e,forWorker:!0})}},83966:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const s=r(i(1708)),n=i(41400),a=i(31586),o=i(7282),l=i(12089),u=i(45608),c=i(57159),d=i(89035);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),(0,o.isTest)()&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:s.default.pid,input:e?.input??"(no input)"}}})},40958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function b(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function S(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,(()=>r))}return[...i.values()]}function P(e,t,i=1,r=(e=>e)){const s=[];if(et;n-=i)s.push(r(n));return s}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every(((e,t)=>e===s[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,n.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let r=0;r0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,n.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=b,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=b(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return S(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=b(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,r.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=S,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every((e=>!t(r,e)))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,r)=>e+(t(i,r)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,r)=>e+t(i,r)),0)},t.firstMatch=function(e,t){for(const i of b(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter((e=>!s.has(r(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,s.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),(()=>r));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,r)=>0===r||t(i)>=t(e[r-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,n.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const r=e.findIndex((e=>i(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const r=i(32639);t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t}},75761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??(i=new URLSearchParams)).append("v",r),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,s))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});n??(n=!0);const b=n&&(0,f.isSafari)((0,h.ua)());b?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=n?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const S=s.map((r=>m(y({assetId:e,params:t,reducer:i,width:r}),r)));return null!=l&&S.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(b?"data-":"")+"srcSet"]=S.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,n.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},5233:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const r=i(41400),s=i(31586),n=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,s.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{"use strict";function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function r(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!r(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!r(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=r,t.isDisabled=function(e){return r(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):r(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const r=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const r=i(40958),s=i(22573),n=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,n.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function w(){return(new Date).setHours(24,0,0,0)}function b(e,i="ago"){return e<1e3?"just now":(i=(0,s.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return b(Date.now()-e,t)},t.fmtElapsedMs=b},95892:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const r=i(38639),s=i(73872);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=s(e);if(y!==s(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach((function(e,t){r.push([e,t])})),t.forEach((function(e,t){s.push([e,t])})),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,r=!1;const s=function(){if(r){if(null!=i)throw i;return t}try{return r=!0,t=e()}catch(e){throw i=e,e}};return s.prior=()=>t,s.hasPrior=()=>r,s}},41400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const n=setTimeout((()=>i()),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}}))}t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n}},33374:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const r=i(31586),s=i(21605),n=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,n.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,s.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,s.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,n.megapixels)(o(e))},t.pixels=o},87562:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExampleDomain=void 0;const r=i(40958),s=i(51926),n=["example.com","example.net","example.org","example.edu",".example",".local"].map((e=>(0,s.stripPrefix)(e,".").split(".")));t.isExampleDomain=function(e){const t=e.toLowerCase().split(".");return n.some((e=>(0,r.arrayEndsWith)(t,e)))}},25763:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEmail=t.isEmailMaybe=void 0;const r=i(22573),s=i(87562),n=i(54993);t.isEmailMaybe=function(e){return null!=o(e)};const a=/^(?.+)@(?.[^@\n\r.\u2028\u2029]*\..+)$/;function o(e){const t=a.exec((0,n.toS)(e).trim());if(null==t?.groups)return;const{local:i,domain:o}=t.groups;return(0,r.blank)(i)||(0,r.blank)(o)||(0,s.isExampleDomain)(o)?void 0:{local:i,domain:o}}t.parseEmail=o},50357:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const r=i(12487),s=i(68708),n=i(34666),a=i(32639);function o(e,t){return(0,r.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,n.isPrimitive)(e)||(0,n.isPrimitive)(t))return e===t;if(!(0,s.isObject)(e)||!(0,s.isObject)(t))return!1;for(const i of(0,s.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=d.get(i);if(null!=r)return r(e,t)??null}for(const i of c){const r=i(e,t);if(null!=r)return r}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const r=i(59455);t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const r=i(40958),s=i(42659),n=i(55835),a=i(31586),o=i(12168),l=[{ms:s.yearMs,s:"year",p:"years"},{ms:s.yearMs/12,s:"month",p:"months"},{ms:s.weekMs,s:"week",p:"weeks"},{ms:s.dayMs,s:"day",p:"days"},{ms:s.hourMs,s:"hour",p:"hours"},{ms:s.minuteMs,s:"minute",p:"minutes"},{ms:s.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,s){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,n.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,r.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,r.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,n.mapOr)(s,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")}},50268:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const r=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,r.lt0)(t))return[...e].slice(t,i);const s=e[Symbol.iterator]();if((0,r.gt0)(t))for(let e=0;e{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(r,s){if((0,isFunction_1.isFunction)(r))return;let n,a,o,l=toJSON(r);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(r===l&&(l={...l}),delete l[e]);for(n=0;nnew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let r=0;t.Latch=class{constructor(e=r++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const r=i(40958),s=i(50357),n=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,r.isEmpty)(l))return;const n=await e,o=await i;if(!(0,s.eql)(n,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const r=i(68708);class s extends Error{constructor(e,t){super(e),this.message=e,(0,r.assignFields)(this,t)}}t.MetaError=s},23838:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter((e=>!(0,n.eql)(e,t)));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,r.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,r.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,(t=>!e(i,t,s)));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const r=i(76790),s=i(22573),n=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,s){return!(null==s||!o(s))&&([e,i]=(0,r.sort)([e,i]),(0,t.lte)(e,s)&&(0,t.gte)(i,s))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,s.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return o(e)&&e>0}function b(e){return o(e)&&e>=0}function S(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function T(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const r=(0===t?1e-5:t)*(1-i);return f(t-r,t+r,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=b,t.toGte0=function(e){return b(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=S,t.map2Numeric=function(e,t,i){return S(e,(e=>S(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,n.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return S(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?P(e/r)*r:P(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=T,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return T(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,r.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,r.compact)((0,s.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function b(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,h)))s[e]=b(...i.map((t=>t[e])));return s}function S(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[r,s]of g(t))!0!==i?.omitKeys?.includes(r)&&(null==s&&!0!==i?.assignNullish||(e[r]=s));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of g(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,r.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,n.notBlank)(t)));return(0,r.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=b,t.pick=function(e,...t){if(null==e)return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:b(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,"."),o=S(t,i);null!=o?.value&&s(o.key,(0,n.blank)(a)?o.value:e(o.value,a))}for(const r of h(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=S,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map((t=>e(t,i))));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,(e=>e.value))}}const[s,a]=(0,c.splitFirst)(i,"."),o=S(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,n.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,r.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),r=p(i);return 1===r.length?r[0]:i}},97790:(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return n(e).flatMap((e=>n(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,r){return n(e).flatMap((e=>n(t).flatMap((t=>n(i).flatMap((i=>r(this.a,e,t,i)))))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r,t.isOpt=s,t.opt=n},97238:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toSeed=t.prngSeed=t.SeedCount=t.PrimeBins=t.PrimesPerBin=void 0;const r=i(31586),s=i(30976),n=i(54993);t.PrimesPerBin=4,t.PrimeBins=8,t.SeedCount=t.PrimesPerBin**t.PrimeBins,t.prngSeed=function(){return(0,s.randomInt)(0,t.SeedCount)},t.toSeed=function(e){const i=(0,r.toInt)((0,n.toS)(e));return(0,r.within)(0,t.SeedCount,i)?i:void 0}},39926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const r=i(40958),s=i(54993),n=["number","string","boolean"];function a(e){return-1!==n.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):r!==n?o.indexOf(r)-o.indexOf(n):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const r=await e;return t(r)?i(r):void 0}},57153:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const r of o(0,e.length,t))i.push(e[r]);return i},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter((e=>(0,s.gt0)(e.priority)));let i=l(0,(0,r.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let r=e;t.global||(t=new RegExp(t,"g"));let s=null;for(;null!=(s=t.exec(e));)s.index===t.lastIndex&&t.lastIndex++,r=r.slice(0,s.index)+i(s)+r.slice(s.index+s[0].length);return r}},21605:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const r=i(31586);function s(e){if(!(0,r.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){const t=s(e);return 90===t||270===t}},62220:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const r=i(68708),s=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,r.fromEntries)(t.map(((e,t)=>[e,t]))),n={};for(const e of t)n[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...n,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,s.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),r=a(t);return null==i||null==r?void 0:i>r?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=f();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function b(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(m(e,r).startsWith(t))return r;return-1}function S(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:"base"}))}function P(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find((e=>S(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=p(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=b,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(r.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),s).trim()).length<=r)return[t];const n=b(t," ",r);if(n>s.length)return[m(t,0,n),...e(m(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const r=i(42659),s=i(68708),n=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,r)=>{let s=!0;const n=setTimeout((()=>{s&&(s=!1,i(a.Timeout))}),t);try{n.unref?.();const t=await e;s&&(s=!1,i(t))}catch(e){s&&(s=!1,r(e))}finally{clearTimeout(n)}}))}async function c(e,t,i=!0){const s=await u(e,t,i);if(s===a.Timeout)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(t)+")");return s}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?a.Timeout:u(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(r,n)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{r(await i())}catch(e){n(e)}}}),t);(0,s.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),r(l))}catch(e){a&&(a=!1,n(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const s=t-Date.now();if(s<=0)throw new o.TimeoutError("timeout ("+(0,r.fmtHMS)(s)+")");return c(e,s,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!0}){if(null==e)return(0,n.tot)(i);const s=await u(e,t,r);return s===a.Timeout?(0,n.tot)(i):s}},99036:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ThumbFits=void 0;const r=i(50989);t.ThumbFits=(0,r.strEnum)("aspect","square")},42279:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const r=i(32639);t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const r=i(22573),s=i(30301),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,s.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,(e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const r=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const r=i(30301),s=i(54993);t.ua=(0,r.lazy)((()=>(0,s.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)}},32790:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeQuote=t.AssetQueryOrderByColumns=void 0;const r=i(50989),s=i(54993);t.AssetQueryOrderByColumns=(0,r.strEnum)("capturedAt","updatedAt"),t.maybeQuote=function(e){return null!=(e=(0,s.toS)(e).trim()).match(/\s/)?`"${e}"`:e}},58939:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const r=i(55835),s=i(31586);function n(e){const t=e;return(0,s.isNumber)(e)?e:(0,s.isNumber)(t.id)?t.id:(0,s.isNumber)(t.assetId)?t.assetId:(0,s.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),((e,t)=>e===t),(()=>!1))}},12236:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.noRecentAssetIdsProgress=t.isRebuildProgress=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0;const r=i(50989);t.SyncStatuses=(0,r.strEnum)("processing","paused","done"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI].includes(e?.uri)},t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},41942:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkReplace=t.XLocationReplace=t.mkRedirect=t.XLocationRedirect=void 0,t.XLocationRedirect="X-Location-Redirect",t.mkRedirect=function(e,i){return{[t.XLocationRedirect]:e,toast:i}},t.XLocationReplace="X-Location-Replace",t.mkReplace=function(e,i){return{[t.XLocationReplace]:e,toast:i}}},71050:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isServerToast=t.DismissAnchor=t.isToastPlusOnly=void 0;const r=i(22573);t.isToastPlusOnly=function(e){return!0===e?.toastPlusOnly},t.DismissAnchor="#dismiss",t.isServerToast=function(e){return(0,r.notBlank)(e?.text)}},79114:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInfoTag=t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.isTagRef=t.ctxToS=t.TagGalleryProps=t.nextChildTagsUrl=t.nextAssetsUrl=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0;const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=128,t.BeforeAfterStreamLimit=8,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.seed,(e=>i.seed=e.toString())),(0,a.mapNumeric)(t.limit,(e=>i.limit=e.toString())),(0,a.mapNumeric)(t.offset,(e=>i.offset=e.toString())),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs],t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)}},94383:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPath=void 0,t.ApiProgressPath="/sse/progress"},27776:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mkTagUri=t.mkTagFullPath=t.mkHomeFullPath=t.urlSeed=void 0;const r=i(40958),s=i(30301),n=i(31586),a=i(97238),o=i(29652);function l(e,i){const r=(0,o.toURLSearchParams)(e);if(i||!(0,n.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function u(e,t,i=!1){const r=c(e,t,i);return(0,o.assembleFullPath)(r.path,r.query)}function c(e,t,i=!1){return{path:"/tag/"+((0,r.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:l(t,i)}}t.urlSeed=(0,s.lazy)(a.prngSeed,100),t.mkHomeFullPath=function(e){return u([],e,!0)},t.mkTagFullPath=u,t.mkTagUri=c},23541:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return n(e)??[]},t.optToA=n},41583:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const r=i(40958),s=i(23541),n=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,s.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,r.compact)((0,n.toA)(e).map(o))}},54993:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const r=i(98553);t.toS=function(e){return n(e,",")};const s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>n(e,t))).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}t.toStr=n},98401:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cancelFileAndProcCleanups=t.scheduleFileAndProcCleanups=t.fileCleanups=t.cleanup_=t.maybeCleanup_=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(56519),o=i(76187),l=i(87290),u=i(79267),c=i(32144),d=i(13829),h=i(69734),f=i(95696),m=i(65238),p=i(70257),g=i(13940),y=i(12495),v=i(95402),w=i(28874),b=i(40958),S=i(42659),P=i(31586),_=i(64526),T=i(22526),M=i(69032),E=(0,r.lazy)((()=>(0,s.mkLogger)("library.Cleanup")));async function k(){const e=_.Library.instance();if(null==e)E().info("No library to vacuum.");else{E().info("Running tag and search maintenance...");try{await(0,M.runTagMaintenance)()}catch(e){E().warn("Failed to run tag maintenance",{error:e})}E().info("Vacuuming db..."),await(await e.dbModelSetup_()).db.vacuum(),(0,n.isDbJanitorService)()&&(E().info("Running database maintenance..."),await e.runDbBackup_())}E().info("Cleaning child processes..."),await(v.Pids.instance()?.killOldProcs()),E().info("Cleaning stale and temp files..."),await D(),await(0,a.mapAsync)({name:"fileCleanup",arr:j(),f:e=>e.cleanup()})}t.maybeCleanup_=(0,r.lazy)(k,5*S.minuteMs),t.cleanup_=k;const D=(0,r.lazy)((()=>(0,l.libraryDataDirPosixFile)()?.join("shared-state").rmrf())),x=(0,r.lazy)((()=>u.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:g.imageCacheDir_,staleMs:w.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ImageCacheName)}))),C=(0,r.lazy)((()=>u.FileCleanup.for({name:"readdirCacheCleanup",rootNativePath:async()=>f.PosixFile.for((0,m.readdirCacheDir)()),staleMs:w.Settings.readdirCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(m.ReadDirCacheName)}))),A=(0,r.lazy)((()=>u.FileCleanup.for({name:"previewWipCleanup",rootNativePath:l.libraryPreviewsDirPosixFile,staleMs:S.hourMs,isPrunable:e=>(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)}))),F=(0,r.lazy)((()=>u.FileCleanup.for({name:"advisoryLockWipCleanup",rootNativePath:d.defaultFsAdvisoryLockDir,staleMs:S.hourMs,isPrunable:h.isPsLockFileOrDir}))),I=(0,r.lazy)((()=>u.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,P.gt0)(w.Settings.syncReportRetentionCount.valueOrDefault)?(0,l.librarySyncReportsDir)():void 0,staleMs:S.hourMs,isPrunable:e=>(0,p.isWip)(e)||(0,c.isCsvExt)(e)})));function O(e){return(0,h.isPsLockFileOrDir)(e)||(0,p.isWip)(e)||(0,o.isSqliteFile)(e)}const L=(0,r.lazy)((()=>u.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,T.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:S.hourMs,isPrunable:O}))),R=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,T.libraryDbObjects_)().libraryDbBackupDir,staleMs:S.hourMs,minRetained:w.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:O})));async function N(){const e=await(_.Library.instance()?.dbModelSetup_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const B=(0,r.lazy)((()=>u.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:N,staleMs:S.hourMs,minRetained:1,isPrunable:O})));function j(){return(0,b.compact)([x(),C(),A(),F(),(0,y.LogDirCleanup)(),I(),L(),R(),B()])}t.fileCleanups=j,t.scheduleFileAndProcCleanups=(0,r.lazy)((()=>{v.Pids.instance()?.scheduleInterval();for(const e of j())e.scheduleInterval()})),t.cancelFileAndProcCleanups=function(){t.scheduleFileAndProcCleanups.unset(),v.Pids.instance()?.cancelInterval();for(const e of j())e.cancelInterval()}},64526:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const l=i(27395),u=i(25764),c=i(38836),d=i(99331),h=i(45608),f=i(15056),m=i(87290),p=i(38835),g=i(57159),y=i(61704),v=i(95696),w=i(18454),b=i(13940),S=i(48604),P=i(19851),_=i(23560),T=i(28874),M=i(2858),E=i(7014),k=i(63870),D=i(15674),x=i(22573),C=i(38639),A=i(42659),F=i(56409),I=i(68708),O=i(25470),L=i(22526),R=i(41844);class N extends c.EndableWrapper{static instance(){const e=T.Settings.libraryDir.valueOrDefault,t=a(this,r,"f",s)?.rootDir.nativePath,i=!0===a(this,r,"f",s)?.isReadySync(),n=!0===a(this,r,"f",s)?.ended;return(0,y.nativePathsEqlSync)(t,e)&&!n?a(this,r,"f",s):(0,_.isSyncService)()&&i?void(0,h.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,l.end)(a(this,r,"f",s)),o(this,r,(0,x.blank)(e)||!(0,M._libraryHasSettings)(e)?void 0:new r(e),"f",s))}static get priorInstance(){return a(this,r,"f",s)}static endPriorInstance(){const e=a(this,r,"f",s);return o(this,r,void 0,"f",s),(0,l.end)(e)}static async instanceReady(){const e=r.instance();return await(e?.ready),e}static instanceRequired_(){const e=r.instance();if(null==e)throw new Error("Library is undefined"+p.FatalErrorFlag);return e}constructor(e){super(`library.Library(${e})`,(()=>this.onEnd()),u.EndableRanks.predb),this.start=Date.now(),this.readyLatch=new F.Latch,n.set(this,(0,P.lazy)((async()=>{try{this.logger.debug("setup() started"),this.logger.throwIfAborted_(),await(0,M.readLibrarySettings)(this.rootDir.nativePath),await(0,m.setupLibraryDirs_)(this.rootDir),await(0,b.imageCacheDir_)(),this.logger.throwIfAborted_();const e=await(0,E.bestVolumeForPath)((0,m.libraryPreviewsDirPosixFile)(this.rootDir));if((0,C.isTrue)(e?.remote)){const e=T.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;T.Settings.maxConcurrentImports.hasValue()||(T.Settings.maxConcurrentImports.tmpValue=e,(0,D.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxSyncFileJobsMax to ${e}.`)}this.logger.throwIfAborted_(),(0,_.isDbService)()&&await this.dbModelJanitor(),this.previews(),this.logger.throwIfAborted_(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,d.ending)()||(this.logger.warn("setup() failed:",{error:e}),w.HealthCheck.addError(e),this.readyLatch.reject(new g.WrappedError("Failed to start library",{cause:e})))}}))),this.previews=(0,P.lazy)((()=>(0,I.tap)(new S.Previews((0,m.libraryPreviewsDirPosixFile)(this.rootDir)),(e=>S.Previews.instance.set(e))))),this.originalsDir=(0,P.lazy)((()=>(0,m.libraryOriginalsDirPosixFile)(this.rootDir))),this.assetFileRepository=(0,P.lazy)((()=>new R.AssetFileRepository(this.originalsDir()))),this.libraryDbFile=(0,P.lazy)((()=>(0,f.pathToDb)(this.dataDir,"models"))),this.dbModelSetup_=(0,P.lazy)((async()=>{if((0,_.isDbService)())return(0,L.dbModelSetup_)(this.rootDir);throw new Error("Not a db service")})),this.dbFsLock=(0,P.lazy)((async()=>(await this.dbModelSetup_()).fslock)),this.useReplica=(0,P.lazy)((async()=>(await this.dbModelSetup_()).useReplica)),this.modelDb=(0,P.lazy)((async()=>(await this.dbModelSetup_()).db)),this.dbModelJanitor=(0,P.lazy)((async()=>O.DbModelJanitor.for(await this.dbModelSetup_()))),this.onEnd=(0,P.lazy)((async()=>{if(!(0,d.ending)())for(const{ea:e,t}of[{ea:this.dbModelJanitor.clear(),t:5*A.minuteMs},{ea:this.dbFsLock.clear(),t:(0,k.commandTimeoutMs)()}])await(0,l.end)(e,t);this.logger.info("onEnd(): finished.")})),this.rootDir=v.PosixFile.for(e),this.dataDir=(0,m.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),a(this,n,"f").call(this)}get isPendingSetup(){return this.readyLatch.isPending()}get ready(){return this.readyLatch.promise.then((()=>this))}isReadySync(){return this.readyLatch.isResolved()}async runDbBackup_(){return(await this.dbModelJanitor())?.backup_()}}t.Library=N,r=N,n=new WeakMap,s={value:void 0}},19113:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=void 0;const r=i(62105),s=i(181),n=i(94448),a=i(39604);t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notBlocklistedSha:a.notBlocklistedSha}),t&&i.push({isValidFile:s.isValidFile}),i}},78339:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.saveLibrarySettings=t.importSettings=t.librarySettings=void 0;const r=i(19851),s=i(50213),n=i(71567),a=i(87290),o=i(98314),l=i(95696),u=i(28874),c=i(2858),d=i(32707),h=i(22573),f=i(50357),m=i(54993),p=i(14611),g=(0,s.mkLogger)("LibrarySettings");function y(e={}){return g.tap({msg:"librarySettings",level:"info",result:{scanAllDrives:u.Settings.scanAllDrives.valueOrDefault,scanPath:u.Settings.scanPaths.values,copyAssets:u.Settings.copyAssetsToLibrary.valueOrDefault,autoUpdateCheck:u.Settings.autoUpdateCheck.value,allowUserAgent:u.Settings.allowUserAgent.value,reportErrors:u.Settings.reportErrors.value,...e}})}function v(e){u.Settings.scanAllDrives.setValueIfDefined(e.scanAllDrives),u.Settings.scanPaths.setValueIfDefined(e.scanPath),u.Settings.copyAssetsToLibrary.setValueIfDefined(e.copyAssets),u.Settings.autoUpdateCheck.setValueIfDefined(e.autoUpdateCheck),u.Settings.allowUserAgent.setValueIfDefined(e.allowUserAgent),u.Settings.reportErrors.setValueIfDefined(e.reportErrors)}t.librarySettings=y,t.importSettings=v,t.saveLibrarySettings=async function(e,t){const i=l.PosixFile.forMaybe((0,m.toS)(e).trim())?.resolve(),s=y(),w=u.Settings.libraryDir.valueOrDefault,b=i??l.PosixFile.forMaybe(w);let S=Promise.resolve();const P=(0,r.lazy)((()=>{S=S.then((async()=>{try{v(s),u.Settings.libraryDir.value=w,await(0,c.writeSystemSettings_)(),(0,h.blank)(w)||await(0,c.writeLibrarySettings_)(w),await(0,p.restartLibrary_)()}catch(e){g.warn("Failed to roll back to prior settings",{priorSettings:s,priorLibraryDirValue:w,error:e})}}))}));if(null==b)return{error:"Please choose a directory for your library.",ready:S};const _=b?.nativePath!==w;if(_){try{await(0,a.setupLibraryDirs_)(b)}catch(e){return{error:"Failed to set up "+b+". Please choose a different directory for your library. "+(0,o.errorToS)(e)}}g.info("Library directory changed, asking sync to shut down",{prior:w,new:i?.nativePath}),n.StdoutWrite.shutdownSync()}try{v(t);const e=!(0,f.eql)(s,y());if(null==await(0,c.writeLibrarySettings_)(b.nativePath))return P(),{error:"Cannot write to "+b.nativePath+". Please choose a different directory for your library.",ready:S};u.Settings.libraryDir.value=b.nativePath;try{await(0,c.writeSystemSettings_)()}catch(e){return P(),g.warn("Failed to write system settings",e),{error:"Couldn't write your system settings to "+(0,d.systemSettingsFile)()+": "+(0,o.errorToS)(e),ready:S}}return g.info("saveLibrarySettings()",{libraryDirChanged:_,librarySettingsChanged:e,settings:t,priorSettings:s,currentSettings:y()}),(_||e)&&(S=S.then((()=>(0,p.restartLibrary_)({readSettings:!1})))),{msg:"Saved",ready:S}}catch(e){return P(),g.error("Failed to save settings",{error:e}),{error:"Failed to save settings: "+(0,o.errorToS)(e),ready:S}}}},14611:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restartLibrary_=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(71567),o=i(34102),l=i(18454),u=i(28874),c=i(2858),d=i(64526),h=(0,r.lazy)((()=>(0,s.mkLogger)("library.RestartLibrary")));t.restartLibrary_=async function(e){if((0,n.isWebService)()&&a.StdoutWrite.shutdownSync(),e?.readSettings??1){for(const e of(0,u.persistedSettings)())e.unsetFileValue();await c.readSettings.refresh()}let t=Promise.resolve();h().warn("Shutting down prior library...");try{t=d.Library.endPriorInstance()}catch(e){h().warn("ending prior library failed:",{error:e})}(0,o.ee)().emit("clearCache"),null!=e?.libraryDir&&e.libraryDir!==u.Settings.libraryDir.valueOrDefault?u.Settings.libraryDir.value=e.libraryDir:u.Settings.libraryDir.broadcastChange(),l.HealthCheck.reset();const i=d.Library.instance();return t=t.then((()=>i?.ready)).then((()=>{})),(0,n.isWebService)()&&(t=t.then((async()=>{const e=await l.HealthCheck.awaitSettled();"ready"===e.state?a.StdoutWrite.restartSync():h().error("Restarted library, but health check summary was not ready",{summary:e})}))),{ready:t}}},18449:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sentryEnabled=void 0;const r=i(7282),s=i(96706),n=i(29325),a=i(28874);t.sentryEnabled=function(){return(0,s.isEnvTrue)("ENABLE_SENTRY")||(0,r.isProd)()&&(0,n.isPacked)()&&!0===a.Settings.reportErrors.value}},95629:function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return s(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelToSeverity=t.logEntryToBreadcrumb=t.mkBreadcrumbs=t.annotateEvent=t.sentryExceptionToS=t.sentryExceptionsToS=t.extractMessage=t.EventFilter=t.eventFilter=t.sendToSentry=t.installSentry=void 0;const o=n(i(16436)),l=a(i(48161)),u=a(i(1708)),c=i(19851),d=i(19043),h=i(50213),f=i(31578),m=i(7282),p=i(96175),g=i(23560),y=i(84968),v=i(81168),w=i(37805),b=i(25764),S=i(38836),P=i(99331),_=i(85100),T=i(98314),M=i(68301),E=i(70025),k=i(8769),D=i(34102),x=i(34592),C=i(42042),A=i(34474),F=i(20839),I=i(57902),O=i(45969),L=i(43334),R=i(40958),N=i(22573),B=i(42659),j=i(41400),z=i(98553),V=i(55835),W=i(12168),U=i(59455),q=i(54993),H=i(18449),G=(0,c.lazy)((()=>(0,h.mkLogger)("Sentry")));function $(e){(0,H.sentryEnabled)()&&null!=e&&!0!==(0,E.isDoNotSendError)(e)&&o.captureException(e)}t.installSentry=async function(e){try{return!!(0,H.sentryEnabled)()&&(o.init({dsn:L.isElectron?"https://0652cdd351054fe9853ff944b1f54e2c@o130922.ingest.sentry.io/289071":"https://5f52aefec1b3439eaed2e77b2d1210a8@o130922.ingest.sentry.io/1828379",shutdownTimeout:(0,_.serviceExitTimeoutMs)(e.name),release:w.release,environment:(0,m.nodeEnv)(),maxBreadcrumbs:100,integrations:[],beforeSend:(0,t.eventFilter)().beforeSend,onFatalError:e=>(0,k.onError)("sentry.onFatalError",e)}),G().info("Sentry initialized",{isElectron:L.isElectron}),!0)}catch(e){return G().warn("Failed to set up sentry",{error:e}),!1}},t.sendToSentry=$,t.eventFilter=(0,c.lazy)((()=>new J));class J{constructor(){this.beforeSend=async(e,t)=>{if(!(0,H.sentryEnabled)())return G().warn("Sentry.beforeSend(): not sending event",e),null;if(!0===await(M.ErrorStore.instance()?.eventQuotaExceeded(e)))return G().warn("Sentry.beforeSend(): event quota exceeded",e),null;const i=K(e,t);if(!0===(0,E.isDoNotSendError)(i))return G().info("Sentry.beforeSend(): event not sendable. vetoing",{event:e,hint:t,msg:i}),null;(0,N.blank)(e.message)&&(e.message=(0,v.ellipsize)(i,256));const r=await Z(e);return await(M.ErrorStore.instance()?.maybeSendEvent(r))??null},(0,D.ee)().on("fatal",$),(0,D.ee)().on("nonFatal",$),new S.EndableWrapper("EventFilter",(()=>this.end()),b.EndableRanks.first)}end(){return(0,V.map)(o.getCurrentHub().getClient(),(e=>e.close(5*B.secondMs)))}}function K(e,t){return(0,R.uniq)((0,R.compactBlankish)([e.message,...(0,U.toA)(Y(e.exception?.values)),(0,T.errorToS)(t?.originalException)])).join(": ")}function Y(e){return(0,R.mapNotEmpty)(e,(e=>(0,R.compactBlanks)(e.map(X))))}function X(e){return(0,R.mapNotEmpty)((0,R.compactBlanks)([e?.type,e?.value].filter((e=>"error"!==(0,q.toS)(e).toLowerCase()))),(e=>e.join(": ")))}async function Z(e){const t=await(0,C.getEmail)();(0,N.notBlank)(t)&&(null==e.user&&(e.user={}),e.user.email=t),(0,R.isEmpty)(e.breadcrumbs)&&(e.breadcrumbs=await Q());const i=e.extra??{};return i.pid=u.default.pid,i.serviceName=(0,g.serviceName)(),i.serviceEnding=(0,P.ending)(),i.runtimeMs=(0,y.runtimeMs)(),i.version=w.version,i.os=(0,p.osFullName)(),i.isDocker=(0,O.isDocker)(),i.nodeVersion=u.default.versions.node,i.locale=await(0,d.locale)(),i.cpus=(0,p.CPUs)(),i.memoryUsageMb=(0,f.memoryUsageMb)(),i.memoryUsageRssMb=(0,f.memoryUsageRssMb)(),i.systemMemory=(0,W.fmtBytes)(l.default.freemem())+" / "+(0,W.fmtBytes)(l.default.totalmem()),i.ffmpeg=await(0,x.ffmpegVersionDescription)(),i.argv=(0,z.stringify)(u.default.argv),e.extra=i,{timestamp:Date.now()/B.secondMs,...e}}async function Q(){await(0,j.delay)(3*F.DefaultLogFlushMs);const e=await(0,A.allRecentLogEntries)();return(0,R.compact)(e.map(ee))}function ee(e){return(0,V.map)(ie(e.l),(t=>({timestamp:e.ts/B.secondMs,level:t,category:e.from??(0,g.processName)(),message:(0,v.stripAnsiEsc)(e.ctx+": "+e.msg),data:"object"==typeof e.meta?e.meta:{value:(0,v.isString)(e.meta)?(0,v.stripAnsiEsc)(e.meta):e.meta}})))}t.EventFilter=J,t.extractMessage=K,t.sentryExceptionsToS=Y,t.sentryExceptionToS=X,t.annotateEvent=Z,t.mkBreadcrumbs=Q,t.logEntryToBreadcrumb=ee;const te=new Map([[I.LogLevels.fatal,"fatal"],[I.LogLevels.error,"error"],[I.LogLevels.warn,"warning"],[I.LogLevels.info,"info"],[I.LogLevels.debug,"debug"]]);function ie(e){return te.get(e)}t.logLevelToSeverity=ie},37158:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},f=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Service=t.setupEventHandlers=void 0;const p=m(i(29907)),g=m(i(1708)),y=i(57206),v=i(19851),w=i(50213),b=i(59880),S=i(23560),P=i(19913),_=i(71567),T=i(37805),M=i(38836),E=i(99331),k=i(45608),D=i(56038),x=i(55534),C=i(42499),A=i(49776),F=i(96706),I=i(98314),O=i(38835),L=i(70025),R=i(8769),N=i(57159),B=i(34102),j=i(33456),z=i(87408),V=i(85021),W=i(17181),U=i(86941),q=i(28874),H=i(41692),G=i(2858),$=i(69385),J=i(22573),K=i(42659),Y=i(41400),X=i(56409),Z=i(55835),Q=i(41583),ee=i(54993),te=i(95629);t.setupEventHandlers=(0,v.lazy)((()=>{(0,B.ee)().on("resume",(()=>(0,$.resume)())),(0,B.ee)().on("pause",(()=>(0,$.pause)()))}));class ie extends M.EndableWrapper{constructor(e){super(e),r.add(this),s.set(this,void 0),n.set(this,new X.Latch),a.set(this,new Map),this.setup_=(0,v.lazy)((()=>(0,D.time)("Service.setup",(()=>f(this,r,"m",o).call(this))))),u.set(this,(0,v.lazy)((()=>{const e=g.default.stdin.pipe(new j.LineReader);return e.on("data",(e=>f(this,r,"m",d).call(this,(0,ee.toS)(e)))),e}))),(0,S.isBillingService)()||(0,H.setSettingsDefaults)(),h(this,s,(0,w.mkLogger)("Service("+this.name+")"),"f"),f(this,r,"m",c).call(this),this.setup_()}get name(){return super.name}get ready(){return f(this,n,"f").promise}get isReady(){return f(this,n,"f").isResolved()}setInputHandler(e,t){f(this,a,"f").set(e.trim().toLowerCase(),t)}}t.Service=ie,s=new WeakMap,n=new WeakMap,a=new WeakMap,u=new WeakMap,r=new WeakSet,o=async function(){try{(0,J.mapNotBlank)((0,F.getEnv)("PS_FATAL_"+this.name),(e=>{throw new N.WrappedError(e,{fatal:!0})})),(0,J.mapNotBlank)((0,F.getEnv)("PS_CRASH_"+this.name),(e=>{(0,Y.later)((()=>{throw new N.WrappedError(e)}),5*K.secondMs)})),(0,P.setServiceName)(this.name),(0,b.setProcessTitle)(),(0,S.isMainService)()&&await(0,U.mergeUserDataDirs_)(),await(0,G.readSettings)(),await f(this,r,"m",l).call(this),(0,W.setupLogger)(),(0,y.addDefaultJsonRevivers)(),(0,A.cacheDir)(),(0,t.setupEventHandlers)(),f(this,u,"f").call(this),await(0,C.setupLuxon)(),q.Settings.startPaused.valueOrDefault&&(0,$.pause)(),(0,E.ending)()?f(this,n,"f").reject():f(this,n,"f").resolve()}catch(e){console.error((0,I.errorToS)(e)),f(this,n,"f").reject((0,Q.toErr)(e)),(0,k.exit)({reason:(0,L.addErrorFlags)(this.name+" setup failed: "+(0,I.errorToS)(e),O.FatalErrorFlag),status:14})}},l=async function(){(0,S.isPermaService)()||(0,B.ee)().on("fatal",(e=>(0,k.exit)({error:e,status:12}))),g.default.on("unhandledRejection",(e=>(0,Z.map)(e,(e=>(0,R.onError)("unhandledRejection",e))))),g.default.on("uncaughtException",(e=>(0,Z.map)(e,(e=>(0,R.onError)("uncaughtException",e))))),g.default.on("SIGINT",(()=>(0,k.exit)({reason:"SIGINT",status:0}))),g.default.on("SIGHUP",(()=>(0,k.exit)({reason:"SIGHUP",status:0}))),g.default.on("SIGTERM",(()=>(0,k.exit)({reason:"SIGTERM",status:0}))),p.default.isWorker&&g.default.on("disconnect",(()=>(0,k.exit)({reason:"disconnect",status:0}))),await(0,te.installSentry)(this)},c=function(){this.setInputHandler("--version",(()=>(0,_.stdoutWrite)({version:T.version}))),this.setInputHandler(x.ServiceExitCommand,(()=>(0,Y.later)((()=>(0,k.exit)({reason:x.ServiceExitCommand+" from stdin",status:0}))))),this.setInputHandler("--times",(()=>(0,_.stdoutWrite)(D.PromiseTimer.instance().report()))),this.setInputHandler(V.HealthCheckCommand,(async()=>(0,_.stdoutWrite)(await(0,z.getStatusSummary)({refresh:!0}))))},d=async function(e){if(f(this,s,"f").debug("onLine()",{line:e,ending:this.ended||(0,E.ending)()}),await this.setup_(),e.startsWith("--")){const t=e.split(/\s+/,1)[0],i=f(this,a,"f").get(t);null==i?(f(this,s,"f").error("onLine(): unknown command",{line:e,knownCommands:[...f(this,a,"f").keys()]}),console.warn("unknown command "+e)):await i(e.slice(t.length).trim())}else f(this,s,"f").error("onLine(): failed to process",{line:e})}},53791:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shutdown=void 0;const r=i(19851),s=i(50213),n=i(71567),a=i(99331),o=i(45608),l=i(65812);let u="unspecified";t.shutdown=function(e){return(0,s.mkLogger)("Shutdown").warn("shutdown()",{reason:e}),u=e,c()};const c=(0,r.lazy)((async()=>{n.StdoutWrite.shutdown(),(0,l.setUnrefTimeout)((()=>(0,a.ending)()?void 0:(0,o.exit)({reason:u,status:0})),3e3)}))},57064:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t._suggestedLibraryDirs=t.suggestedLibraryDirs=t.SuggestedLibraryDir=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(72993),o=i(19851),l=i(50213),u=i(7282),c=i(45255),d=i(81168),h=i(5916),f=i(56519),m=i(32551),p=i(48195),g=i(55939),y=i(44198),v=i(64660),w=i(83278),b=i(92423),S=i(29882),P=i(65238),_=i(16287),T=i(45969),M=i(28874),E=i(7014),k=i(40958),D=i(76790),x=i(22573),C=i(31586),A=i(13538),F=i(12168),I=(0,o.lazy)((()=>(0,l.mkLogger)("library.SuggestedLibraryDir")));class O{static async for(e,t){if((0,x.blank)(e))return;const i=await(0,E.bestVolumeForPath)(e,t);if(null==i)return void I().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:e});const r=await(0,p.isLibraryDir)(e);return new O(e,r,i)}constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=M.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=M.Settings.minDiskFreeGb.valueOrDefault*F.GB){if(this.isLibrary)return;const t=await(0,_.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,S.containsHiddenPathname)(this.nativePath))return I().tap({...i,result:"contains hidden path"});{const e=await(0,b.whyExcludedDirectoryRecursive)(w.BaseFile.for(this.nativePath));if(null!=e)return I().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,v.canRWXFirstExistingAncestor)(this.nativePath)?(0,C.gt0)(e)&&this.availableBytesnew O(e,!1,{mountpoint:"/test",available:F.GB})))});const l=[],d=[],h=await(0,A.thenOrTimeoutMaybe)(i,M.Settings.statTimeoutMs.valueOrDefault)??await(0,A.thenOrTimeoutMaybe)((0,E.volumes)(),M.Settings.statTimeoutMs.valueOrDefault);if(null==h||(0,k.isEmpty)(h))return I().warn("volumes() is empty: they don't get any suggestions."),[];async function v(t){const i=await O.for(t,h);if(null!=i)return i.isLibrary||i.isCurrentLibrary?(I().info("addSuggestion(): path is a library",i),void l.push(i)):void(null==await i.whyExcluded(e)&&d.push(i))}if(await v(M.Settings.libraryDir.value),(0,T.isDocker)())return[...l,...d];await v(await(0,g.picturesDir)());const w=[n.default.cwd(),...await(0,P.childDirectories_)(n.default.cwd())];(0,T.isDocker)()||w.push(...await(0,P.childDirectories_)((0,m.homeDir)())),(0,k.filterInPlace)(w,(e=>(0,S.isNotHiddenPosixPath)(e)));for(const e of w)await(0,p.isLibraryDir)(e)&&(I().info("current working dir is a library",e),await v(e));function b(){return Date.now()-r>c.ShortCommandTimeoutMs-500&&(I().debug("...ran out of time, stopping."),!0)}(0,T.isDocker)()||await v(s.default.join((0,m.homeDir)(),(0,a.AppName)())),await(0,f.mapAsync)({name:"suggestedLibraryDirs.addVolume",arr:h,f:e=>async function(e){try{if(await(0,p.isLibraryDir)(e.mountpoint))return I().info("addVolume(): vol.mountpoint is a library",e.mountpoint),void await v(e.mountpoint);for(const t of await(0,P.childDirectories_)(e.mountpoint)){if(b())break;if(await(0,p.isLibraryDir)(t))I().info("addVolume(): dir is a library",t),await v(e.mountpoint);else for(const i of await(0,P.childDirectories_)(t)){if(b())break;await(0,p.isLibraryDir)(i)&&(I().info("addVolume(): dir is a library",t),await v(e.mountpoint))}}const t=s.default.join(e.mountpoint,(0,a.AppName)());I().info("addVolume(): adding default suggestion",t),await v(t)}catch(t){I().warn("addVolume(): Failed to add suggestion",{err:t,vol:e})}}(e),timeoutMs:c.ShortCommandTimeoutMs}),I().debug("Finished gathering suggestions. Filtering...",{priorLibraries:l,suggestions:d});const _=l;for(const e of(0,D.sortBy)(d,(e=>[-e.availableBytes,-e.nativePath.length]))){if(_.length>=t)break;_.some((t=>t.nativePath===e.nativePath||t.mountpoint===e.mountpoint))||(I().debug("adding new path",e),_.push(e))}return(0,k.uniqBy)((0,D.sortBy)(_,(e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath])),(e=>e.nativePath))}t.SuggestedLibraryDir=O,t.suggestedLibraryDirs=(0,h.lazyAsync)({desc:"library.suggestedLibraryDirs",later:()=>L()}),t._suggestedLibraryDirs=L},77948:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemInformation=t.libraryMetrics=void 0;const r=i(21330),s=i(46296),n=i(17344),a=i(18454),o=i(81674),l=i(66184),u=i(96175),c=i(24540),d=i(23560),h=i(28874),f=i(2858),m=i(84968),p=i(94174),g=i(37805),y=i(14854),v=i(15674),w=i(40958),b=i(22573),S=i(38639),P=i(75240),_=i(55835),T=i(31586),M=i(20214),E=i(51926),k=i(12168),D=i(43487),x=i(54017),C=i(48723);async function A(){if(null==D.Asset.db())return;const e=[];e.push((0,k.plurMetric)(D.Asset.shownCount(),"asset"));const t=x.AssetFile.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,E.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,k.plurMetric)(i.assetFileCount,t+" file"))}return e.push((0,k.plurMetric)(C.Tag.rows(),"tag")),e}t.libraryMetrics=A;const F={pending:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"};t.systemInformation=async function(){const e=await(0,o.b)(),t=e?.l?.tier??"lite",i=a.HealthCheck.summary();return(0,w.compact)([{term:"Version",defn:g.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:F[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,S.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,_.mapOr)(e?.l?.exp,(e=>(0,r.toIsoDate)(e)),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,u.osFullName)()},{term:"CPUs",defn:(0,u.CPUs)()},{term:"System load",defn:(0,_.map)(y.CpuUsage.instance().busyPct(),(e=>(0,T.fmtPct)(e)+" busy"))??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(h.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,v.maxConcurrentImports)()} concurrent imports, ${(0,v.sharpThreadsPerProcess)()} gfx/process)`},(0,d.isWebService)()?{term:"Web uptime",defn:(0,P.fmtDuration)((0,m.runtimeMs)())}:void 0,(0,b.mapNotBlank)((0,c.procDeviceModel)(),(e=>({term:"Device",defn:e}))),{term:"Current user",defn:await(0,p.username)()+((0,T.gte0)((0,p.userid)())?"":" (userid: "+(0,p.userid)()+", groupid: "+(0,p.groupid)()+")")},(0,f.libraryHasSettings)()?{term:"Library path",defn:h.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,await(0,M.thenMap)(A(),(e=>({term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:e}))),{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,l.defaultLogLevel)()}]).filter((({term:e,defn:t})=>(0,b.notBlank)(e)&&(0,b.notBlank)(t)))}},35580:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d,h,f,m,p,g,y,v=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TaskList=t.TaskListRunLaterMs=void 0;const w=i(19851),b=i(7282),S=i(23560),P=i(88264),_=i(73568),T=i(78406),M=i(25764),E=i(99331),k=i(56038),D=i(42638),x=i(34102),C=i(70417),A=i(28874),F=i(14854),I=i(73328),O=i(69385),L=i(15674),R=i(40958),N=i(42659),B=i(45599),j=i(26905),z=i(56409),V=i(31586),W=i(94710);t.TaskListRunLaterMs=8;class U extends T.EndableInterval{constructor(){const e="TaskList()";super({name:e,callback:()=>this.maybeRunChunk(),intervalMs:7*N.secondMs,onEnd:()=>v(this,r,"m",a).call(this),rank:M.EndableRanks.first,endTimeoutMs:A.Settings.taskTimeoutMs.valueOrDefault}),r.add(this),this.recentlyProcessed=new P.TTLArray(N.minuteMs),s.set(this,[]),this.taskCount=(0,w.lazy)((()=>W.Task.count())),d.set(this,(0,w.lazy)((()=>{this.logger.debug("status",this.state())}),((0,b.isTest)()?1:30)*N.secondMs)),f.set(this,(()=>this.maybeRunChunk())),m.set(this,(0,w.lazy)((()=>this.logger.info("runChunk(): no-op",{isPaused:(0,O.isPaused)(),isFull:this.p.isFull(),isTooBusy:(0,F.isTooBusy)(),whyDoNotRun:(0,I.whyDoNotRun)(this),pendingWorkCount:this.pendingWorkCount(),queueItemCount:this.taskCount(),freeSlots:this.p.freeSlots()})),((0,b.isTest)()?1:30)*N.secondMs)),this.maybeRunChunk=(0,w.lazy)((()=>{setTimeout((()=>{this.ended||(0,E.ending)()||(v(this,r,"m",g).call(this),this.maybeRunChunk.unset())}),t.TaskListRunLaterMs)})),p.set(this,(0,w.lazy)((()=>{const e=A.Settings.minBusyPct.valueOrDefault,t=A.Settings.stuckCheckIntervalMs.valueOrDefault;if(e<=0||this.p.isIdle()||t<=0)return;const i=F.CpuUsage.instance().busyPct();if(this.logger.debug("maybeCheckForStuckTasks()",{cpuBusyPct:i,minBusyPct:e,stuckCheckIntervalMs:t}),!(0,V.gte)(i,e))for(const e of this.p.running)if(e.elapsedMs>t){const t=e.payload;this.logger.error("Stuck serial task. Aborting.",{task:t,elapsedMs:e.elapsedMs});const i="stuck after "+e.elapsedMs+"ms";t.abort(i),e.reject(new _.AbortError(i))}}),A.Settings.stuckCheckIntervalMs.valueOrDefault)),this.p=new D.Promises(e,L.maxConcurrentImports),this.p.ee.on("vacancy",this.maybeRunChunk),this.p.ee.on("drain",(()=>v(this,r,"m",l).call(this))),(0,x.ee)().on("resume",v(this,f,"f")),W.Task.ee.on("added",this.maybeRunChunk)}async awaitDrain(e=[],t=0){(0,R.isEmpty)(e)&&(e=W.TaskNames.values);const i=new z.Latch;return v(this,s,"f").push({l:i,taskNames:e,maxRemaining:t,who:(0,j.shortStack)()}),this.maybeRunChunk(),i}isRunnable(){return!this.p.isFull()}currentWorkCount(){return this.p.unsettledCount()}pendingWorkCount(){return this.taskCount()-this.currentWorkCount()}hasCapacity(e=A.Settings.taskListCap.valueOrDefault){return e<=0||this.taskCount()e.payload))}currentTasksByFn(e){return this.currentTasks().filter((t=>t.fn===e))}state(){return{...this.p.stats(),isDone:v(this,r,"m",l).call(this),freeSlots:this.p.freeSlots(),pendingWork:this.taskCount(),next10:v(this,r,"m",h).call(this,10).map((e=>e.toString())),recentlyProcessedLast10:this.recentlyProcessed.slice(-10).map((e=>e.toString())),isRunnable:this.isRunnable()}}doNotStartMoreWork(){return(0,E.ending)()||this.ended||(0,O.isPaused)()||this.p.isFull()||(0,F.isTooBusy)()||(0,I.doNotRun)(this)||0===this.pendingWorkCount()}}t.TaskList=U,s=new WeakMap,d=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,r=new WeakSet,n=function(){this.taskCount.unset()},a=async function(){(0,x.ee)().off("resume",v(this,f,"f"));const e=new _.AbortError((0,E.ending)()?"service ending":"TaskList ended");for(const t of v(this,s,"f"))t.l.reject(e);await this.p.awaitAll()},o=function(){(0,R.filterInPlace)(v(this,s,"f"),(e=>e.l.isPending())),W.Task.dbl.runf((e=>e.delete().where("retries","<",0))),v(this,r,"m",n).call(this)},l=function(){if(this.ended)return;if(v(this,r,"m",o).call(this),(0,R.isEmpty)(v(this,s,"f")))return;const e=W.Task.countTaskNames();for(const t of this.p.deferreds){const i=t.name;e[i]=(e[i]??0)+1}for(const t of v(this,s,"f"))(0,C.sum)(t.taskNames.map((t=>e[t]??0)))<=t.maxRemaining&&t.l.resolve()},u=function(){return(0,R.uniq)(this.currentTasks().filter((e=>e.isSerial)).map((e=>e.fn)))},c=function(){return this.currentTasks().map((e=>e.id))},h=function(e){return 0===e?[]:W.Task.ops().allf((t=>(t=W.Task.orderBy(t.distinct().whereNotIn("id",v(this,r,"m",c).call(this)).whereNotIn("fn",v(this,r,"m",u).call(this))),(0,V.gt0)(e)&&(t=t.limit(e)),t)))},g=function(){if(v(this,r,"m",n).call(this),v(this,p,"f").call(this),this.doNotStartMoreWork())v(this,m,"f").call(this);else{v(this,d,"f").call(this);const e=this.p.freeSlots(),t=v(this,r,"m",h).call(this,e);this.logger.debug("runChunk():",{freeSlots:e,next:t});for(const e of t)this.p.enqueue({name:this.name,payload:e,l:()=>v(this,r,"m",y).call(this,e),serialId:e.isSerial?e.fn:void 0})}v(this,r,"m",l).call(this)},y=async function(e){try{await(0,k.time)("task."+e.fn,e._run())}catch(t){this.logger.warn("Failed to run task",{task:e,error:t})}finally{this.maybeRunChunk()}},U.instance=(0,B.defer)((()=>(0,S.isTaskListManager)()?new U:void 0))},98392:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExposeArg=void 0;const r=i(28874),s=i(38639);t.ExposeArg={beforeParse:e=>e.option("--expose","The web service is only accessible to the computer running PhotoStructure by default. Providing this option will expose your library to all computers on your network. See https://photostructure.com/faq/remote-access/ ."),afterParse:e=>{(0,s.isTrue)(e.expose)&&(r.Settings.exposeNetworkWithoutAuth.envValue=!0)}}},31503:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);function o(){return(0,r.isMainService)()||(0,r.isSyncService)()}t.LogArgs={beforeParse:e=>{const t=(o()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return o()?e.option("-v, --verbose",'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!'):e.option("-v, --verbose","Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY VERY NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),o()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),r=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.envValue="trace":l?n.Settings.logLevel.envValue="debug":r?n.Settings.logLevel.envValue="info":i?n.Settings.logLevel.envValue="warn":t&&(n.Settings.logLevel.envValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.envValue=!1,n.Settings.logStdout.envValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.envValue=!0),(t||i||r||l||u)&&(n.Settings.logStdout.tmpValue=!0,o()&&(n.Settings.tailLogs.tmpValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.envValue="info"))}}},46628:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.albumsFromTags=t.tagFilesWithAlbums=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(47783),c=i(97573),d=i(42231),h=i(40958),f=i(22573),m=i(68708),p=i(75020),g=i(54993),y=(0,s.lazy)((()=>(0,n.mkLogger)("curators.AlbumTagger")));function v(e){return(0,f.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,c.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,h.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,(t=>(0,m.pluckDeep)(e,t)?.value))),i=(0,h.compact)(t.map(v));if((0,h.isEmpty)(i))return[];if(i.length>1)return y().tap({level:"info",msg:"albumFromFile()",result:i.map((e=>[p.TagRoots.Albums,...e]))});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,(t=>(0,m.pluckDeep)(e,t)?.value)),u=(0,h.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,g.toS)(n)].join(" ")),c=null==u?[p.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,m.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return y().tap({level:"info",msg:"albumFromFile()",result:(0,h.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,u.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,u.readRawTags)(i.sibling(e),!1)))}return y().tap({msg:"tagFilesWithAlbums()",result:(0,d.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w},88224:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAsset=t.tagAndUpsertAsset_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(28874),o=i(42231),l=i(40958),u=i(20214),c=i(43487),d=i(46628),h=i(63175),f=i(4407),m=i(58886),p=i(32646),g=i(48144),y=i(60047),v=i(6186),w=i(42003),b=i(43723),S=(0,r.lazy)((()=>(0,s.mkLogger)("curators.AssetTagger")));async function P({primaryVariation:e,files:t,priorTagPaths:i,capturedAts:r,uris:s}){const u=[];if(t=(0,l.uniqBy)([e,...t],(e=>e.nativePath)),a.Settings.tagCamera.valueOrDefault&&await(0,n.thenMap)((0,h.cameraTagFile)(e),(t=>{S().debug("Camera tag for "+e+":",t),u.push(t)})),a.Settings.tagLens.valueOrDefault&&await(0,n.thenMap)((0,y.lensTagFile)(e),(t=>{S().debug("Lens tag for "+e+":",t),u.push(t)})),a.Settings.tagGeo.valueOrDefault)for(const e of t){const t=await(0,p.geoTagFile)(e);if(null!=t){u.push(t);break}}await(0,n.thenMap)((0,f.dateTagFile)(e,r),(t=>{S().debug("Date tag for "+e+":",t),u.push(t)}));const c=await(0,b.whoTagFiles)(t)??[];S().debug("whoTagFiles for "+e+":",c),u.push(...c),await(0,n.thenMap)((0,g.keywordTagFiles)(t,c),(t=>{S().debug("Keyword tags for "+e+":",t),u.push(...t)})),a.Settings.tagFileType.valueOrDefault&&await(0,n.thenMap)((0,w.typeTagFiles)(t),(t=>{S().debug("MIME type tags for "+e+":",t),u.push(...t)})),await(0,n.thenMap)((0,m.tagAssetPaths)(s),(e=>{S().debug("file paths for uris",{uris:s,arr:e}),u.push(...e)})),await(0,n.thenMap)((0,d.tagFilesWithAlbums)(t),(t=>{S().debug("Album tags for "+e+":",t),u.push(...t)}));const P=(0,o.omitAncestorTags)((0,l.uniqBy)(u.map(v.normalizeTagRoot),o.joinTagPath)),_=await(0,v.tagDeltas)(i,P);return S().info("tagAsset("+e+")",{priorTagPaths:i,after:P,result:_}),_}t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();S().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map((e=>e.uri))});const i=t.find((e=>e.shown)),r=await(i?.posixFile_());if(null==i||null==r)return void S().throw("tagAndUpsertAsset(): no existing or primary asset file",{asset:e,existingPrimaryAssetFile:i,primaryVariant:r,doNotSend:!0,fatal:!1});const s=e.getShown();s?.id!==i.id&&(S().warn("Changing primary asset we're using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:s?.uri}),e.setShown_(i));const n=await(0,u.thenCollect)(t,(e=>e.posixFile_())),l=e.getAssetFiles().map((e=>e.uri)),d=e.getTagPaths(),h=await e.getCapturedAts(),f=await P({primaryVariation:r,files:n,priorTagPaths:d,capturedAts:h,uris:l});S().info("tagAndUpsertAsset",f);const m=f.add.find((e=>(0,o.leafIsExcluded)(e,a.Settings.keywordBlocklist.values)));if(null!=m){if(!0!==e.shown)return S().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:m}),await c.Asset.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),S().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:m,uris:l,files:n.map((e=>e.nativePath))});S().info("this asset has an excluded tag, marking excluded",{excludedTag:m}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(f),await e.updateFromFiles(),f},t.tagAsset=P},63175:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTagFile=t.cameraTag=void 0;const r=i(47783),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))}},4407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dateTagFile=t.dateTag=t.dayTagRef=t.monthTagRef=t.yearTagRef=t.dayToOrdinal=t.ordinalToMonth=t.monthToOrdinal=t.yearToOrdinal=void 0;const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(47783),h=i(40958),f=i(55835),m=i(31586),p=i(75020),g=i(54993),y=(0,r.lazy)((()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"}))),v=(0,r.lazy)((()=>{const e=y();return(0,h.range)(0,12,(t=>e.format(new Date(2016,t,1)))).map((e=>(0,a.stripSuffix)(e,".")))}));function w(e){return 1e4-e}function b(e){return 13-e}function S(e){return 33-e}function P(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:w(e)})))}function _(e){if((0,m.within)(1,12,e))return(0,f.map)(v()[e-1],(t=>({name:String(e),displayName:t,ordinal:b(e)})))}function T(e){return(0,n.mapGt0)(e,(e=>({name:(0,g.toS)(e),ordinal:S(e)})))}function M(e){const t=(0,g.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase();if(null==e||""===t||"off"===t||t.startsWith("disable"))return;const i=[p.TagRoots.When];if(t.startsWith("y")){const t=(0,f.map)((0,o.getYear)(e),P);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,f.map)((0,o.getMonth)(e),_);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,f.map)((0,o.getDay)(e),T);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",(()=>{y.unset(),v.unset()})),t.yearToOrdinal=w,t.monthToOrdinal=b,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=S,t.yearTagRef=P,t.monthTagRef=_,t.dayTagRef=T,t.dateTag=M,t.dateTagFile=async function(e,t){if(""===u.Settings.tagYMD.valueOrDefault)return;const i=[...t];(0,h.isEmpty)(t)&&i.push((await(0,d.readTags)(e))?.capturedAt);const r=(0,c.bestCapturedAt)(i);return null==r||(0,c.capturedAtSrcFromStat)(r.src)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:M(r.date)}},58886:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addFileUriTagsToAsset=t.addFilesTagsToAsset=t.isFsTag=t.tagAssetPaths=void 0;const r=i(19851),s=i(50213),n=i(42231),a=i(21404),o=i(40958),l=i(89937),u=i(75020),c=i(54017),d=i(94448),h=i(69032),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.FilePathTagger")));function m(e,t){return e.applyTagPathDeltas({add:(0,o.compact)(t.map((e=>(0,a.uriToTagPath)({uri:e,isFile:!0}))))})}t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(l.PS_LOCAL_FILE_SCHEME)&&null!=(0,d.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:await(0,h.displayNameForVolsha)(t)},f().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){f().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===u.TagRoots.fs},t.addFilesTagsToAsset=function(e){const t=c.AssetFile.dbl.pluckAllf((t=>t.select("uri").where({asset:e})));return m(e,t)},t.addFileUriTagsToAsset=m},32646:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTagFile=t.geoTag=void 0;const r=i(48884),s=i(56519),n=i(50213),a=i(28874),o=i(47783),l=i(14245),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)((()=>(0,n.mkLogger)("curators.GeoTagger")));function p(e){const t=a.Settings.tagGeoMaxDistanceKm.valueOrDefault;if(t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t))return void m().warn("geoTag(): GeolocationDistance too large, skipping geo tag",(0,f.pickDeep)(e,...l.GeolocationFields));const i=a.Settings.tagGeoSynonyms.synonymMap(),s=a.Settings.tagGeoTemplate.valueOrDefault.map((t=>(0,r.first)(i.get(t)??[t],(t=>(0,f.pluckDeep)(e,t)?.value)))),n=(0,c.compactBlanks)(s);return m().tap({msg:"geoTag",result:0===n.length?void 0:(0,c.compact)([u.TagRoots.Where,...n]),meta:{picked:s}})}t.geoTag=p,t.geoTagFile=function(e){return(0,s.thenMap)((0,o.readTags)(e),p)}},48144:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.keywordTagFiles=t.processKeywords=t.dedupeKeywordPaths=t.normalizeKeywordPaths=t.extractPathnameTags=t.extractDashDashTags=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(47783),h=i(97573),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),v=i(96249),w=i(55835),b=i(75020),S=i(54993),P=i(6186),_=i(43723),T=(0,s.lazy)((()=>(0,n.mkLogger)("curators.KeywordTagger"))),M=(0,s.lazy)((()=>(0,g.mapNotBlank)(c.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[ /${(0,a.escapeRegExp)(e)}]`)))));function E(e){return T().tap({msg:"extractDashDashTags()",result:(0,w.mapOr)((0,S.toS)(e).split("--")[1],(e=>(0,m.compactBlanks)((0,w.mapOr)(M(),(t=>e.split(t)),[e]))),(()=>[])),meta:{s:e}})}function k(e){return[...E(e.parent().posixPath),...E(e.name)]}(0,y.later)((()=>{c.Settings.keywordDelimiters.watchLater((()=>M.unset()))})),t.extractDashDashTags=E,t.extractPathnameTags=k;const D=/\w{2,7}:\/\/\S+/g;function x(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(D,(e=>(i.push(e),"")));s.push(...(0,w.mapOr)((0,h.delimRe)(),(t=>e.split(t)),[e]))}const n=s.map((e=>(0,o.isString)(e)?(0,h.keywordToPath)(e):e)).map((e=>Array.isArray(e)&&1===e.length?e[0]:e)),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map((e=>(0,m.compactBlanks)(e.map((e=>e.trim()))))).filter(m.isNotEmpty),d=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map((e=>e.trim())).filter((e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(d,e))),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=b.TagRoots.Keywords),e[0]!==b.TagRoots.Keywords&&(p?t.push([b.TagRoots.Keywords,...e]):y&&e.unshift(b.TagRoots.Keywords));for(const e of f)t.push([b.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function C(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(P.normalizeTagRoot),(e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]})),((e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t))))}function A(e,t){const[i,s]=(0,r.partition)(x(e),_.isWhoTag),n=(0,v.flatten)(i.map(_.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map((e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]})))),l=C([...s.filter((e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" ")))),...n]);return T().tap({msg:"processKeywords()",level:"info",result:l})}t.normalizeKeywordPaths=x,t.dedupeKeywordPaths=C,t.processKeywords=A,t.keywordTagFiles=async function(e,t){return A([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(k)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:e=>(0,u.thenMap)((0,d.readRawTags)(e),h.rawTagKeywords)})):[]],t)}},60047:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTagFile=t.lensTag=void 0;const r=i(56519),s=i(28874),n=i(47783),a=i(75020),o=i(40958),l=i(22573),u=i(55835);function c(e){return(0,u.map)(e,(e=>(0,l.mapNotBlank)(e.lensMake,(t=>(0,l.mapNotBlank)((0,o.compactBlanks)(s.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],(e=>[a.TagRoots.Lens,t,e]))))))}t.lensTag=c,t.lensTagFile=function(e){return(0,r.thenMap)((0,n.readTags)(e),c)}},6186:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagDeltas=t.normalizeTagRoot=t.stripTagRoot=t.hasTagRoot=t.Roots=t.KwRoot=t.WhereRoot=t.WhoRoot=t.AlbumsRoot=t.WhenRoot=void 0;const r=i(50213),s=i(28874),n=i(42231),a=i(75020),o=i(40958),l=i(22573),u=i(45599);t.WhenRoot={name:a.TagRoots.When,ordinal:1},t.AlbumsRoot={name:a.TagRoots.Albums,ordinal:2},t.WhoRoot={name:a.TagRoots.Who,ordinal:4},t.WhereRoot={name:a.TagRoots.Where,ordinal:5},t.KwRoot={name:a.TagRoots.Keywords,ordinal:7};const c=(0,u.defer)((()=>(0,r.mkLogger)("curators.Taggers")));t.Roots=[t.WhenRoot,t.AlbumsRoot,{name:a.TagRoots.fs,ordinal:3},t.WhoRoot,t.WhereRoot,{name:a.TagRoots.Camera,ordinal:5},{name:a.TagRoots.Lens,ordinal:6},t.KwRoot,{name:a.TagRoots.Type,ordinal:8}];const d=(0,o.uniq)([...a.TagRoots.values,...s.Settings.rootTagKeywordsAliases.values,...s.Settings.rootTagWhoAliases.values,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase())));function h(e){return d.includes((0,n.tagRefToS)(e[0]).toLowerCase())}t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const f=(0,o.uniq)([a.TagRoots.Albums,...s.Settings.rootTagAlbumsAliases.values].map((e=>e.toLowerCase()))),m=(0,o.uniq)([a.TagRoots.Keywords,...s.Settings.rootTagKeywordsAliases.values].map((e=>e.toLowerCase()))),p=(0,o.uniq)([a.TagRoots.Where,...s.Settings.rootTagWhereAliases.values].map((e=>e.toLowerCase()))),g=(0,o.uniq)([a.TagRoots.Who,...s.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));t.normalizeTagRoot=function(e){const i=(0,n.tagRefToS)(e[0]).toLowerCase();return(0,l.blank)(i)?e:m.includes(i)||m.includes(i)?[t.KwRoot,...e.slice(1)]:p.includes(i)?[t.WhereRoot,...e.slice(1)]:g.includes(i)?[t.WhoRoot,...e.slice(1)]:f.includes(i)?[t.AlbumsRoot,...e.slice(1)]:e},t.tagDeltas=async function(e,t){const i=(0,n.tagDiff)(t,e),r=(0,n.tagDiff)(e,t),a=s.Settings.excludedRootTags.valueOrDefault;return(0,o.filterInPlace)(i,(e=>{const t=a.includes((0,n.tagRefToS)(e[0]).toLowerCase());return t&&!(0,n.tagPathsInclude)(e,r)&&(r.push(e),c().info("tagDeltas(): removing excluded tag",e)),!t})),{add:i,remove:r}}},42003:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixCase=t.friendlySubtype=t.mimeTypeToTag=t.typeTagFiles=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)((()=>(0,s.mkLogger)("curators.TypeTagger")));t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))};const m=new Map(["M2TS","JPEG","QuickTime"].map((e=>[e.toLowerCase(),e])));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),(e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e])))})}t.mimeTypeToTag=p;const g=(0,r.lazy)((()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]])));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),(e=>["Raw",(0,n.capitalize)(e[1])])),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}t.friendlySubtype=y,t.fixCase=v},43723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameTag=t.isWhoTag=t.whoTagFiles=void 0;const r=i(19851),s=i(50213),n=i(28874),a=i(47783),o=i(28630),l=i(66039),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=(0,r.lazy)((()=>(0,s.mkLogger)("curators.WhoTagger")));t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,o.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,a.readRawTags)(i,!0);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,a.readRawTags)(i,!0);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(w)));return g().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map((e=>e.nativePath))}})};const y=(0,c.uniq)([m.TagRoots.Who,...n.Settings.rootTagWhoAliases.values].map((e=>e.toLowerCase())));function v(e){return y.includes((0,u.tagRefToS)(e[0]).toLowerCase())}function w(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,l.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,l.renderNameTag)(e)}t.isWhoTag=v,t.nameTag=w},98348:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const c=i(48884),d=i(19851),h=i(23560),f=i(25764),m=i(38836),p=i(99331),g=i(5916),y=i(12959),v=i(55332),w=i(91872),b=i(80632),S=i(51040),P=i(44955),_=i(15056),T=i(70025),M=i(57159),E=i(18454),k=i(28874),D=i(5233),x=i(42659),C=i(31586),A=i(68708),F=i(30976),I=i(17036),O=i(27134),L=i(35052);class R extends m.EndableWrapper{constructor(e,t){super("db.Db("+e+")",(()=>this.closeDb()),f.EndableRanks.db),r.add(this),this.schema=e,this.dbFile=t,s.set(this,0),n.set(this,void 0),this.endTimeoutMs=x.minuteMs,this.onRetry=(0,d.lazy)((()=>this.closeDb()),k.Settings.maxBusyDbMs.valueOrDefault/2),this.maxUpdatedAt=(0,d.lazy)((()=>"models"===this.schema?l(this,r,"m",a).call(this,"Asset","AssetFile","Example"):0),5*x.secondMs),this.migrate_=(0,g.lazyAsync)({desc:"db.migrate",later:async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");let i;if(await this.dbFile.isNonEmptyFile())try{await(0,O.verifyDb_)((()=>this.db))}catch(e){this.logger.warn("verifyDb failed before attempting Migration.",{error:e}),i=e}(null!=i||k.Settings.dbForceRecover.valueOrDefault)&&(E.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new I.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e}}}),this.tableInfo_=(0,d.lazy)((()=>(0,L.localTableInfo)(this.db)))}toJSON(){return(0,A.pick)(this,"schema","dbFile")}get isOpen(){return!0===l(this,n,"f")?.open}get inTransaction(){return this.isOpen&&!0===l(this,n,"f")?.inTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){var e;const t=null==l(this,n,"f");if(t||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:t});try{u(this,n,(0,b.mkdb_)({nativePath:this.dbFile.nativePath}),"f")}catch(e){throw new M.WrappedError("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return(0,h.isSyncService)()&&"INCREMENTAL"===k.Settings.dbAutoVacuumMode.valueOrDefault&&(0,C.gt0)(k.Settings.dbWalAutoCheckpoint.valueOrDefault)&&u(this,s,(e=l(this,s,"f"),++e),"f")%k.Settings.dbWalAutoCheckpoint.valueOrDefault==0&&(this.logger.info("running incremental_vacuum..."),l(this,n,"f")?.pragma("incremental_vacuum")),l(this,n,"f")}async verify_(){await(0,O.verifyDb_)((()=>this.db))}assertHeartbeat_(){const e=(0,F.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{this.logger.info("closing db",l(this,n,"f")),await(0,D.retryOnReject_)((()=>{!0===l(this,n,"f")?.open&&l(this,n,"f")?.close()}),{timeoutMs:k.Settings.dbBusyTimeoutMs.valueOrDefault,maxRetries:5,errorIsRetriable:T.isSqliteBusyError,retryDelay:x.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}u(this,n,void 0,"f")}async vacuum(){try{await(0,w.handleDbRetries_)("db.checkpoint",(()=>this.db),(()=>(0,O.checkpoint_)({db:this.db})),this.onRetry),await(0,w.handleDbRetries_)("db.optimize",(()=>this.db),(()=>this.db.pragma("OPTIMIZE")),this.onRetry),await(0,w.handleDbRetries_)("db.vacuum",(()=>this.db),(()=>this.db.exec("VACUUM")),this.onRetry)}catch(e){throw this.logger.warn("vacuum(): failed",{error:e}),e}}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,O.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}localBackupDir(){return(0,_.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,P.isDirSQLiteReadWrite)(e),s=(i?e:this.localBackupDir().join((0,y.filestamp)())).join(this.dbFile.base);return await l(this,r,"m",o).call(this,s),i||await(0,v.dbBackupCold_)(s,e),e.join(this.dbFile.base)}}t.Db=R,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=function(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,S.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,c.max)(t)},o=async function(e){await e.parent().mkdirp_(),await this.db.backup(e.nativePath,{progress:e=>(this.logger.log((0,p.ending)()?"info":"debug","backup() "+(0,C.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed"),(0,p.ending)()?1e3:100)})}},25470:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.DbModelJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const c=i(66364),d=i(50213),h=i(23560),f=i(78406),m=i(25764),p=i(38836),g=i(99331),y=i(56038),v=i(12959),w=i(55332),b=i(76187),S=i(73209),P=i(28874),_=i(42659),T=i(75240),M=i(95700),E=i(22526),k=i(45648),D=5*_.minuteMs;t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class x extends f.EndableInterval{static for(e){return new x(e.db,e.fslock,e.libraryDbFile,e.libraryDbBackupDir)}constructor(e,t,i,o){super({name:"db.DbModelJanitor",callback:()=>l(this,r,"m",n).call(this),intervalMs:P.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:_.minuteMs,rank:m.EndableRanks.db,endTimeoutMs:5*_.minuteMs,onEnd:()=>l(this,r,"m",a).call(this)}),r.add(this),this.db=e,this.dbFslock=t,this.libraryDbFile=i,this.libraryDbBackupDir=o,this.logger=(0,d.mkLogger)(this.name),this.fslockRelease=new p.EndableWrapper("db.DbModelJanitor.fslockRelease",(()=>this.dbFslock.release()),m.EndableRanks.postdb,D),s.set(this,0),this.dbFslock.tryAcquire_()}get useReplica(){return!this.db.dbFile.eql(this.libraryDbFile)}forceBackup_(){return this.backup_(!0)}async backup_(e=!1){return await(0,S.withLock_)({file:this.libraryDbBackupDir,timeoutMs:5*_.minuteMs,noopIfContested:!e},(async()=>{if(e&&u(this,s,0,"f"),(0,k.hasDbSetupErrors)())return this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:(0,k.dbSetupErrors)()}),t.NoOp;if(!await this.dbFslock.tryAcquire_())return this.logger.info("backup_(): no-op: someone else has the fslock",{me:this.dbFslock.lockfile?.base,owner:(await this.dbFslock.selfAndSiblingNames_())[0]}),t.NoWriteLock;l(this,r,"m",o).call(this)||await(0,M.runMaintenanceTasks)();const i=this.db.maxUpdatedAt();return null!=i&&i>l(this,s,"f")?(0,y.time)("db.DbModelJanitor.backup_()",(async()=>{l(this,r,"m",o).call(this)?this.logger.info("backup_(): posthaste: skipping vacuum"):await this.db.vacuum(),u(this,s,i,"f");const e=this.libraryDbBackupDir.join((0,v.filestamp)()),t=await this.db.backup_(e,!this.useReplica);return this.useReplica&&await(0,w.dbBackupCold_)(t,this.libraryDbFile.parent()),this.logger.info("backup_(): backup successful",{destDbFile:t}),t})):(this.logger.info("backup_(): no update to the db since last backup",{ago:(0,T.fmtDuration)(Date.now()-l(this,s,"f"))}),t.NoOp)}))??t.Contested}}t.DbModelJanitor=x,s=new WeakMap,r=new WeakSet,n=async function(){try{await this.backup_()}catch(e){this.logger.error("backup_() failed",{error:e})}},a=async function(){const e=S.FsLock.for({file:this.libraryDbFile.sibling("db-teardown"),timeoutMs:D,endableRank:m.EndableRanks.postdb,noopIfContested:!1});(0,h.isDbManager)()&&await e.withLock_((async()=>{if(await this.dbFslock.iAmOnly_({vacuum:!0})){if(this.logger.info("#teardown(): I'm the last one in. Running backup and cleanup."),await this.backup_(),this.useReplica){const e=[(0,E.libraryDbInfoFromDbFile)(this.libraryDbFile),...(0,b.sqliteFiles)(this.db.dbFile)];this.logger.info("#teardown(): Removing replica artifacts",{victims:e});for(const t of e)await t.unlink()}}else this.logger.info("#teardown(): no-op: other processes are still running")})),await this.db.closeDb()},o=function(){return this.ended||(0,g.ending)()||(0,c.isSuspended)()}},35758:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelRepair=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(71567),o=i(98314),l=i(38835),u=i(18454),c=i(28874),d=i(63870),h=i(64526),f=i(14611),m=i(74085),p=i(22526),g=i(45648),y=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelRepair")));t.dbModelRepair=async function(){return{...await async function(){const e=h.Library.instance();if(null==e)throw new Error("No library set."+l.NoLibraryErrorFlag);const t=await e.dbModelJanitor();if(null==t)throw new Error("No library set (missing dbModelJanitor)."+l.NoLibraryErrorFlag);(0,g.clearDbSetupErrors)();const i=await(0,m.dbModelHealthCheck)().refresh();if(y().info("dbModelRepair: health check result: ",i),c.Settings.dbForceRecover.valueOrDefault)u.HealthCheck.addLoadingMsg("PS_DB_FORCE_REPAIR was set. Trying to repair.");else if("ok"!==i.level)u.HealthCheck.addLoadingMsg(`Database health check failed: ${i.msg}. Trying to repair.`),c.Settings.dbForceRecover.envValue=!0;else try{return u.HealthCheck.addLoadingMsg("Backing up the library database..."),await t.forceBackup_(),u.HealthCheck.addLoadingMsg("Validating the library database..."),await t.db.verify_(),u.HealthCheck.addLoadingMsg("No repair needed: maintenance tasks, backup, and integrity tests ran without error."),y().tap({msg:"dbModelRepair()",level:"info",result:{noop:!0,op:"validated"}})}catch(e){u.HealthCheck.addLoadingMsg(`Maintenance, backup, or integrity tasks failed: ${(0,o.errorToS)(e)}. Trying to repair.`),c.Settings.dbForceRecover.envValue=!0}(0,n.isWebService)()&&a.StdoutWrite.shutdownSync();const r=await e.dbFsLock();if(!await r.acquire_({timeoutMs:2*(0,d.commandTimeoutMs)(),releaseOnFailure:!1}))return y().throw("Failed to acquire exclusive lock on the library database. Shut down other processes before retrying.");try{await(0,p.assertValidDbInfo_)()}catch(e){u.HealthCheck.addLoadingMsg(`Library database setup was invalid: ${(0,o.errorToS)(e)}. Resetting and restarting.`),await(0,p.libraryDbInfoJsonFile)().unlink(),c.Settings.dbForceRecover.envValue=!0}await(0,f.restartLibrary_)();const s=c.Settings.dbForceRecover.valueOrDefault;return c.Settings.dbForceRecover.unset(),y().tap({msg:"dbModelRepair()",level:"info",result:{op:s?"repaired":"restarted",noop:!1}})}(),state:(await u.HealthCheck.rerunSetup()).state}}},22526:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelSetup_=t.assertValidDbInfo_=t.libraryDbInfoFromDbFile=t.libraryDbInfoJsonFile=t.fsLockForDb=t.libraryDbObjects_=void 0;const r=i(19851),s=i(50213),n=i(92407),a=i(55332),o=i(44955),l=i(15056),u=i(87290),c=i(98314),d=i(38835),h=i(73209),f=i(95696),m=i(17217),p=i(18454),g=i(57902),y=i(28874),v=i(2858),w=i(40958),b=i(22573),S=i(42659),P=i(94448),_=i(98348),T=i(45648),M=(0,r.lazy)((()=>(0,s.mkLogger)("db.DbModelSetup")));function E(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+d.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+d.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+d.NoLibraryErrorFlag);const i=(0,l.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,l.dbBackupDir)(i)}}function k(e){return h.FsLock.for({file:e,timeoutMs:0,noopIfContested:!1})}function D(e=y.Settings.libraryDir.valueOrDefault){const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dir"+d.NoLibraryErrorFlag);return x((0,l.pathToDb)(t,"models"))}function x(e){return e.sibling("db-info.json")}async function C(e=D(),t){try{const i=await e.readJson(g.LogLevels.info);if(null==i)throw new Error(e+" is missing"+d.DbSetupErrorFlag);if(null!=t&&!await t.equalsUri_(i.uri))throw new Error(e+" expects the live db to be "+i.uri+" but the live db is "+await t.uri_()+d.DbSetupErrorFlag);const r=await f.PosixFile.forUri(i.uri);if(null==r)throw new Error(e+" expects the live db to be "+i.uri+" but that URI cannot be resolved."+d.DbSetupErrorFlag);try{await(0,o.assertDirSQLiteReadWrite_)(r.parent())}catch(t){throw M().error("assertValidDbInfo_(): failed to assert live dir was r/w",{error:t,liveDbFile:r,infoJsonFile:e}),new Error("Failed to validate that the live database directory, "+r.dir+", was read-writable by SQLite: "+(0,c.errorToS)(t)+d.DbSetupErrorFlag)}return{liveDbFile:r}}catch(e){throw(0,T.addDbSetupError)(e),e}}t.libraryDbObjects_=E,t.fsLockForDb=k,t.libraryDbInfoJsonFile=D,t.libraryDbInfoFromDbFile=x,t.assertValidDbInfo_=C,t.dbModelSetup_=async function(e=y.Settings.libraryDir.valueOrDefault){const{libraryDbFile:t,fslock:i,libraryDbBackupDir:r}=await async function(e=y.Settings.libraryDir.valueOrDefault){const t=E(e);return{...t,fslock:k(t.libraryDbFile)}}((0,b.mapNotBlank)(e,m.toNativePath_));let s,o;await i.tryAcquire_();const u=x(t);try{if(await(0,h.withLock_)({file:u,timeoutMs:5*S.minuteMs},(async()=>{const i=await u.readJson(g.LogLevels.info);if(s=i?.useReplica,null!=i){const{liveDbFile:e}=await C(u,t);o=new _.Db(l.Schemas.models,e)}if(null==s||null==o){const i=await(0,n.getLiveDbDir_)(e),r=await i.db.uri_();s=i.useReplica,s&&await p.HealthCheck.traceLater_("Setting up local replica database",(0,a.dbBackupCold_)(t,i.db.parent())).catch((e=>M().throw("Failed to set up replica db"+d.DbSetupErrorFlag,{src:t,dest:i.db,error:e}))),o=new _.Db(l.Schemas.models,i.db),await u.writeJson_({uri:r,useReplica:s})}})),null==o||null==s)return M().throw("Failed to open model db"+d.DbSetupErrorFlag+d.InternalErrorFlag,{libraryDir:e});if(await i.tryAcquire_()){const e=await o.migrate_();s&&(e.repaired||(0,w.isNotEmpty)(e.appliedMigrations))&&await o.backup_(t.parent(),!s),(0,T.clearDbSetupErrors)()}P.modelDb.set(o)}catch(e){throw M().error("Failed to set up model db",{error:e}),(0,T.addDbSetupError)(e),i.release(),e}return M().tap({msg:"dbModelSetup()",result:{db:o,useReplica:s,libraryDbFile:t,libraryDbBackupDir:r,fslock:i}})}},86859:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(54557),s=i(50213),n=i(99331),a=i(56038),o=i(65753),l=i(66184),u=i(70417),c=i(28874),d=i(40958),h=i(22573),f=i(45599),m=i(96249),p=i(31586),g=i(51926),y=i(57038),v=i(21074),w=(0,f.defer)((()=>(0,s.mkLogger)("db.DbRequest")));t.DbRequest=class{constructor(e,t){this.db=e,this.tableName=t,this.cachedStatements=new r.FifoCache(256)}qb(){return(0,y.knex)()(this.tableName)}prep(e,t=!1){const i=(0,v.toSqlQuery)(e);try{const r=this.cachedStatements.getOrSet(this.db().db.__uid+":"+(!0===t?"pluck:":"")+i.sql,(()=>{const e=this.db().prepare(i.sql);return!0===t?e.pluck():e}));return r.database.open?{sq:i,stmt:r}:(this.cachedStatements.clear(),this.prep(e,t))}catch(e){return w().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}wrap({q:e,pluck:t,m:i}){try{const{sq:r,stmt:s}=this.prep(e,t);c.Settings.logSql.valueOrDefault&&w().log((0,l.defaultLogLevel)(),i+"(): "+(0,v.sqlQueryToS)(r));const n=s[i].bind(s);return null==r.bindings?n():n(r.bindings)}catch(t){if(!0===t.message?.includes("AdvisoryLock"))throw t;w().throw(t,{method:i,...(0,v.toSqlQuery)(e)})}}run(e){return this.wrap({q:e,m:"run"})}runScript(e,t=""){const i=(0,a.mkElapsed)("db.runScript()");for(const r of e){if((0,h.blank)(r)||r.trim().startsWith("--"))continue;this.run({sql:r});const e=(0,g.replaceAll)((0,g.ellipsize)(r,60),t,"");i.elapsed(e)}}mapRun(e){return e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return null==t.bindings?i.run():i.run(t.bindings)}))}runf(e){return this.wrap({q:e(this.qb()),m:"run"})}upsert(e){const t=(0,v.toSqlQuery)(e(this.qb()));return t.sql=t.sql.replace(/^(?:update|insert)\b/i,(e=>e.toUpperCase()+" OR REPLACE ")),this.wrap({q:t,m:"run"})}first(e){return this.wrap({q:e,m:"get"})}firstf(e){return this.wrap({q:e(this.qb()),m:"get"})}mapAll(e){return(0,m.flatten)(e.map((e=>{const{sq:t,stmt:i}=this.prep(e);return i.all(t.bindings)})))}all(e){return this.wrap({q:e,m:"all"})}allf(e){return this.wrap({q:e(this.qb()),m:"all"})}async batched(e){let t,i=0;do{t=this.wrap({q:e.qb(this.qb(),t).limit((0,o.maxBatchPluckSize)()),m:"all"}),(0,d.isNotEmpty)(t)&&(await e.onResults(t),i+=t.length)}while((0,d.isNotEmpty)(t)&&!(0,n.ending)()&&(null==e.maxResults||e.maxResults>i));return{resultCount:i,done:null==t||t.length<(0,o.maxBatchPluckSize)()}}pluckFirst(e){return this.wrap({q:e,pluck:!0,m:"get"})}pluckFirstf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"get"})}pluckAll(e){return this.wrap({q:e,pluck:!0,m:"all"})}pluckAllf(e){return this.wrap({q:e(this.qb()),pluck:!0,m:"all"})}async pluckBatched(e){let t=0;const i=(0,u.min)([e.limit??(0,o.maxBatchPluckSize)(),e.maxResults]);if(i<=0||(0,p.lte0)(e.maxResults))return{done:!1,resultCount:t};let r;for(;null==e.maxResults||e.maxResults<=0||t(0,o.mkLogger)("db.DbSchemaValid")));function y(e){return l.PosixFile.for(s.default.join(u.ProjectPath.Data(),e+"-schema.json"))}t.schemaJsonFile=y,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,p.localTableInfo)(e.db),i=t.map((e=>e.tableName)),r=(await y(e.schema).readJson_()).tableInfo;{const e=r.map((e=>e.tableName)),t=(0,c.diff)(e,i);(0,c.isNotEmpty)(t)&&g().throw("Db is missing "+(0,f.plur)(t.length,"table")+": "+(0,h.andList)(t))}for(const e of t){const t=r.find((t=>t.tableName===e.tableName));if(null==t)g().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,c.isNotEmpty)(i)&&g().throw("Db is missing "+(0,f.plur)(i.length,"column")+" from table "+e.tableName+": "+(0,h.andList)(i.map((e=>e.name))))}}g().info("Validated schema.",{from:(0,d.shortStack)()})}catch(e){throw(0,m.dbModelHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return y(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",tableInfo:(0,p.localTableInfo)(t)},{spaces:2})}},45648:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addDbSetupErrorListener=t.hasDbSetupErrors=t.clearDbSetupErrors=t.addDbSetupError=t.dbSetupErrors=t._dbSetupErrors=void 0;const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[];t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)}},36908:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dedupeTags_=t.mergeTags_=void 0;const r=i(19851),s=i(50213),n=i(81168),a=i(42231),o=i(40958),l=i(76790),u=i(23838),c=i(31586),d=i(54993),h=(0,r.lazy)((()=>(0,s.mkLogger)("db.DedupeTags")));function f(e,t){function i(t){return e.prepare(t).run()}(0,o.isEmpty)(t)&&h().warn("mergeTags(): empty tagIds",{tagIds:t}),h().info("mergeTags() starting",{tagIds:t});const r=e.prepare("SELECT id, _path, parentId FROM Tag WHERE id IN ("+t.join(",")+") ORDER BY ID").all(),s=(0,o.compactBlanks)(r.map((e=>(0,a.tagPathLeaf)(e._path))).sort()),n=r[0],l=r.slice(1),u=n?.id;if((0,o.isEmpty)(s)||(0,o.isEmpty)(l)||null==n||!(0,c.gt0)(u))return void h().warn("mergeTags(): missing winner",{winner:n,winnerId:u,leafs:s,losers:l});const d=(0,a.splitTagPath)(n._path).slice(0,-1),f=[...d,s[0]];n._path=(0,a.joinTagPath)(f),n.parentId=0===d.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,a.joinTagPath)(d))??n.parentId,h().info("mergeTags()",{winner:n,losers:l,winnerTagPath:f,leafs:s});const m=l.map((e=>e.id)).join(",");i(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${m})`),i(`DELETE FROM AssetTag WHERE tagId in (${m})`),i(`DELETE FROM Tag WHERE id in (${m})`),e.prepare("UPDATE Tag SET parentId = :parentId, _path = :path WHERE id = :id").run({parentId:n.parentId,path:n._path,id:u});const p=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:u,like:n._path+"%"});for(const t of p){const i=(0,a.splitTagPath)(t._path).slice(f.length),r=(0,a.joinTagPath)([...f,...i]);t._path!==r&&(h().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return h().tap({msg:"mergeTags()",level:"info",result:{winner:n,losers:r}})}t.mergeTags_=f,t.dedupeTags_=function(e){const t=new u.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,n.stripSuffix)((0,d.toS)(r).trim(),a.TagSep).toLowerCase().normalize(),i);const i=(0,l.sortBy)(t.entriesArray().filter((([,e])=>e.length>1)),(([e])=>[-(0,n.countChars)(e,a.TagSep),-e.length,e]));for(const[,t]of i)f(e,t)}},57038:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstMigratedAt=t.knex=void 0;const s=r(i(31832)),n=i(19851),a=i(56519),o=i(55835),l=i(68708);t.knex=(0,n.lazy)((()=>(0,s.default)({client:"better-sqlite3",useNullAsDefault:!0}))),t.firstMigratedAt=async function(e){return(0,a.thenMap)(e("migrations").min("migration_time").first(),(e=>(0,o.map)((0,l.values)(e)[0],(e=>new Date(e)))))}},17036:function(e,t,i){"use strict";var r,s,n,a=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0;const o=i(77598),l=i(19851),u=i(50213),c=i(7282),d=i(37805),h=i(4867),f=i(51040),m=i(77740),p=i(38835),g=i(8769),y=i(57159),v=i(34102),w=i(73209),b=i(95696),S=i(43899),P=i(18454),_=i(28874),T=i(40958),M=i(42659),E=i(41400),k=i(98553),D=i(55835),x=i(34666),C=i(32639),A=i(45648),F=i(94715),I=i(27134);t.Migration=class{constructor(e,t,i){r.add(this),this.schema=e,this.db=t,this.dbFile=i,this.fsMigrations_=(0,l.lazy)((()=>this.migrationsDir.children_((e=>e.isFile&&e.basename.endsWith(".sql"))).catch((e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+p.InternalErrorFlag,{error:e}))))),this.ensureMigrationTable_=(0,l.lazy)((()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")})),this.unknownMigrations_=(0,l.lazy)((()=>this.migrationsInDatabase_().filter((e=>!(0,x.lt)((0,F.migrationNameToDate)(e),d.gitDate))))),this.assertKnownMigrations_=(0,l.lazy)((()=>{const e=this.unknownMigrations_();if((0,T.isNotEmpty)(e)){const t=new y.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,g.onError)(t),t}})),this.logger=(0,u.mkLogger)("db.Migration("+(0,k.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=b.PosixFile.for(S.ProjectPath.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter((t=>!e.includes(t.name)))}migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}async apply_(e){return(0,w.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:_.Settings.dbMaintenanceTimeoutMs.valueOrDefault},(()=>a(this,r,"m",s).call(this,e)))}async applyMigration_(e,t){try{const i=Date.now(),s=F.Migrations[e.name.replace(/^[\d_-]+/,"")],o=(0,C.isFunction)(s);return o?await s.bind(F.Migrations)(this.db):await a(this,r,"m",n).call(this,e),this.logger.info("applyMigration() completed",{elapsedMs:Date.now()-i,codeMigration:o,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,v.ee)().emit("clearDbCache")}}},r=new WeakSet,s=async function(e){try{this.ensureMigrationTable_(),(0,c.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const r of await this.pendingMigrationFiles_())await P.HealthCheck.traceLater_("Upgrading database ("+r.name+")",(async()=>{if((0,m.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,m.getDevEnvFlag)("PS_SLOMO")&&await(0,E.delay)((0,o.randomInt)(M.secondMs,3*M.secondMs)),await(0,D.map)(e,(e=>e(r))),await(0,h.thenOrTimeoutError)({p:this.applyMigration_(r,i),timeoutMs:5*_.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch((e=>{throw new y.WrappedError("Migration "+r.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})}))})),t.push(r.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new y.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,A.addDbSetupError)(t),P.HealthCheck.addError(t),t}},n=async function(e){const t=e.name.includes("_nofk");try{const i=await e.readTextFile(),r=(0,f.splitBatchSql)(i);if((0,T.isEmpty)(r))this.logger.info("No-op migration: "+e);else{t&&this.db.pragma("foreign_keys = OFF");for(const t of r)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}t&&(0,I.foreignKeyCheck_)(this.db)}}finally{t&&this.db.pragma("foreign_keys = ON")}}},94715:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.isoToPrecisionMs=t.fix_root_tags=t.tag_path_suffix=t.migrationNameToDate=t.plucklabmodeb6=t.lowercase_psnet_function=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(97352),o=i(68852),l=i(81168),u=i(85810),c=i(42022),d=i(1971),h=i(79842),f=i(89724),m=i(17415),p=i(88600),g=i(20014),y=i(42231),v=i(87001),w=i(40958),b=i(55835),S=i(31586),P=i(97790),_=i(89937),T=i(54993),M=i(7656),E=i(36908),k=(0,s.lazy)((()=>(0,n.mkLogger)("db.Migrations"))),D=new RegExp(`^(${(0,o.escapeRegExp)(_.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function x(e,t){return(0,a.mapGt0)(e,(()=>(0,b.map)(function(e,t=c.ModeBits){return(0,g.splitBits)(e,t).map((e=>(0,u.unlabhash)(e,t)))}(e,6)[t],(e=>(0,u.toLabhash)(e,c.ModeBits)))))}function C(e){return e.endsWith(y.TagSep)?e:e+y.TagSep}function A(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())k().warn("fix_root_tags(): broken tag",{broken:t}),(0,l.countChars)(t._path,y.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)}function F(e){return(0,b.map)((0,h.isoToDated)(e),h.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(l.isString).flatMap((e=>D.exec(e))).map((e=>e[1].toLowerCase()+e[2])).getOrElse((()=>e)),t.plucklabmodeb6=x,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map((e=>(0,S.toInt)(e)));return(0,p.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=C,t.fix_root_tags=A,t.isoToPrecisionMs=F,t.Migrations={fix_root_tags:A,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},f.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},m.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},F),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtLocal bigint"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtOffset integer"),e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtPrecisionMs integer"),e.exec("UPDATE AssetFile SET capturedAtLocal = isoToLocal(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtOffset = isoToOffsetMinutes(capturedAtISO)"),e.exec("UPDATE AssetFile SET capturedAtPrecisionMs = isoToPrecisionMs(capturedAtISO)"),e.exec("DROP INDEX asset_captured_at_geohash_idx"),e.exec("DROP INDEX assetfile_exifuid_idx"),e.exec("CREATE INDEX assetfile_capturedAtLocal_idx ON AssetFile(capturedAtLocal)")},spread_modes:e=>{e.function("plucklabmodeb6",{deterministic:!0},x),(0,S.times)(d.ModeCount,(t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`))),e.exec("UPDATE AssetFile SET "+(0,S.times)(d.ModeCount,(e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`)).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},v.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,T.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,(e=>[e.shown,e.version,e.updatedAt])),o=n.filter((e=>e.id!==a?.id));i.push(...o.map((e=>e.id)))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:E.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},C),(0,E.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all();k().info("normalize_tag_paths():",{badTags:t});for(const i of t){const t=(0,y.normalizeTagPath)(i._path);(0,E.mergeTags_)(e,(0,w.compact)([i.id,...e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t)]))}},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter((e=>null!=t.exec(e)));k().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:M.rebuildTagAssetCounts,create_tag_fts:e=>{e.exec("DROP TABLE IF EXISTS tag_fts"),e.exec("CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize=\"unicode61\");")},rebuild_null_island:e=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,y.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")}}},27134:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairDbFile_=t.checkpoint_=t.verifyDbFile_=t.verifyDb_=t.foreignKeyCheck_=t.integrityCheck_=t.quickCheck_=t.backupDbFile_=t.sqlite=void 0;const r=i(14121),s=i(19851),n=i(50213),a=i(84777),o=i(12959),l=i(5531),u=i(91872),c=i(99315),d=i(76187),h=i(51040),f=i(38835),m=i(57159),p=i(29882),g=i(95696),y=i(89966),v=i(38156),w=i(28874),b=i(63870),S=i(5233),P=i(42659),_=i(41400),T=i(50357),M=i(98553),E=i(56409),k=i(31586),D=i(20214),x=i(51926),C=i(12168),A=i(59455),F=i(54993),I=i(94448),O=i(9508),L=(0,s.lazy)((()=>(0,n.mkLogger)("db.SQLite")));function R({db:e,pragma:t,okResult:i}){L().debug("pragmaOrThrow_()",{db:N(e),db_open:e?.open,pragma:t,okResult:i});const r=(0,x.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,T.eql)(r,i)||L().throw(`${t} failed for ${N(e)}: ${(0,M.stringify)({result:r})}`)}function N(e){return(0,p.ellipsizePath)({p:e.name,maxLength:80})}function B(e){return R({db:e,pragma:"quick_check",okResult:"ok"})}function j(e){return R({db:e,pragma:"integrity_check",okResult:"ok"})}function z(e){const t=(0,A.toA)(e.pragma("foreign_key_check"));t.length>w.Settings.dbInvalidFKThreshold.valueOrDefault&&L().throw("foreignKeyCheck_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:w.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)L().warn("repairDbFile_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,h.dbValueToEscapedString)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function V(e){await(0,u.handleDbRetries_)("db.quickCheck",e,B),await(0,_.delay)(1),await(0,u.handleDbRetries_)("db.integrityCheck",e,j),await(0,_.delay)(1),await(0,u.handleDbRetries_)("db.foreignKeyCheck",e,z)}function W(e){return(0,O.withDbSync)(e,V,(0,b.commandTimeoutMs)())}t.sqlite=async function({dbFile:e,sql:t,args:i}){const s=await(0,y.sqliteNativePath_)(),n=await(0,r.thenElapsed)((0,a.stdout_)(s,[...(0,A.toA)(i),e.nativePath,t],{timeoutMs:1*P.minuteMs}));return L().debug("sqlite("+t+") on "+e+" in "+n.elapsedMs+"ms",n.result),n.result},t.backupDbFile_=function(e,t){return(0,S.retryOnReject_)((()=>async function(e,t){try{await t.parent().mkdirp_(),await t.unlink("trace");const i=await e.size();if(!(0,k.gt0)(i))return void L().warn("backupDbFile_(): "+e+" is empty");await((0,I.modelDb)()?.end()),await(0,O.withDb)(e,(async e=>e.exec("VACUUM INTO "+(0,h.dbValueToEscapedString)(t.nativePath))),2*P.minuteMs),L().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new m.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t)),{maxRetries:3,retryDelay:P.secondMs,timeoutMs:P.minuteMs,errorIsRetriable:()=>!0})},t.quickCheck_=B,t.integrityCheck_=j,t.foreignKeyCheck_=z,t.verifyDb_=V,t.verifyDbFile_=W,t.checkpoint_=async function e({db:t,retries:i=3,checkpointType:r=w.Settings.dbWalCheckpointType.valueOrDefault}){if((r=l.CheckpointTypes.getCI(r)??l.CheckpointTypes.AUTO)===l.CheckpointTypes.AUTO)return;const s="wal_checkpoint("+r+")",[n]=(0,A.toA)(t.pragma(s));return L().info("checkpoint()",{pragma:s,result:n}),(0,k.gt0)(n?.busy)&&i>0?(await(0,_.delay)(250),e({db:t,retries:i-1})):n};const U=/no such table: sqlite_\w+/i;t.repairDbFile_=async function(e,t=c.RepairModes.dump){const i=g.PosixFile.for(e),r=(await i.parent().join("db-"+t,(0,o.filestamp)()).mkdirp_()).join(i.base);L().info(`repairDbFile_(${i} -> ${r})`);try{const e=await(0,y.sqliteNativePath_)(),s=4*Math.min(20*C.MiB,await(0,d.sqliteSizeBytes)(i)),n=new v.PushProgressObserver({path:(0,F.toS)(i),op:"Repairing your database"},s),o=new E.Latch,l=(0,a.execFile)(e,[i.nativePath,"."+t],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});l.stdout.on("error",(e=>{const i=(0,F.toS)(e);U.test(i)?L().info("repairDbFile_(): ignoring stderr",{err:i}):o.reject(new Error("sqlite "+t+" failed: "+i))}));const u=(0,a.execFile)(e,[r.nativePath],5*P.minuteMs,{encoding:"buffer",maxBuffer:s});u.on("exit",(()=>o.resolve())),l.stdout.on("end",(()=>{u.stdin.end(null)})),l.stdout.on("data",(e=>{const t=e.length;n.incrProgress(t),u.stdin.write(e)})),await o,L().info(`repairDbFile_(): recovered to ${r}.`),await W(r),L().info(`repairDbFile_(): ${r} is valid, finishing repair.`);const c=await(0,D.thenCollect)((0,d.sqliteFiles)(i),(e=>e.renameYMDHMS_({subdir:"needed-repair"})));return await(0,D.thenCollect)((0,d.sqliteFiles)(r),(e=>e.mv_(i.parent()))),c.find((e=>".db"===e.ext||e.ext.startsWith(".sqlite")))}catch(e){return L().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+f.FatalErrorFlag,{error:e})}}},21074:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlWhereInClause=t.isQueryBuilder=t.sqlQueryToS=t.toSqlQuery=t.isSqlQuery=void 0;const r=i(48884),s=i(68852),n=i(81168),a=i(12943),o=i(96249),l=i(98553),u=i(31586),c=i(68708),d=i(32639),h=i(54993);function f(e){return null!=e&&(0,n.isString)(e.sql)&&(null==e.bindings||(0,a.isDbValued)(e.bindings))}t.isSqlQuery=f,t.toSqlQuery=function(e){if(null==e)throw new Error("null sql");if(f(e))return e;if((0,n.isString)(e))return{sql:e};if((0,d.isFunction)(e.toSQL))return(0,c.omit)(e.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+(0,l.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,o.flatten)((0,r.zip)(e.sql.split("?"),e.bindings.map((e=>(0,l.stringify)(e))))).join("");{let t=e.sql;for(const i of(0,c.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,s.escapeRegExp)(i),"gi"),(0,h.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,d.isFunction)(e?.where)&&(0,d.isFunction)(e?.limit)},t.sqlWhereInClause=function(e){return"("+(0,u.times)(e,(()=>"?")).join(",")+")"}},35052:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localTableInfo=t.parseTableInfo=void 0;const r=i(22573),s=i(23838);function n(e){const t=new s.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,r.blank)(i.name)||(0,r.blank)(i.type)||t.add(i.tableName,{name:i.name,type:i.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===i.notnull,pk:1===i.pk});return t.entriesArray().map((([e,t])=>({tableName:e,columns:t})))}t.parseTableInfo=n,t.localTableInfo=function(e){return n(e.prepare("SELECT \nm.tbl_name as tableName,\np.*\nFROM sqlite_master AS m\nJOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid").all())}},9508:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDb=t.withDbSync=void 0;const r=i(80632),s=i(28874),n=i(30301),a=i(54993);t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)((()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i})));try{return t((function(){const e=o();return e.open?e:o.refresh()}))}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const n=(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i});try{return await t(n)}finally{n.close()}}},74085:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbModelHealthCheck=void 0;const r=i(77740),s=i(98314),n=i(18454),a=i(28874),o=i(82950),l=i(42659),u=i(45599),c=i(64526),d=i(16185),h=i(45648),f=i(31687),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.dbModelHealthCheck=(0,u.defer)((()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library database…",settings:["libraryDir","forceLocalDbReplica"],timeoutMs:()=>10*a.Settings.dbMaintenanceTimeoutMs.valueOrDefault,ttlMs:l.minuteMs,onReset:()=>(0,h.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837"}],later:async()=>{const e=await(c.Library.instance()?.ready);if(null==e)return{level:"disabled",msg:["Library database tests disabled: no library is open"]};let t,i=!1;try{const s=Date.now();if(i=!1,(0,h.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,o.li)((0,h.dbSetupErrors)())],links:[m]};if(t=await e.modelDb(),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await(0,d.assertValidDbSchema_)(t),i=!0,await t.verify_(),await t.vacuum(),f.Heartbeat.assertPing_();const n=await e.dbModelSetup_();return{level:"ok",msg:["Library database is OK",(0,o.li)(["Schema validation, vacuum, optimize, and upsert round-trip took "+(Date.now()-s)+"ms","Live db is "+(0,o.tt)(t.dbFile.nativePath),"Local replica mode is "+(0,o.tt)(n.useReplica),n.useReplica?"Cold library db is "+(0,o.tt)(n.libraryDbFile):void 0])]}}catch(r){return{level:"error",msg:["Library database validation failed",(i?"":"Unrecoverable: ")+(0,s.errorToS)(r),null==t?void 0:"Live db is "+(0,o.tt)(t.dbFile.nativePath),null==e?void 0:"Local replica mode is "+(0,o.tt)(await e.useReplica())],links:i?[m]:void 0}}}});return(0,h.addDbSetupErrorListener)((()=>e.refresh())),e}))},8400:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(19851),s=i(88625),n=i(2858),a=i(74085),o=i(1991),l=i(40549);t.libraryHealthCheckSetup=(0,r.lazy)((async()=>{await(0,n.readSettings)(),(0,s.healthCheckSetup)(),(0,o.syncHealthCheck)(),(0,a.dbModelHealthCheck)(),(0,l.volumeUuidHealthCheck)()}))},1991:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncHealthCheck=void 0;const r=i(48884),s=i(50213),n=i(95696),a=i(62105),o=i(18454),l=i(2858),u=i(40958),c=i(82950),d=i(45599),h=i(94019),f=(0,d.defer)((()=>(0,s.mkLogger)("health.SyncHealthCheck")));t.syncHealthCheck=(0,d.defer)((()=>o.HealthCheck.for({section:"Library",id:"library-nothing-to-sync",ordinal:99,settings:["scanAllDrives","scanPaths","scanLibraryFirst","scanLibraryLast"],pendingMsg:"Checking synced directories…",later:async()=>{if(!(0,l.libraryHasSettings)())return{level:"disabled",msg:"Library sync paths test disabled: no library is open"};const e=(await(0,h.pathsToSync)()).map((e=>e.nativePath));if((0,u.isEmpty)(e))return{level:"warn",msg:"No paths are configured to scan\n"+(0,c.li)([(0,c.tt)("PS_SCAN_ALL_DRIVES")+" is false",(0,c.tt)("PS_SCAN_PATHS")+" is empty","both "+(0,c.tt)("PS_SCAN_LIBRARY_FIRST")+" and "+(0,c.tt)("PS_SCAN_LIBRARY_LAST")+" are false"]),links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]};{const t=e.map((e=>n.PosixFile.for(e)));return f().info("Checking if any paths are empty",{posixFiles:t}),null==await(0,r.findAsync)(t,(async e=>null!=await e.someDescendant((e=>e.isDirectorySync()||(0,a.acceptParentAndFileAndSimple)(e)),1)))?{level:"warn",msg:["No eligible files found in scanned paths","Checked paths:",(0,c.li)(e.map(c.tt))],links:[{text:"Read more",url:"https://photostructure.com/go/nothing-to-scan"}]}:{level:"ok",msg:["At least one directory with eligible files is configured to be synced","Checked paths:",(0,c.li)(e.map(c.tt))]}}}})))},40549:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=void 0;const r=i(50213),s=i(56519),n=i(18454),a=i(28874),o=i(2858),l=i(85087),u=i(63870),c=i(86848),d=i(7014),h=i(40958),f=i(82950),m=i(45599),p=i(57924),g=i(23838),y=i(68708),v=i(94019),w=(0,m.defer)((()=>(0,r.mkLogger)("health.VolumeUUIDHealthCheck")));t.volumeUuidHealthCheck=(0,m.defer)((()=>n.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumes…",settings:["scanAllDrives"],links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],later:async()=>{if(!(0,o.libraryHasSettings)())return{level:"disabled",msg:"Volume UUID test disabled: no library is open"};const e=[],t=[];if(a.Settings.scanAllDrives.valueOrDefault)e.push(...await(0,d.volumes)());else{const i=await(0,v.scanPaths)(),r=await(0,s.mapAsyncSerial)({name:"scannedVolumes",arr:i.result.map((e=>e.nativePath)),f:e=>(0,d.bestVolumeForPath)(e),timeoutMs:(0,u.commandTimeoutMs)()});e.push(...(0,h.uniqBy)(r,(e=>e.mountpoint))),t.push(...i.noUriPaths)}const i=[...(0,g.groupBy)(e,(e=>e.uuid)).values()].filter((e=>e.length>1)),r=e.filter((e=>null==e.uuid&&!(0,c.volumeUuidNotExpected)(e))).map((e=>e.mountpoint)),n=(await(0,d.volumes)()).filter((e=>!1===e.ok)).map((e=>(0,h.compactBlanks)([e.mountpoint,e.status]).join(": ")));if(w().debug("volumeHealthCheck result",{missingUUIDs:r,noUriPaths:t,unhealthyVolumes:n,scannedVolumes:e.map((e=>(0,y.pick)(e,"uuid","mountpoint")))}),(0,h.isEmpty)(r)&&(0,h.isEmpty)(i)&&(0,h.isEmpty)(t)&&(0,h.isEmpty)(n))return(0,h.isEmpty)(e)?{msg:["No volumes need UUIDs",(0,f.tt)(a.Settings.scanAllDrives.key)+" is false, and no volumes other than the library are configured to be scanned."],level:"ok"}:{msg:["All scanned volume UUIDs are OK",(0,f.li)(e.map((e=>(0,f.tt)((0,l.volsha)(e.uuid)+" → "+e.mountpoint))))],level:"ok"};{const e=[];return(0,h.isEmpty)(n)||e.push("Some volumes are unhealthy",(0,f.li)(n.map((e=>(0,f.tt)(e))))+"PhotoStructure may crash or hang when accessing unhealthy volumes."),(0,h.isEmpty)(r)||e.push("Some volumes are missing UUIDs",(0,f.li)(r.map((e=>(0,f.tt)(e)))),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(i)||e.push("Some volumes have duplicate UUIDs",i.map((e=>(0,f.li)((0,p.andList)(e.map((e=>(0,f.tt)(e.mountpoint))))+" share UUID "+(0,f.tt)(e[0].uuid)))).join("\n---\n"),"This can cause problems with deduplication and library portability."),(0,h.isEmpty)(t)||e.push("Some paths failed to have URIs generated",(0,f.li)(t.map((e=>(0,f.tt)(e)))),"This will prevent these paths from being imported."),{level:"warn",msg:e.join("\n---\n"),links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}})))},43487:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const u=i(48884),c=i(19851),d=i(50213),h=i(88158),f=i(45393),m=i(56519),p=i(89724),g=i(38835),y=i(74128),v=i(79847),w=i(28874),b=i(47783),S=i(38010),P=i(40958),_=i(76790),T=i(75761),M=i(38639),E=i(11371),k=i(98553),D=i(55835),x=i(31586),C=i(20214),A=i(59455),F=i(64526),I=i(4407),O=i(54017),L=i(48722),R=i(37094),N=i(45295),B=i(39604),j=i(48723),z=i(41507),V=i(72761),W={"Asset.shown":1,"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null};class U extends V.TimestampedModel{constructor(){super(...arguments),r.add(this),this.attrs={},this.assetIdish=(0,c.lazy)((()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}))),this.mergedTags=(0,c.lazy)((async()=>{const e=[];for(const t of this.getAssetFiles()){const i=await t.posixFile(),r=await(0,b.readTags)(i),s=await(i?.mtimeMs());null!=i&&null!=r&&null!=s&&e.push({...r,SourceFile:i.nativePath,sourceModifiedTime:s,sourceIsPrimary:(0,M.isTrue)(t.shown)})}const t=R.AssetRevision.ops().allf((e=>e.where({assetId:this.id}))),i=new S.MergedTags("Asset:"+this.id);return i.addTag(...e,...this.assetFiles),i.addRevision(...t),i}))}static shownUnhidden(e){return null==e?s.query().where(W):e.andWhere(W)}static findUnhiddenById(e){return(0,x.gt0)(e)?s.ops().firstf((t=>s.shownUnhidden(t.where({id:e})))):void 0}static shownRemovable(e,t){return(t??s.query()).whereNotNull(e).andWhere({"Asset.shown":1})}static shownCount(){return s.ops().count(s.shownUnhidden().countDistinct("Asset.id"))}static deletePreviews(e){return F.Library.instance().previews().ap(e).deleteAll()}static async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const r=(0,d.mkLogger)("Asset("+e+").remove()"),n=s.ops().findById(e);if(null==n)return void r.warn("asset not found");const a=n.isActive(),o=n.tagIds();r.info("starting",{unlinkAssetFiles:i});const l=n.getAssetFiles({refresh:!0});if(t){(0,B.upsertToShaBlockslist)(...l.map((e=>e.sha)));for(const e of l)(0,y.syncReport)().onProgress({from:"Asset.remove",path:await e.getNativePath()??e.uri,state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}N.AssetTag.dbl.runf((t=>t.delete().where({assetId:e}))),O.AssetFile.dbl.runf((t=>t.delete().where({assetId:e}))),R.AssetRevision.dbl.runf((t=>t.delete().where({assetId:e}))),s.dbl.runf((t=>t.delete().where({id:e}))),a&&j.Tag.deltaAssetCountAndAncestors(o,-1);try{await s.deletePreviews(e)}catch(e){r.error("Failed to delete previews",{error:e})}return{deletedMeta:i?await(0,v.trashOrUnlinkFileUris_)(l):[],assetFileMeta:l}}static nextOutdated(e=h.identity){return this.ops().findOne(e(l(this,s,"m",n).call(this)))}static nextOutdateds(e){return this.ops().all(e(l(this,s,"m",n).call(this)))}static outdatedCount(e=h.identity){return this.dbl.pluckFirst(e(l(this,s,"m",n).call(this)).count())}static findFirstByFile(e){return this.ops().findOne(e(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")))}static unshownAssetIds(){return this.dbl.pluckAll("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL")}static archive(e){null!=s.ops().findById(e)&&(N.AssetTag.dbl.runf((t=>t.where({assetId:e}).delete())),O.AssetFile.dbl.runf((t=>t.where({assetId:e}).delete())),s.dbl.runf((t=>t.where({id:e}).delete())))}markUnshownAndUpsert(){this.shown=!1,this.version=f.AssetVersion,this.upsert()}markShownAndUpsert_(e){const t=this.getShown()?.id;if(null!=e){const t=e.shown;this.setShown_(e,{skipUpsert:!0}),!0!==t&&e.upsert()}this.shown=!0,this.version=f.AssetVersion,t!==this.getShown()?.id&&(this.updateCount=(this.updateCount??0)+1),this.upsert()}async updateFromFiles(){const e=await this.mergedTags();(0,D.map)(e.get("rating"),(e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value}))}isActive(){return(0,x.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||(0,x.gte)(this.rating,w.Settings.rejectRatingsLessThan.valueOrDefault))}toAssetId(){return(0,L.toAssetId)(this)}renderCaption(e){return(0,D.map)(this.capturedAtLocal,(t=>"Taken "+(0,p.fmtLocalDateShort)(t,e)))}async whenApiTag(){const e=(0,I.dateTag)((0,p.localToDateObject)(this.capturedAtLocal));return null==e?void 0:j.Tag.findOrCreate(e).toApiTag()}findAssetFileByUri(e){return this.getAssetFiles()?.find((t=>t.uri===e))}addAssetFile(e){(0,P.filterInPlace)(e.asset?.assetFiles??[],(t=>!(t.id===e.id||t.uri===e.uri))),e.assetId=this.id,e.asset=this,e.shown=!1,this.getAssetFiles().push(e),this.clear(),this.capturedAtLocal??(this.capturedAtLocal=e.capturedAtLocal),this.rating??(this.rating=e.rating),this.durationMs??(this.durationMs=e.durationMs)}async assetFileForFile_(e,t){const i=await e.uri();if(null==i)return this.logger().throw("assetFileForFile_(): null uri",{f:e});const r=this.getAssetFiles().find((e=>e.uri===i));if(null!=r)return r;const s=new O.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}static getTags(e){return j.Tag.ops().all(j.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map((e=>e.id))??N.AssetTag.dbl.pluckAllf((e=>e.select("tagId").where({assetId:this.id})))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??(this.tags=s.getTags(this.id))}tagPaths(){return this.getTags().map((e=>e.path.join("/"))).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,u.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter((e=>!t.includes(e))),r=t.filter((t=>!e.includes(t)));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:j.Tag.findOrCreateByPathN(e.add??[]).map((e=>e.id)),tagIdsToRemove:j.Tag.findByPathN(e.remove??[]).map((e=>e.id))})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,P.uniq)((0,A.toA)(e.tagIdsToAdd).filter((e=>(0,x.gt0)(e)&&!t.includes(e)))),r=(0,P.uniq)((0,A.toA)(e.tagIdsToRemove).filter((e=>(0,x.gt0)(e)&&t.includes(e))));if((0,P.isEmpty)(i)&&(0,P.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&j.Tag.deltaAssetCountAndAncestors(t,-1),(0,P.isEmpty)(i)||N.AssetTag.dbl.runf((e=>e.insert(i.map((e=>({assetId:this.id,tagId:e})))).onConflict(["assetId","tagId"]).ignore())),(0,P.isEmpty)(r)||N.AssetTag.dbl.runf((e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete())),this.tags=void 0;const s=(0,P.uniq)([...t,...i]).filter((e=>!r.includes(e)));return this.isActive()&&j.Tag.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().info("getStreams(): fetched tags "+t,{limit:e});const i=t.map((t=>t.getAssetStream(this,e)));this.streams=(0,z.coalesceStreams)((0,P.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}getBeforeAfterId(){const e=s.dbl.all(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId"));this.afterId=e.find((e=>e.assetId>this.id)),this.beforeId=e.reverse().find((e=>e.assetIde.path))}getAssetFiles({refresh:e=!1}={}){return null!=this.id&&(e&&(this.assetFiles=void 0),this.assetFiles??(this.assetFiles=(0,_.sortBy)(O.AssetFile.ops().findBy({assetId:this.id}),(e=>[!(0,M.isTrue)(e.shown),-e.mtime])))),this.assetFiles??[]}setShown_(e,t){e instanceof O.AssetFile&&(this.getAssetFiles(),this.assetFiles?.some(((t,i)=>{const r=t.id===e.id||t.uri===e.uri;return r&&(this.assetFiles[i]=e),r})));const i=e instanceof O.AssetFile?e.id:e;if(this.getShown()?.id===i)return void this.logger().debug("setShown_(): no-op, already set",{afId:i});this.logger().info("setShown_()",{assetId:this.id,assetFileId:i}),(0,x.gt0)(this.id)&&(0,x.gt0)(i)||this.logger().throw("setShown_(): invalid IDs: "+(0,k.stringify)({assetId:this.id,assetFileId:i})+g.InternalErrorFlag);const r=Date.now();O.AssetFile.dbl.runf((e=>e.update({shown:0,updatedAt:r}).where({assetId:this.id}))).changes<=0&&this.logger().warn("setShown_(): all asset files were already unshown",{afId:i});const s=O.AssetFile.dbl.runf((e=>e.update({shown:1,updatedAt:r}).where({id:i})));1!==s.changes&&this.logger().throw("setShown_(): failed to update asset file: unexpected changed rows",{runResult:s});const n=this.assetFiles?.find((e=>e.id===i))??this.getAssetFiles({refresh:!0}).find((e=>e.id===i));if(null!=n){this.capturedAtLocal=n.capturedAtLocal,this.rating=n.rating,this.durationMs=n.durationMs;for(const e of this.assetFiles??[])e.shown=e.id===i;!0!==t?.skipUpsert&&this.upsert()}else this.logger().throw("setShown_(): failed to find shown asset file",{af:e})}getShown(e){return this.getAssetFiles(e)?.find((e=>(0,M.isTrue)(e.shown)))??this.getAssetFiles({refresh:!0})?.find((e=>(0,M.isTrue)(e.shown)))}getShownNativePath(){return this.getShown()?.getNativePath()}async getCapturedAts(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.capturedAt()))}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,T.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption(),...this.attrs}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id);await(0,m.thenMap)(r.readInfo(),(async e=>{e.mimetype.startsWith("video/")&&(this.poster=await r.posterLink())}));const s=!0;this.imgAttrs.set(t,await r.imgAttrs(t,s,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,E.ReducerNames.fit),...this.attrs}}isVideo(){if(null==this.assetFiles)throw new Error(".video called before getFiles()");return this.assetFiles.some((e=>e.isVideo))}videoAttrs(){return{controls:!0,autoplay:!0,poster:this.poster,...this.attrs}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some((e=>e.type===i.mimetype))||await i.exists()&&(t??(t=i),e.push({src:(0,T.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some((e=>"video/mp4"===e.type))||null==t||e.unshift({src:(0,T.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getPosixFiles(){return(0,C.thenCollect)(this.getAssetFiles(),(e=>e.posixFile_()))}async getExistingAssetFiles(){return(0,m.filterAsync)({name:"getExistingAssetFiles",arr:this.getAssetFiles(),f:e=>e.exists()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return;const i=(0,A.toA)(O.AssetFile.ops().findBy({assetId:this.id,uri:t}))[0];return(0,D.orElse)(i,(async()=>{const t=new O.AssetFile;return t.asset=this,t.assetId=this.id,await t.setFile_(e),t}))}partialSimpleAsset(){return{assetId:this.id,liked:(0,x.gte)(this.rating,w.Settings.likeRating.valueOrDefault),hidden:(0,M.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=U,s=U,r=new WeakSet,n=function(){return s.shownUnhidden().andWhere("Asset.version","<",f.AssetVersion)},a=function(){return this.beforeId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]))},o=function(){return this.afterId=s.dbl.first(s.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount"}).andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]))},U.$tableName="Asset",U.$uniqueColumnName="id",U.$booleanFields=["shown","hidden"]},54017:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const a=i(76760),o=i(19851),l=i(88158),u=i(45393),c=i(68852),d=i(81168),h=i(13991),f=i(54296),m=i(56519),p=i(76490),g=i(89724),y=i(98314),v=i(38835),w=i(8769),b=i(29882),S=i(95696),P=i(62105),_=i(74128),T=i(35721),M=i(69589),E=i(28874),k=i(28544),D=i(16170),x=i(45200),C=i(34238),A=i(87001),F=i(42233),I=i(21404),O=i(40958),L=i(17586),R=i(22573),N=i(38639),B=i(42659),j=i(33374),z=i(50357),V=i(75240),W=i(11371),U=i(55835),q=i(31586),H=i(68708),G=i(34666),$=i(89937),J=i(75020),K=i(64526),Y=i(41844),X=i(43487),Z=i(48723),Q=i(94710),ee=i(72761);class te extends ee.TimestampedModel{constructor(){super(...arguments),r.add(this),this.uriObj=(0,o.lazy)((()=>C.URI.parse(this.uri))),this.whyRejected=(0,o.lazy)((async()=>{const e=await this.posixFile_();return null==e?"invalid URI":!0===await this.isFileDeleted()?"deleted":(0,P.whyRejectFile)(e)})),this.posixFile_=(0,o.lazy)((async()=>S.PosixFile.for(await this.getNativePath())))}static outdatedQuery(e){let t=X.Asset.shownUnhidden(e.q).join("AssetFile","AssetFile.assetId","Asset.id").where("AssetFile.version","<",u.AssetFileVersion);return null!=e.maxUpdatedAt&&(t=t.andWhere("AssetFile.updatedAt","<",e.maxUpdatedAt)),t.andWhere((t=>{(0,O.isNotEmpty)(e.mountpoints)&&(t=t.whereIn("AssetFile.mountpoint",e.mountpoints));for(const i of e.uris)t=t.orWhereLike("AssetFile.uri",i+"%");return t})).orderBy("AssetFile.id")}static async nextOutdated(e=l.identity){return this.ops().findOne(e(this.outdatedQuery(await(0,F.currentVolumeRoots)())))}static async outdatedCount(e=l.identity){const t=this.outdatedQuery(await(0,F.currentVolumeRoots)());return this.dbl.pluckFirst(e(t.count("AssetFile.id")))}static shownAssetFileId(e){return this.dbl.pluckFirstf((t=>t.where({assetId:e,shown:1}).limit(1)))}static primaryForAssetId(e){return(0,q.gt0)(e)?te.ops().first(X.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.shown":1})):void 0}static shownUnhidden({uriRoot:e}={}){let t=X.Asset.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,R.blank)(e)||(t=t.andWhereLike("AssetFile.uri",e+"%")),t}static recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return this.dbl.pluckAll(te.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}static assetFileCountByMimeType(e){const t=te.shownUnhidden({uriRoot:e}).select("mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("mimetype").orderBy("mimetype");return this.dbl.all(t)}static assetFileCountWithMimeType(e,t){let i=te.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("mimetype",e+"%"):i.andWhere("mimetype",e),this.dbl.first(i)}static assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map((e=>({mimeTypeRoot:e,assetFileCount:te.assetFileCountWithMimeType(e,t)?.assetFileCount??0})))}static children(e,t){const i=this.query().whereLike("uri",e+"/%").andWhere("uri","regexp",`^${(0,c.escapeRegExp)(e)}/[^/]+$}`);return this.ops().all(null==t?i:t(i))}static async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().allf((e=>e.where({sha:t,fileSize:i}).andWhereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))):void 0}static sameAssetFileInLibrary(e){return this.ops().allf((t=>t.where((0,H.pick)(e,"sha","fileSize")).andWhere((e=>e.whereLike("uri",$.PS_LIBRARY_PROTOCOL+"%"))).andWhere((t=>t.whereNot({id:e.id})))))}librarySiblings(){return this.getAsset()?.getAssetFiles().filter((e=>e.id!==this.id&&e.uri.startsWith($.PS_LIBRARY_PROTOCOL)))}capturedAtLocale(e){return(0,g.fmtLocalDateShort)(this.capturedAtLocal,e)}get dominantColors(){return p.DominantColor.fromModeData(this)}set dominantColors(e){(0,H.assignAllFields)(this,p.DominantColor.toModeData(e))}get posixPathFromGrandparent(){return(0,U.map)(this.uriObj()?.fsPath,b.posixPathFromGrandparent)}async whyNotMatchesFile(e){const t=n(this,r,"m",s).call(this);if(null!=t)return t;if(null==this.fileSize||null==this.mtime)return"missing file metadata";if(null!=e){const t=await e.uri();if(null==t)return"file has no URI";if(!await(0,A.uriIsEquivalent)(this.uri,t))return"file URI mismatch"}try{const t=e??await this.posixFile_();if(!await t.exists())return"file is missing";const i=await this.fileFields_(t);return null==i?!0===await(t?.isDeleted())?"file is deleted":"file is unreadable":i.fileSize!==this.fileSize?"file size changed since last sync":(0,q.closeTo)(i.mtime,this.mtime,2*B.secondMs)?void 0:"file mtime changed since last sync"}catch(e){return(0,y.errorToS)(e)}}async matchesFile(e){const t=await this.whyNotMatchesFile(e);return this.logger().tap({level:"info",msg:"matchesFile()",result:null==t,meta:{whyNot:t}})}async whyNotInSyncWithFile(e){return E.Settings.forceSync.valueOrDefault?E.Settings.forceSync.key+"=true":this.version!==u.AssetFileVersion?"AssetFileVersion: "+this.version+" != "+u.AssetFileVersion:this.whyNotMatchesFile(e)}async inSyncWithFile(e){const t=await this.whyNotInSyncWithFile(e);return this.logger().tap({msg:"inSyncWithFile()",result:null==t,meta:{whyNotInSync:t}})}async fileFields_(e){const t=e??await this.posixFile_();return null==t?void 0:await(0,h.assetFileStatFields_)(t)}isInLibrary(){return this.uri.startsWith($.PS_LIBRARY_PROTOCOL)}async isNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){const t=await this.whyNotNoop(e);return this.logger().tap({msg:"isNoop()",result:null==t,meta:{whyNotNoop:t}})}async whyNotNoop(e={forceSync:E.Settings.forceSync.valueOrDefault}){if(!0===e.forceSync)return"forceSync is true";if(!(0,q.gt0)(this.id))return"missing .id";if(!(0,q.gt0)(this.assetId))return"missing .assetId";{const e=await this.whyNotInSyncWithFile();if(null!=e)return e}if(await(0,Y.mayCopyAssetsToLibrary)()){const e=K.Library.instanceRequired_().assetFileRepository(),t=e.whyNotCopyFile(await this.posixFile_());if((0,R.blank)(t)&&null==await e.existingLibraryAssetFile(this))return"need to copy into library"}this.syncState=_.AssetFileSyncStates.noop}isVersionUpToDate(){return(0,G.gte)(this.version,u.AssetFileVersion)}async siblingCount(){return te.dbl.pluckFirstf((e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id})))}async upsertIfNeeded_(e,t=(0,M.forceContextOrSetting)()){if(null!=e&&await this.setFile_(e),await this.matchesFile()&&(0,q.gt0)(this.id)&&!t.forceSync)return void(null==this.syncState&&(this.upsert(),this.syncState??(this.syncState=_.AssetFileSyncStates.noop)));const i=await this.isFileDeleted();if(!0===i)return this.syncState=_.AssetFileSyncStates.deleted,this.delete(),!0!==t.skipAssetRepair&&Q.Task.addOne("repairAsset",{assetId:this.assetId}),this;if(!1===i){const i=await this.updateFromFile_(e,t);return this.syncState??(this.syncState=null==i?_.AssetFileSyncStates.noop:_.AssetFileSyncStates.synced),this.upsert()}return this.syncState??(this.syncState=_.AssetFileSyncStates.skipped),this}async updateFileFields_(e){(0,H.assignFields)(this,await this.fileFields_(e))}async updateFromFile_(e,t=(0,M.forceContextOrSetting)()){const i=Date.now(),r=this.logger().addContext(".updateFromFile_()");if(null!=this.id&&!0!==t.forceSync&&await this.matchesFile(e))return void r.info("updateFromFile() no-op: up-to-date version and file stat matches since last update");if(null!=e&&await this.setFile_(e),null==e&&(e=await this.posixFile_()),null==e||await e.clear().notExists())return this.syncState=_.AssetFileSyncStates.deleted,void r.info("no-op, "+e+" is missing");const s=await(0,h.mkAssetFile_)(e);return s.uri!==this.uri&&((0,R.blank)(this.uri)||!0===this.uri?.startsWith("file:"))&&(this.logger().warn("updateFromFile() upgrading uri",{prior:this.uri,new:s.uri}),this.uri=s.uri),(0,H.assignAllFields)(this,(0,H.omit)(s,"uri")),this.version=u.AssetFileVersion,this.syncState=_.SyncFileStates.synced,r.elapsed("finished",Date.now()-i,this.toJSON()),this}async updateFromShaSibling_(e){const t=n(e,r,"m",s).call(e);if(null==t){if(await this.exists())return this.logger().debug("updateFromShaSibling",e),null!=e.sha&&await e.matchesFile()&&this.sha===e.sha?((0,H.assignFields)(this,(0,H.omit)(e,"id","posixFile","uriObj","shown","uri","mtime","fileSize","mountpoint","createdAt","updatedAt","updateCount",...te.$transientFields)),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing")}else this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t})}getAsset(){return this.asset??(this.asset=(0,q.gt0)(this.assetId)?X.Asset.ops().findById(this.assetId):void 0)}exists(){return(0,x.uriExists)(this.uri,this.mountpoint)}async isFileDeleted(){return(await this.posixFile_())?.isDeletedUri(this.uri)}async accepted(){return(0,R.blank)(await this.whyRejected())}async setFile_(e){const t=await e.uri_();if(null==t)return this.logger().throw("setFile(): no URI for "+e);const i=await e.mountpoint();if(null!=this.uri&&!await(0,A.uriIsEquivalent)(t,this.uri))return this.logger().throw("setFile(): cannot reassign non-equivalent URI",{prior:this.uri,new:t,file:e.nativePath});const r=await e.uriObject_();return null==r?this.logger().throw("failed to create URI for "+e):(this.uri=t,this.uriObj.set(r),this.mountpoint=i?.nativePath,this.nativePath=e.nativePath,this.posixFile_.set(Promise.resolve(e)),this)}get basename(){return(0,R.blank)(this.uri)?void 0:decodeURIComponent(this.uri.slice(this.uri.lastIndexOf("/")+1))}posixFile(){return this.posixFile_().catch((()=>{}))}async getNativePath(){return(0,R.blank)(this.nativePath)&&(null==this.uri?this.logger().error(".getNativePath() called before .setFile_()"+v.InternalErrorFlag):this.nativePath=await(0,f.getAssetFileNativePath)(this)),this.nativePath}async capturedAt(){return null==this.nativePath&&await this.getNativePath(),k.CapturedAt.fromAssetFile(this)}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=await this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmpty()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:e?`Download ${i.base}`:(0,T.mkDownloadableTitle)(i,"original",this.isVideo?"video":"image",{width:this.width,height:this.height}),basename:i.base,description:"Download original",details:`(${(0,j.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=await this.posixFile_();if(null==i)return[];const r=e.ap(this.assetId),s=[];if(await(0,m.thenMap)(this.originalDownloadable(),(e=>s.push(e))),this.isVideo)return s;if(!(0,N.isTrue)(this.shown)&&this.sha!==t)return s;const n=(0,O.compact)(await Promise.all([...await r.previewInfos()].reverse().filter((e=>e.reducer===W.ReducerNames.fit)).map((e=>(0,T.previewToDownloadable)(i.base,e)))));return s.push(...(0,O.uniqBy)(n,(e=>e.size))),s}catch(e){return(0,w.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=C.URI.parse(this.uri),t=(0,U.map)((0,I.uriToTagPath)({uri:e,isFile:!0}),(e=>Z.Tag.findByPath(e)));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",e)}}async _pathInfo_(e){const t=await this.posixFile_();if(null==t)return this.logger().throw("pathInfo(): no posixFile",{uri:this.uri});const i=t.nativePath,r=C.URI.parse(this.uri),s=await t.exists();if(null==e||(0,O.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:a.sep,exists:s};function n(){return(0,L.at)((0,L.at)(e,-1)?.tagPath,-1)}(0,z.eql)(e[0]?.tagPath,[J.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===$.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,d.equalsIgnoreCase)(n(),(0,L.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&n()===J.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===$.PS_LOCAL_FILE_SCHEME){const t=C.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:n(),thisVolSha:t}),n()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:n()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:a.sep,exists:s}})}async toApi(e,t){return(0,m.thenMap)(this.pathInfo(),(async i=>(0,H.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,shown:(0,N.isTrue)(this.shown),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,t),createdAtLocale:ie(this.createdAt),updatedAtLocale:ie(this.updatedAt)})))}get isVideo(){return(0,D.isVideoMimeType)(this.mimetype)}}function ie(e){return(0,U.map)(e,(e=>(0,V.fmtDuration)(Date.now()-e,1)+" ago"))}t.AssetFile=te,r=new WeakSet,s=function(){if((0,R.blank)(this.uri))return"blank uri";if((0,R.blank)(this.sha))return"blank sha";if(!(0,q.gt0)(this.width))return"missing width";if(!(0,q.gt0)(this.height))return"missing height";if(!(0,q.gt0)(this.capturedAtLocal))return"missing capturedAtLocal";if(!(0,q.gte0)(this.capturedAtPrecisionMs))return"missing capturedAtPrecisionMs";if(E.Settings.useImageHashes.valueOrDefault){const e=[];for(const t of["dctHash","diffHash","meanHash"])(0,R.blank)(this[t])&&e.push(t);if(1===e.length)return"missing image hash: "+e[0];if(e.length>1)return"missing image hashes: "+e.join(", ")}return this.isVersionUpToDate()?void 0:"outdated version"},te.$tableName="AssetFile",te.$uniqueColumnName="uri",te.$booleanFields=["shown"],te.$transientFields=["nativePath","syncState"]},48722:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=void 0;const r=i(76596),s=i(31586);t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n}},37094:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static insert(...e){return a.ops().insert(e.map((e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)}))))}get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a,a.$tableName="AssetRevision"},69853:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setAssetRotation_=void 0;const r=i(50213),s=i(39250),n=i(66778),a=i(69589),o=i(40958),l=i(45599),u=i(98553),c=i(31586),d=i(21605),h=i(43487),f=i(94710),m=(0,l.defer)((()=>new s.LastOneInWins("Asset")));t.setAssetRotation_=async function(e,t,i){if(!(0,c.gt0)(e))throw new Error("invalid asset "+(0,u.stringify)(e));if(!(0,d.isRotation)(t))throw new Error("setRotation("+t+"): invalid rotation "+(0,u.stringify)(t));return m().enqueue({key:e,fn:s=>async function(e,t,i,s){const c=Date.now(),d=(0,r.mkLogger)("setAssetRotation("+(0,u.stringify)({assetId:e,rotation:t})+")"),m=h.Asset.ops().findById(e);if(null==m)return d.throw("Unknown assetId:"+e);const p=(0,l.defer)((()=>{f.Task.addOne("repairAsset",{assetId:e})}));d.throwIfAborted_(s);const g=m.getAssetFiles();if(null==m.getShown())return p(),d.throw("No primary asset file for Asset "+e+". Trying to repair.",{doNotSend:!0,fatal:!1,retriable:!1});const y=await i.ap(e).smallestFileForReducer("fit");if(null==y)return p(),d.throw("Missing previews for Asset "+e+". Trying to repair.",{doNotSend:!0,fatal:!1,retriable:!1});const v=[];for(const e of g)try{const i=await e.posixFile();if(null==i||await i.notExists()){d.info("cannot rotate variation: file is missing",{f:i,af:e});continue}if(d.throwIfAborted_(s),null==await(0,n.matchAndWriteRotation_)(y,i,t)){d.info("cannot rotate variation: matchRotation() failed",{f:i,af:e});continue}v.push(await e.upsertIfNeeded_(i.clear(),(0,a.forceContextOrSetting)({forceSync:!0})))}catch(t){d.warn("failed to update asset file",{af:e,error:t})}return(0,o.compact)(v),(0,o.isNotEmpty)(v)&&await i.apb(e,g,{forceRebuildPreviews:!0}).build_(),d.info("setRotation("+t+"): completed.",{elapsedMs:Date.now()-c,updatedAssetFiles:v}),v}(e,t,i,s)})}},45295:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{$pk(){return this.assetId+":"+this.tagId}}t.AssetTag=s,s.$tableName="AssetTag",s.$uniqueColumnName="assetId,tagId",s.$useCache=!1,s.$pkColumnNames=["assetId","tagId"]},61204:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeMonthTag=t.normalizeDateTags=t.getMonthTags=void 0;const r=i(19851),s=i(50213),n=i(97352),a=i(75020),o=i(4407),l=i(48723),u=`'${a.TagRoots.When}' || char(31) || '%' || char(31) || '%' || char(31)`,c=u+" || '%' || char(31)",d=(0,r.lazy)((()=>(0,s.mkLogger)("model.DateTagNormalizer")));function h(){return l.Tag.ops().allf((e=>e.whereNotNull("ordinal").andWhereRaw("_path LIKE "+u+" AND _path NOT LIKE "+c).limit(2400)))}function f(e){const t=(0,n.mapGt0)(e.ordinal,(e=>(0,o.monthTagRef)((0,o.ordinalToMonth)(e))));null==t?d().warn("failed to fix tag (no monthTagRef)",{t:e}):t.name!==e.name&&(d().info("Fixing month name",{tagRef:t,tag:e}),e.changeName(t.name)),e.maybeUpsertDisplayName(t?.displayName)}t.getMonthTags=h,t.normalizeDateTags=async function(){for(const e of h())f(e)},t.normalizeMonthTag=f},31687:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(38835),s=i(42659),n=i(31586),a=i(72761);class o extends a.TimestampedModel{static ping(e){return o.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){if(null==o.db())throw new Error("no library is open"+r.NoLibraryErrorFlag);try{o.ping(e);const t=o.ops().findOneBy({name:e});if(null==t||t.name!==e||(0,n.lt)(t.updatedAt,Date.now()-20*s.secondMs))throw new Error("Heartbeat row wasn't inserted")}finally{try{o.dbl.runf((t=>t.delete().where({name:e})))}catch{}}}}t.Heartbeat=o,o.$tableName="Heartbeat",o.$uniqueColumnName="name",o.$useCache=!1},95700:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runMaintenanceTasks=void 0;const r=i(19851),s=i(56038),n=i(28874),a=i(42659),o=i(41400),l=i(69032),u=i(61204),c=i(49796);t.runMaintenanceTasks=async function({force:e}={}){await d(),await(!0===e?h.refresh():h());try{await(!0===e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)())}catch{}};const d=(0,r.lazy)((()=>(0,s.time)("db.normalizeDateTags",u.normalizeDateTags))),h=(0,r.lazy)((()=>(0,s.time)("db.Progress.vacuum",(()=>c.Progress.vacuum()))),2*a.hourMs);(0,o.later)((()=>{n.Settings.libraryDir.watchLater((()=>{d.unset(),h.unset()}))}))},55046:(e,t,i)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const s=i(57975),n=i(50213),a=i(7282),o=i(65211),l=i(40958),u=i(38639),c=i(45599),d=i(31586),h=i(68708),f=i(34666),m=i(54993),p=i(57038),g=i(94448),y=i(33572),v=i(63872);class w{constructor(){this.$instanceId=(0,a.isTest)()?(0,o.uid)():void 0}static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,p.knex)()(this.$tableName)}static queryBy(e){return this.query().where(e)}static queryOneBy(e){return this.queryBy(e)}static ops(){return this._ops??(this._ops=new v.ModelOps(this,this.db))}static get dbl(){return this.ops().dbl}static rows(){return this.ops().rows()}static truncate(){if((0,a.isProd)())throw new Error("rejecting attempt to truncate in prod");this.dbl.run("DELETE FROM "+this.$tableName)}static ucn(e){const t=this.$uniqueColumnName.split(",").map((t=>e[t]));return t.some((e=>null==e))?void 0:1===t.length?t[0]:t.join(",")}static hasId(e){return this.$pkColumnNames.every((t=>null!=e[t]))}static pickId(e){return(0,h.pick)(e,...this.$pkColumnNames)}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return(0,m.toS)(this.id)}$ucn(){return this.class().ucn(this)}$tableName(){return this.class().$tableName}$uid(){return`${this.$tableName()}(${this.id??this.$ucn()})${!0===this.shown?"!":""}`}logger(){return(0,n.mkLogger)(this.class().$schema+"."+(0,m.toS)(this.valueOf()))}[s.inspect.custom](){return{...this.$toShallowJSON(),$instanceId:this.$instanceId}}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(e){return(0,y.fromJSON)(this,e)}static toJSON(e){return this.fromJSON(e).toJSON()}$toShallowJSON(){return this.$_toJSON({encodeBool:u.isTrue})}$toDbJSON(e){return this.$_toJSON({encodeBool:u.boolToInt,includeCtor:!1,includeTransient:!1,colNames:e})}$clone(){return(0,y.fromJSON)(this.class(),this.toJSON())}toJSON(){return this.$_toJSON({encodeBool:u.isTrue})}_get(e,t,i=!0){const r=this[e];return null===r?[e,null]:!(0,f.isPrimitive)(r)||!i&&(0,l.includes)(this.class().$transientFields,e)?void 0:(0,l.includes)(this.class().$booleanFields,e)?[e,t(r)]:[e,r]}$_toJSON({encodeBool:e,includeCtor:t=!0,includeTransient:i=!0,colNames:r}){const s=this.class(),n=(0,l.notEmptyOr)(r,s.ops().columnNames());return(0,h.fromEntries)(n.map((t=>this._get(t,e,i))),t?{$ctor:s.$ctor}:{})}insert(){return this.logger().debug("insert()",{self:this.toJSON()}),this.class().ops().insertOne(this)}update(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("update()",{self:this.toJSON()}),this.class().ops().updateOne(this)}upsert(e){return null!=e&&(0,y.assignFromJSON)(this,e),this.logger().debug("upsert()",{self:this.toJSON(),arg:e}),this.class().ops().upsertOne(this)}$afterInsert(){}$beforeUpsert(){}$afterUpsert(){}reload(){return this.class().ops().reloadOne(this)}delete(){(0,d.gt0)(this.id)&&this.class().ops().delete([this.id])}}t.Model=w,r=w,w.$schema="models",w.$logger=(0,c.defer)((()=>(0,n.mkLogger)(r.$schema+"."+r.$tableName))),w.db=g.modelDb,w.$pkColumnNames=["id"]},94448:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryModelDbFile=t.modelDb=void 0;const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)((()=>{})),t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),(e=>(0,r.pathToDb)(e,"models")))}},33572:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toJSON=t.assignFromJSON=t.fromJSON=t.addModelClass=void 0;const r=i(50213),s=i(40958),n=i(22573),a=i(38639),o=i(97790),l=i(51926),u=new Map;function c(e){u.set(e.$ctor,e)}function d(e,t,i=[]){const r=e.class();for(const[n,o]of Object.entries(t)){if("$ctor"===n)continue;if(void 0===o)continue;const t=(0,l.stripPrefixes)(n,i);e[t]=null==o?o:(0,s.includes)(r.$booleanFields,t)?(0,a.isTrue)(o):o}return e}t.addModelClass=c,t.fromJSON=function(e,t){if(null==t)throw new Error("json is null");if(null!=e&&(0,n.notBlank)(e.$ctor)&&!u.has(e.$ctor)&&c(e),t instanceof e)return t;const i=(0,o.opt)(t.$ctor).flatMap((e=>u.get(e))).getOrElse((()=>e));if(t instanceof i)return t;const r=new i;return null==t?r:d(r,t,(0,s.uniq)([e.$tableName+".",i.$tableName+"."]))},t.assignFromJSON=d,t.toJSON=function e(t,i,s){if(null!=t)return Array.isArray(t)?t.map(((t,r)=>e(t,i,`${s}[${r}]`))):"function"==typeof t.toJSON?t.toJSON():void(0,r.mkLogger)("ModelJSON.toJSON()").warn("Failed",{m:t,key:s,mc:i.$ctor})}},63872:function(e,t,i){"use strict";var r,s,n,a,o,l,u,c,d=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},h=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const f=i(48884),m=i(19851),p=i(50213),g=i(81168),y=i(48299),v=i(12943),w=i(38835),b=i(34102),S=i(28874),P=i(40958),_=i(76790),T=i(22573),M=i(50357),E=i(96249),k=i(98553),D=i(55835),x=i(31586),C=i(68708),A=i(59455),F=i(86859),I=i(33572);t.ModelOps=class{constructor(e,t){r.add(this),this.model=e,this.db=t,s.set(this,void 0),n.set(this,!0),a.set(this,new y.WeakCache),o.set(this,new Set),this.columnNames=(0,m.lazy)((()=>this.db().tableInfo_().find((e=>(0,g.equalsIgnoreCase)(e.tableName,this.tableName))).columns.map((e=>e.name)))),this.updatableColumnNames=(0,m.lazy)((()=>(0,P.diff)(this.columnNames(),this.immutableColumnNames))),this.ucnFieldNames=(0,m.lazy)((()=>this.ucn.split(","))),d(this,s,(0,p.mkLogger)(`ModelOps(${e.$tableName})`),"f"),(0,I.addModelClass)(e),d(this,n,e.$useCache??!0,"f"),this.dbl=new F.DbRequest(this.db,e.$tableName),(0,b.ee)().on("clearCache",(()=>h(this,a,"f").clear())),(0,b.ee)().on("clearDbCache",(()=>h(this,a,"f").clear()))}clearDbCache(){h(this,a,"f").clear()}get $cache(){return h(this,a,"f")}$cachedByJson(e){if(null==e||!h(this,n,"f"))return;const t=this.$pickModelUcn(e);return(null==t?void 0:h(this,a,"f").get((0,k.stringify)(t)))??this.$cachedById(e.id)}$cachedById(e){return(0,x.gt0)(e)&&h(this,n,"f")?h(this,a,"f").get((0,k.stringify)(e))??h(this,a,"f").findEntry((t=>t.id===e)):void 0}get dbOpen(){return(0,D.mapOr)(this.db(),(e=>e.isOpen),(()=>!1))}get tableName(){return this.model.$tableName}query(){return this.model.query()}toDbValued(e){const t=this.model.fromJSON(e),i=(0,v.toDbValued)(t);return(0,C.pick)(i,...this.columnNames())}run(e){return this.dbl.run(e)}fromJSON(e){if((0,C.isEmptyObj)(e))return;const t=this.model.fromJSON(e);return h(this,r,"m",u).call(this,t)}fromJSONs(e){return(0,P.compact)(e.map((e=>this.fromJSON(e))))}first(e){return this.fromJSON(this.dbl.first(e))}firstf(e){return this.first(e(this.query()))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,t){return this.findOneBy({...t,id:e})}findByIds(e){e=(0,A.toA)(e).filter(x.gt0);const t=[],i=[];for(const r of e){const e=this.$cachedById(r);null!=e?t.push(e):i.push(r)}const r=(0,f.batches)(i,S.Settings.dbBatchSelectSize.valueOrDefault).map((e=>this.dbl.all(this.query().whereIn("id",e))));return(0,_.sortBy)([...t,...this.fromJSONs((0,E.flatten)(r))],(t=>e.indexOf(t.id)))}findBy(e){return this.all(this.model.queryBy(e))}findWhereIn(e,t){return this.all(this.model.query().whereIn(e,t))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,x.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,A.toA)(e).map((e=>this.insertOne(e)))}upsertOne(e){return this.modelSupportsUpsert?this.upsert([e])[0]:this.insertOrUpdateOne(e)}insertOrUpdateOne(e){return null==e.id?this.insertOne(e):this.updateOne(e)}insertOne(e){if(this.model.hasId(e))throw new Error("insert called for "+(0,k.stringify)(e)+w.NonRetriableErrorFlag);const t=this.fromJSON(e);if(null==t)return h(this,s,"f").throw("insertOne(): fromJSON returned null"+w.InternalErrorFlag,{t:e});t instanceof this.model&&h(this,r,"m",u).call(this,t),t.$beforeUpsert();const i=t.$toDbJSON(this.columnNames()),n=this.dbl.runf((e=>e.insert(i)));return t.id=(0,x.toInt)(n.lastInsertRowid),t.$afterInsert(),t.$afterUpsert(),t}unsetField(e,t){return(0,D.map)(this.$cachedById(e),(e=>{e[t]=null})),this.dbl.runf((i=>i.where({id:e}).update(t,null)))}updateOne(e){if(null==e.id)throw new Error("update called for "+(0,k.stringify)(e)+w.NonRetriableErrorFlag+w.InternalErrorFlag);const t=this.model.fromJSON(e);t.$beforeUpsert();const i=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf((t=>t.where({id:e.id}).update(i))),t.$afterUpsert(),h(this,r,"m",u).call(this,t)??t}get ucn(){return(0,T.toNotBlank)(this.model.$uniqueColumnName)??"id"}get modelSupportsUpsert(){return null!=this.ucn&&"id"!==this.ucn}get ucnConstraint(){return`(${this.ucn})`}get immutableColumnNames(){return(0,P.uniq)([...this.ucnFieldNames(),"id","createdAt"])}onConflictClause(e){const t=this.immutableColumnNames,i=e.filter((e=>!t.includes(e))).sort().map((e=>`${e}=excluded.${e}`)).join(","),r=["ON CONFLICT",this.ucnConstraint];return(0,T.blank)(i)?r.push("DO NOTHING"):r.push("DO UPDATE SET",i),r.join(" ")}$pickModelUcn(e){const t={};for(const i of this.ucnFieldNames()){const r=e[i];if(null==r)return;t[i]=r}return t}reloadOne(e){if(h(this,o,"f").has(e.id))return;const t=this.$pickModelUcn(e);if(null!=t){const i=h(this,r,"m",u).call(this,e),s=this.findOneBy(t);if(null==s)return;return h(this,r,"m",l).call(this,i,s),i!==e&&h(this,r,"m",l).call(this,e,i),i}h(this,s,"f").warn(".reloadOne(): failed to reload "+(0,k.stringify)(e))}reload(e){const t=[],i=this.allf((i=>{for(const r of e){const e=this.model.hasId(r)?this.model.pickId(r):this.$pickModelUcn(r);null!=e?(t.push([r,e]),i=i.orWhere(e)):h(this,s,"f").warn("reload(): given insufficient partial model",{fragment:r})}return i})),n=[];for(const[e,a]of t){const t=i.find((e=>(0,M.eqlSubset)(a,e)));if(null==t)h(this,s,"f").warn("reload(): failed to find result in db",{prior:e,dbArr:i});else{const i=h(this,r,"m",u).call(this,e);h(this,r,"m",l).call(this,i,t),i!==e&&h(this,r,"m",l).call(this,i,t),n.push(t)}}return n}upsert(e){if(e=(0,P.compact)(e),!this.modelSupportsUpsert)return e.map((e=>this.insertOrUpdateOne(e)));const t=this.columnNames(),i=[];for(const s of(0,f.batches)((0,A.toA)(e),S.Settings.dbBatchUpsertSize.valueOrDefault)){const e=new Map,n=new Set,a=(0,P.compact)(s.map((e=>this.fromJSON(e))));for(const t of a){const i=(0,k.stringify)(this.$pickModelUcn(t));e.set(i,t),this.model.hasId(t)||n.add(i),t.$beforeUpsert()}h(this,r,"m",c).call(this,a.map((e=>e.$toDbJSON(t))));const o=this.reload(a),l=new Map(o.map((e=>[(0,k.stringify)(this.$pickModelUcn(e)),e])));for(const e of a){const t=(0,k.stringify)(this.$pickModelUcn(e)),r=l.get(t)??e;n.has(t)&&r.$afterInsert(),r.$afterUpsert(),i.push(r)}}return i}delete(e){const t=(0,A.toA)(e).filter(x.gt0);for(const e of t)h(this,o,"f").add(e);return h(this,a,"f").deleteValueIf((e=>t.includes(e.id))),this.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??S.Settings.dbBatchSelectSize.valueOrDefault;let i,r;do{i=this.allf((i=>(i=e.qb(i),null!=r&&(i=i.andWhere("id",">",r)),i.orderBy("id","asc").limit(t)))),(0,P.isNotEmpty)(i)&&(r=Math.max(...i.map((e=>e.id))),await e.onResults(i))}while((0,P.isNotEmpty)(i))}},s=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakSet,l=function(e,t){(0,C.assignFields)(e,t,{omitKeys:["$instanceId"],assignNullish:!0})},u=function(e){if(h(this,n,"f")){const t=this.$cachedByJson(e);if(null!=t)return h(this,r,"m",l).call(this,t,e),t;{const t=this.$pickModelUcn(e)??e.id;null!=t&&h(this,a,"f").set((0,k.stringify)(t),e)}}return e},c=function(e){const t=this.query().insert(e).toSQL(),i=new Set;for(const t of e)for(const e of(0,C.keys)(t))i.add(e);const s={sql:t.sql+" "+this.onConflictClause([...i.values()]),bindings:t.bindings};this.run(s);for(const t of e){const e=this.$cachedByJson(t);null!=e&&h(this,r,"m",l).call(this,e,this.model.fromJSON(t))}}},20958:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(19851),s=i(50213),n=i(88158),a=i(99331),o=i(70025),l=i(8769),u=i(22573),c=i(98553),d=i(50989),h=i(72761);t.OperationNames=(0,d.strEnum)("rebuildLibrary","forceRestartSync");const f=(0,r.lazy)((()=>(0,s.mkLogger)("model.Operation")));class m extends h.TimestampedModel{static incomplete(){return this.ops().allf((e=>e.whereIn("id",(e=>e.table(m.$tableName).min("id").whereNull("completedAt")))))}static ensurePendingOp(e){return m.getFirstPendingOp(e)??m.ops().insertOne(e)}static getFirstPendingOp(e){return f().tap({msg:"getFirstPendingOp",level:"info",result:this.ops().firstf((t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i})),meta:{crit:e}})}static markOpCompleted(e,t){return(0,u.blank)(e?.name)?f().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf((i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t})))}static async applyIfPending(e,t){const i=this.ops().firstf((t=>t.whereNull("completedAt").andWhere(e)));return f().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce_(e,t,i=n.identity){const r=this.ops().firstf((t=>i(t.whereNotNull("completedAt").andWhere(e))));if(null!=r)return void f().debug("applyOnce(): already done",{priorCompleted:r});const s=this.ops().insertOne(e);try{const e=await t(s);return(0,a.ending)()||s.markCompleted(),e}catch(t){if((0,o.isRedoableError)(t))return void f().info("applyOnce(): redoable error",{crit:e,error:t});throw(0,l.onError)("Operation.applyOnce(): "+(0,c.stringify)(e),t),t}}markCompleted(){null==this.completedAt&&(this.completedAt=Date.now(),this.upsert())}}t.Operation=m,m.$tableName="Operation",m.$uniqueColumnName="id",m.$useCache=!1},49796:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=t.defaultMinCreatedAt=t.toPct=void 0;const r=i(48161),s=i(1708),n=i(48884),a=i(50213),o=i(28874),l=i(40958),u=i(42659),c=i(45599),d=i(98553),h=i(55835),f=i(31586),m=i(68708),p=i(67478),g=i(51926),y=i(59455),v=i(54993),w=i(76386),b=i(33572),S=i(55009),P=i(72761),_=(0,c.defer)((()=>(0,a.mkLogger)("model.Progress")));function T(e){return null==e||!(0,f.isNumber)(e)||e<0||e>100?void 0:(0,f.sigFigs)(e,3)}t.toPct=T;const M=(0,g.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n uri,\n max(completedAt) AS lastCompletedAt\n FROM\n Progress\n WHERE\n CAST(completedAt AS int) > 0\n GROUP BY\n 1\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function E(){const e=o.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*u.dayMs}t.defaultMinCreatedAt=E;class k extends P.TimestampedModel{static vacuum(e=o.Settings.progressRetentionDays.valueOrDefault*u.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf((e=>e.select("id").where("createdAt","<=",t)));for(const e of(0,n.batches)(i,o.Settings.dbBatchSelectSize.valueOrDefault))S.ProgressMeta.dbl.runf((t=>t.whereIn("progressId",e).delete())),k.dbl.runf((t=>t.whereIn("id",e).delete()))}static countCompletedDirectorySyncs(){return this.dbl.pluckFirstf((e=>e.where({state:"done"}).whereNotNull("completedAt").where("uri","like","ps%")))}static times(){return _().tap({msg:"times()",result:this.dbl.all({sql:M})})}static insertNew(e){const t=(0,h.map)(e.dek,d.stringify);return this.ops().insertOne({...(0,m.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&this.assignFromPojo(e),super.upsert()}$beforeUpsert(){super.$beforeUpsert(),null==this.id&&(this.pid??(this.pid=s.pid),this.hostname??(this.hostname=(0,r.hostname)())),"done"===this.state&&(this.completedAt??(this.completedAt=Date.now())),this.completePct=T(this.completePct),this.incompletePct=T(this.incompletePct),this.scanningPct=T(this.scanningPct)}$afterUpsert(){super.$afterUpsert(),(0,w.tellWebProgressUpdated)()}toSyncState(){return{id:this.id,uri:this.uri,volume:this.volume,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return(0,l.compactBlanks)((0,p.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,d.stringify)((0,l.compactBlanks)((0,y.toA)(t))))}assignFromPojo(e){return(0,b.assignFromJSON)(this,(0,m.omit)(e,"volume","uri"))}getMeta(){return S.ProgressMeta.ops().allf((e=>e.where({progressId:this.id}).orderBy("createdAt")))}getPriorIncomplete(e=E()){return this.logger().tap({msg:"priorIncompleteProgress()",result:k.ops().firstf((t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc")))})}getLastCompletedAt(e=E()){return k.dbl.pluckFirstf((t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e)))}getLastIncompleteStartAt(){return k.dbl.pluckFirstf((e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0)))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),S.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,l.diff)(t.map((e=>e.name)),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),S.ProgressMeta.ops().upsert((0,m.entries)(e).map((([e,t])=>({progressId:this.id,name:e,value:(0,v.toS)(t)})))),(0,l.isNotEmpty)(i)&&S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).whereIn("name",i).delete()))}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),S.ProgressMeta.dbl.runf((t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete()))}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),S.ProgressMeta.dbl.runf((e=>e.where({progressId:this.id}).delete()))}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,m.fromEntries)(this.getMeta().map((e=>[e.name,e.value])))??{}})}}t.Progress=k,k.$tableName="Progress",k.$uniqueColumnName="id"},55009:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{}t.ProgressMeta=n,n.$tableName="ProgressMeta",n.$uniqueColumnName="progressId,name"},39604:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.upsertToShaBlockslist=t.upsertFileToShaBlockslist=t.isShaBlockslisted=t.notBlocklistedSha=void 0;const r=i(19851),s=i(50213),n=i(95696),a=i(40958),o=i(22573),l=i(86859),u=i(94448),c=(0,r.lazy)((()=>(0,s.mkLogger)("model.ShaBlocklist"))),d=(0,r.lazy)((()=>new l.DbRequest(u.modelDb,"ShaBlocklist")));function h(e){return null!=(0,u.modelDb)()&&!(0,o.blank)(e)&&c().tap({msg:"isShaBlockslisted",result:null!=d().pluckFirstf((t=>t.where({sha:e}).limit(1))),meta:{sha:e}})}function f(...e){if(null==u.modelDb.prior())return;const t=(0,a.uniq)(e).map((e=>({sha:e})));return(0,a.isEmpty)(t)?void 0:d().upsert((e=>e.insert(t)))}t.notBlocklistedSha=async function(e){if(null==(0,u.modelDb)())return null;const t=h(await n.PosixFile.for(e).sha());return null==t?null:!t},t.isShaBlockslisted=h,t.upsertFileToShaBlockslist=async function(e){if(null==(0,u.modelDb)())return;const t=await n.PosixFile.for(e).sha();return null==t?void 0:f(t)},t.upsertToShaBlockslist=f},48723:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=t.UpdateTagAssetCountTimeName=void 0;const a=i(56038),o=i(34102),l=i(19851),u=i(50213),c=i(36372),d=i(97352),h=i(28874),f=i(81168),m=i(42231),p=i(75020),g=i(40958),y=i(22573),v=i(42659),w=i(41400),b=i(50357),S=i(55835),P=i(31586),_=i(34666),T=i(20214),M=i(51926),E=i(59455),k=i(12168),D=i(6186),x=i(57038),C=i(21074),A=i(7656),F=i(43487),I=i(48722),O=i(45295),L=i(98784),R=i(41507),N=i(72761),B=4*v.secondMs,j=(0,l.lazy)((()=>(0,u.mkLogger)("model.Tag")));(0,w.later)((()=>{(0,o.ee)().on("clearCache",(()=>z.clear())),(0,o.ee)().on("clearDbCache",(()=>z.clear()))})),t.UpdateTagAssetCountTimeName="db.updateTagAssetCountTimeName";class z extends N.TimestampedModel{constructor(){super(...arguments),this.displayPath=(0,l.lazy)((()=>{const e=this.getParent();return(0,g.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])})),this.ancestorIds=(0,l.lazy)((()=>0===this.parentId||null==this.parentId?[]:r.dbl.pluckAll({sql:(0,M.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.id","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}}))),this.firstNonInterstitialTagId=(0,l.lazy)((()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id})),this.directAssetCount=(0,l.lazy)((()=>0===this.id?0:F.Asset.dbl.pluckFirst(F.Asset.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id"))))}static orderBy(e){return e.orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")}static clear(){this.root.unset(),this.roots.unset(),this._upsertDefaultRoots.unset(),this.ops().clearDbCache()}static validate_(){return(0,a.timeSync)("Tag.validate_",(()=>{r.clear();for(const e of this.ops().allf((e=>e.whereRaw("id = parentId")))){j().warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,g.isEmpty)(t)?void 0:this.findOrCreate(t);e.update({parentId:i?.id??null})}for(const e of r.roots())e.validate_([])}))}validate_(e){const t=this.path;if(!(0,b.eql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static deltaAssetCountAndAncestors(e,t=1){return r.incrAssetCount(r.selfAndAncestorIds(e),t)}static incrAssetCount(e,t=1){(0,g.isEmpty)(e)||r.dbl.runf((i=>i.whereIn("id",e).andWhereNot({assetCount:null}).update({assetCount:(0,x.knex)().raw("assetCount + "+Math.round(t)),updatedAt:Date.now()})))}static selfAndAncestorIds(e){const t=(0,E.toA)(e).filter(P.gt0);return r.dbl.pluckAll({sql:(0,M.compressWhitespace)("WITH RECURSIVE ancestors(id) AS ("," SELECT id FROM Tag where id in "+(0,C.sqlWhereInClause)(t.length)," UNION ALL"," SELECT Tag.parentId as id"," FROM Tag, ancestors"," WHERE Tag.id = ancestors.id",")","SELECT distinct(id)","FROM ancestors","WHERE id IS NOT NULL"),bindings:t})}static updateAssetCount(e){if((0,P.gt0)(e))return(0,a.timeSync)(t.UpdateTagAssetCountTimeName,(()=>{const t=r.dbl.pluckFirst({sql:A.RecursiveAssetCountForTagQuery,bindings:{tagId:e}});r.dbl.runf((i=>i.update({assetCount:t,updatedAt:Date.now()}).where({id:e}))),j().debug("Updated asset counts for tag ",{tagId:e,assetCount:t})}))}static findByIdOrPath(e,t){return 0===e?r.root():(0,P.gt0)(e)?this.findById(e):this.findByPath(t)}static findById(e){return 0===e?r.root():this.ops().findById(e)}static findByPath(e){if((0,g.isEmpty)(e))return r.root();const t=(0,m.joinTagPath)(e);return this.ops().firstf((e=>e.whereLike("_path",t)))}static findByPathN(e){const t=(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,y.toNotBlank)((0,m.joinTagPath)(e))));return(0,g.compact)(t.map((e=>this.findByPath(e))))}static getPagedAssets(e,t){const i=new r;return i.id=e,i.getPagedAssetIds(t)}static findOrCreate(e){if((0,g.isEmpty)(e))throw new Error("empty tagPath");const t=this.findByPath(e);if(null!=t)return t;const i=n(this,r,"m",s).call(this,e),a=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));return(0,S.map)(a,(e=>i.parentId=e.id)),this.ops().upsertOne(i)}static findOrCreateByPathN(e){return(0,g.uniqBy)(e.filter(g.isNotEmpty),(e=>(0,m.joinTagPath)(e))).map((e=>this.findOrCreate(e)))}clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.assets=void 0,this.relatedAssets=void 0,this.ancestorIds.unset(),this}$afterInsert(){L.TagFts.insertFts([this])}siblingPath(e){return(0,m.joinTagPath)([...this.parentPath,e])}changeName(e){return this.changePath(this.siblingPath(e))}maybeUpsertDisplayName(e){return(0,y.blank)(e)||e===this._displayName?void 0:this.upsert({_displayName:e})}changePath(e,t=!0){const i=this._path,s=r.findByPath((0,m.splitTagPath)(e));this.logger().info("changePath(): ",{priorPath:i,newPath:e,existingSibling:s});try{if(null==s)r.dbl.runf((t=>t.whereLike("_path",i+"%").update({updatedAt:Date.now(),_path:(0,x.knex)().raw("REPLACE(_path, ?, ?)",[i,e])}))),this._path=e;else{e=s._path,this.logger().info("changePath(): replacing with sibling",e),O.AssetTag.dbl.upsert((e=>e.where({tagId:this.id}).update({tagId:s.id}))),O.AssetTag.dbl.runf((e=>e.where({tagId:this.id}).delete()));for(const e of this.getChildren())e.changePath((0,m.joinTagPath)([...s.path,e.name]),!1);r.dbl.runf((e=>e.where({parentId:this.id}).update({parentId:s.id}))),this.delete()}}finally{t&&r.clear()}}get name(){const e=this.path;return e[e.length-1]}get path(){return(0,m.splitTagPath)(this._path)}get displayName(){return(0,y.toNotBlank)(this._displayName)??this.name}get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}get sortBy(){return[this.depth,null==this.ordinal?2**51:this.ordinal,this.path.map((e=>e.toLowerCase()))]}$childrenQuery(){return r.orderBy(r.query().where({parentId:this.id}))}$assetsQuery(){return F.Asset.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id})}$selectAssetIdColumns(e){return e.clearSelect().select({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,S.map)(this.parent,(t=>t.setAncestors(e.slice(0,-1))))}async toApiPathElements(){return(0,T.thenCollect)(this.getAncestorsAndSelf(),(e=>e.toPathTag()))}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(){return{tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=r.findById(this.parentId):this.parent}getPagedChildren(e){if(0===this.id){const t=e.offset??0,i=t+(e.limit??this.children.length);return[...this.children].slice(t,i)}const t=this.$childrenQuery();return(0,d.mapGt0)(e.offset,(e=>{t.offset(e)})),(0,d.mapGt0)(e.limit,(e=>{t.limit(e)})),r.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:r.dbl.pluckFirstf((e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count()))}getChildren(){return this.isRoot||(this.children=r.ops().all(this.$childrenQuery()),this.children.forEach((e=>{e.parent=this}))),this.children}link(){return"/tag/"+this.path.map(encodeURIComponent).join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(){return this.ancestors??(this.ancestors=this._getAncestors())}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return 0===this.parentId||null==this.parentId?[]:r.ops().all({sql:(0,M.compressWhitespace)("WITH RECURSIVE cte(id, level) AS ("," VALUES (:tagId, 0)"," UNION ALL"," SELECT Tag.parentId as id, cte.level + 1 as level"," FROM Tag, cte"," WHERE Tag.id = cte.id",")","SELECT Tag.*","FROM Tag JOIN cte on cte.id = Tag.id","WHERE Tag.id <> :tagId","ORDER BY cte.level DESC"),bindings:{tagId:this.id}})}getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(p.ThumbsPerSample),(0,P.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,g.compact)(F.Asset.dbl.all(t).map(I.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return F.Asset.ops().all(e)}async assetCountDesc(e){const t=this.assetCount;return(null==t||null==e||e.length===t||0===e.length?"":(0,k.fmt)(e.length)+" of ")+(0,k.plur)(t,"asset")}getAssetCount(){return 0===this.id?r.dbl.pluckFirst({sql:(0,M.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," Asset","WHERE"," Asset.shown = 1"," AND Asset.excluded = 0"," AND Asset.hidden = 0"," AND Asset.deletedAt IS NULL")}):r.dbl.pluckFirst({sql:A.RecursiveAssetCountForTagQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.path[0]===p.TagRoots.When?F.Asset.shownUnhidden():this.$assetsQuery();return r=r.distinct().where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw(`ABS(Asset.id-${e.id})`):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}getAssetStream(e,t){t=(0,P.gt0)(t)?t:p.BeforeAfterStreamLimit;const[i,r,s]=["<","=",">"].map((i=>(0,g.compact)(F.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(I.toAssetId))));for(const t of r)t.assetIdF.Asset.shownUnhidden(this.$selectAssetIdColumns(r)).distinct().join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").whereLike("_path",this._path+"%").orderByRaw((0,c.prngOrderByClause)(e+(this.id??0),"Asset.id",i)).limit(t))).map(I.toAssetId));return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}get attrs(){return{href:this.link(),title:this.name}}}t.Tag=z,r=z,s=function(e){const t=new r;t._path=(0,m.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,y.mapNotBlank)(i.displayName,(e=>t._displayName=e)),(0,P.mapNumeric)(i.ordinal,(e=>t.ordinal=e)),(0,y.mapNotBlank)(i.description,(e=>t.description=e)),(0,P.mapNumeric)(i.releasedAt,(e=>t.releasedAt=e))),t},z.$tableName="Tag",z.$uniqueColumnName="_path",z.$useCache=!0,z.cmp=(e,t)=>(0,_.cmp)([e.ordinal??Number.MAX_SAFE_INTEGER,...e.path],[t.ordinal??Number.MAX_SAFE_INTEGER,...t.path]),z.root=(0,l.lazy)((()=>{const e=new r;return e.id=0,e._path=m.TagSep,e.parentId=void 0,e.children=r.roots().filter((e=>!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.name)&&!(0,f.includesIgnoreCase)(h.Settings.hiddenHomeTags.valueOrDefault,e.description??""))),e.ancestors=[],e.assetCount=F.Asset.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e}),B),z._upsertDefaultRoots=(0,l.lazy)((()=>r.ops().upsert(D.Roots.map((e=>({_path:(0,m.joinTagPath)([e.name]),ordinal:e.ordinal})))))),z.roots=(0,l.lazy)((()=>{r._upsertDefaultRoots();const e=r.ops().all(r.orderBy(r.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e}),B);const V=(0,l.lazy)((()=>F.Asset.dbl.pluckFirstf((e=>e.count()))),v.minuteMs)},98784:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagFts=void 0;const r=i(38156),s=i(3127),n=i(40958),a=i(41400),o=i(94715),l=i(55046),u=i(48723);class c extends l.Model{static insertFts(e){try{const t=e.filter((e=>null!=e.parentId)).map((e=>({rowid:e.id,root:(0,s.tag_fts_root)(e._path),path:(0,s.tag_fts_path)(e._path)})));(0,n.isEmpty)(t)||this.dbl.runf((e=>e.insert(t)))}catch(e){this.$logger().warn("Failed to update tag_fts",{error:e})}}static async rebuild(){const e=new r.PushProgressObserver({op:"Rebuilding tag search index"},u.Tag.dbl.pluckFirstf((e=>e.count("*")))),t=this.dbl.db();o.Migrations.create_tag_fts(t.db),await u.Tag.ops().batched({qb:e=>e,onResults:t=>(this.$logger().throwIfAborted_(),this.insertFts(t),e.incrProgress(t.length),(0,a.delay)(1))}),e.completed()}}t.TagFts=c,c.$tableName="tag_fts",c.$uniqueColumnName="rowid",c.$booleanFields=[]},41507:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.coalesceStreams=t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0;const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")"),this.logger().info("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,(e=>[-e.capturedAtLocal,-e.assetId])),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map((e=>e.path.join("/"))).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+1),capturedAtLocal:-1,v:0}))),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,(e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0})))]}toJSON(){return{tags:this.tags.map((e=>e.toString())),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,(e=>e.path)),(0,a.pushUniqBy)(this.before,e.before,(e=>e.assetId)),(0,a.pushUniqBy)(this.after,e.after,(e=>e.assetId)),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map((e=>e.path)),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,(e=>e.toApiTag())),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map((e=>e.path)),tas:e.tags.map((e=>e.path))},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],(e=>e.assetId))})}},t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter((e=>e.length>5));for(const e of s){const s=(0,r.greatestBy)(i,(i=>(0,l.gtOrElse)(i.streamCoeff(e),t)));null==s?i.push(e):s.mergeWith(e)}return i}},94710:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Task=t.StaleTaskError=t.InvalidTaskError=t.TaskNames=t.Tasks=t.testTask=void 0;const c=i(78474),d=i(22454),h=i(23560),f=i(12089),m=i(76740),p=i(22911),g=i(99331),y=i(31562),v=i(38835),w=i(70025),b=i(8769),S=i(74128),P=i(28874),_=i(37692),T=i(40958),M=i(22573),E=i(42659),k=i(45599),D=i(98553),x=i(49769),C=i(68708),A=i(50989),F=i(59455),I=i(58723),O=i(34274),L=i(90901),R=i(61989),N=i(93755),B=i(69032),j=i(55046);t.testTask=(0,f.shim1)({name:"testTask",impl:async e=>{}}),t.Tasks={applyDeleted:I.applyDeleted,applyExcluded:I.applyExcluded,runTagMaintenance:B.runTagMaintenance,updateAssetFile:N.updateAssetFile_,repairAsset:async function(e){e.forceSync=!0,e.skipPreviews=!0,e.skipAssetTagging=!0;const t=await(0,R.updateAsset_)(e);return(0,T.isNotEmpty)(t?.assetIdsToUpdate)&&q.add(t?.assetIdsToUpdate.map((t=>({fn:"repairAsset",args:{...e,assetId:t},priority:W.repairAsset+1})))),null!=t&&!0!==t.deleted&&(0,M.blank)((0,F.toA)(t.rejected).join(""))&&(0,M.blank)(t.error)&&q.addOne("assetPostUpsertTasks",(0,C.omit)(e,"skipPreviews","skipAssetTagging")),t},assetPostUpsertTasks:L.assetPostUpsertTasks,syncFile:O.importFileToResult_,testTask:t.testTask},t.TaskNames=(0,A.strEnum)(...(0,C.keys)(t.Tasks));class z extends Error{}t.InvalidTaskError=z;class V extends Error{}t.StaleTaskError=V;const W={applyDeleted:16,applyExcluded:16,runTagMaintenance:14,updateAssetFile:13,repairAsset:12,assetPostUpsertTasks:10,syncFile:0,testTask:-1},U=["repairAsset"];class q extends j.Model{constructor(){super(...arguments),r.add(this),o.set(this,(0,k.defer)((()=>new m.Abortable)))}static countTaskNames(){const e={};for(const t of s.dbl.allf((e=>e.select("fn").count().groupBy("fn"))))e[t.fn]=t["count(*)"];return e}static orderBy(e){return e.orderBy([{column:"priority",order:"desc"},{column:"retries",order:"desc"},{column:"id",order:"asc"}])}static count(){return s.dbl.pluckFirstf((e=>e.count("id")))}static freeSlots(){return P.Settings.taskListCap.valueOrDefault-s.count()}static countByFn(e){return s.dbl.pluckFirstf((t=>t.where({fn:e}).count("id")))}static nextByFn(e,t=(e=>e)){return s.ops().allf((i=>s.orderBy(t(i.where({fn:e})))))}set args(e){this.argsJSON=(0,D.stringify)(e)}get args(){const e=(0,D.parseJSON)(this.argsJSON);return(0,C.notEmptyObj)(e)&&(e.halt=u(this,o,"f").call(this)),e}get isSerial(){return U.includes(this.fn)}toString(){return`Task#${this.fn}(${this.argsJSON})`}static addOne(e,t){return s.add([{fn:e,args:t}])[0]}static add(e,t=!1){if((0,T.isEmpty)(e))return[];const i=s.ops().upsert(e.map((e=>({fn:e.fn,argsJSON:(0,D.stringify)(e.args)})),t));return s.ee.emit("added",i),(0,h.isTaskListManager)()||(0,_.addStateEvent)("checkTasks"),i}$beforeUpsert(){this.priority??(this.priority=W[this.fn]),this.retries??(this.retries=P.Settings.maxRetries.valueOrDefault)}donePromise(){return(0,h.isTaskListManager)()?(0,x.getOrSet)(u(s,s,"f",n),this.id,(()=>new p.Deferred(this.toString(),{payload:this}))):(0,y.untilTrue)((()=>null==s.ops().findById(this.id)),{intervalMs:E.secondMs})}abort(e){this.logger().warn("aborting task",{reason:e,task:this}),u(this,o,"f").call(this).abort(e),this.delete(),(0,M.blank)(this.args.path)||(0,S.syncReport)().onProgress({path:this.args.path,from:this.fn,state:S.SyncFileStates.failed,details:e})}async _run(){if(this.retries<0)throw this.logger().warn(".run(): too many retries"+v.InternalErrorFlag,{job:this}),this.delete(),new z;if(!u(this,r,"m",l).call(this))throw this.logger().warn(".run(): someone already started this task",{job:this}),new V;try{const e=Date.now(),i=await t.Tasks[this.fn](this.args);return this.logger().throwIfAborted_(u(this,o,"f").prior()),s.taskResolvedCounts.incr(this.fn),s.ee.emit("resolved",this,i,Date.now()-e),this.delete(),u(s,s,"f",n).get(this.id)?.resolve(i),i}catch(e){if((0,g.ending)())throw this.logger().info("task failed, but we're ending. We'll leave it for next time.",{task:this}),e;throw s.taskRejectedCounts.incr(this.fn),(0,w.isRedoableError)(e)?(this.retries++,this.priority--,this.upsert()):!0===(0,w.isRetriableError)(e)&&this.retries>=0?this.logger().warn("run failed, but we can retry it later",{task:this,error:e}):(s.ee.emit("rejected",this,e),this.delete(),u(s,s,"f",n).get(this.id)?.reject(e),(0,b.onError)(this.toString()+" failed",e)),e}finally{u(s,s,"m",a).call(s)}}}t.Task=q,s=q,o=new WeakMap,r=new WeakSet,a=function(){for(const[e,t]of u(this,s,"f",n).entries())t.isSettled&&u(this,s,"f",n).delete(e)},l=function(){const e=this.retries;if(1===s.dbl.runf((t=>t.where({id:this.id,retries:e}).update({retries:e-1}))).changes)return--this.retries,!0;{const e=this.toJSON(),t=this.reload();return this.logger().warn(".#decrRetries(): someone already started this task",{before:e,reloaded:t}),!1}},q.$tableName="Task",q.$uniqueColumnName="fn,argsJSON",q.$useCache=!1,q.taskResolvedCounts=new d.CountingSet,q.taskRejectedCounts=new d.CountingSet,q.ee=new c.EventEmitter,n={value:new Map}},72761:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??(t.updatedAt=Date.now()),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf((e=>e.whereIn("id",i).update(t)))}get createdAtDate(){return(0,r.mapGt0)(this.createdAt,(e=>new Date(e)))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,(e=>new Date(e)))}touch(e={}){e.updatedAt??(e.updatedAt=Date.now());const t=this.id;null==t?this.upsert():this.class().dbl.runf((i=>i.where({id:t}).update(e)))}$beforeUpsert(){if(super.$beforeUpsert(),this.createdAt??(this.createdAt=Date.now()),this.updatedAt=Date.now(),"updateCount"in this){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeUpsert(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},73407:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeAssetTags_=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(47783),o=i(54017),l=(0,r.lazy)((()=>(0,s.mkLogger)("model.WriteAssetTags")));t.writeAssetTags_=async function(e,t){const i=o.AssetFile.ops().findBy({assetId:e});return(0,n.mapAsync)({name:"writeAssetTags",arr:i,f:e=>async function(e,t){const i=await e.posixFile_();if(null!=i&&!0===await(i?.exists()))return(0,a.writeTags_)(i,t,e.mimetype);l().info("Skipping AssetFile:"+e.id+" (file is missing)",{writeTags:t})}(e,t)})}},58723:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyExcluded=t.applyDeleted=void 0;const r=i(50213),s=i(43487),n=(0,r.mkLogger)("ops.ApplyRemovable");async function a(e,t,i){const r=e?"Deleting":"Excluding",a=e?"deletedAt":"excludedAt";await s.Asset.dbl.batched({qb:e=>e.select("id").where("shown",0).andWhere(a,"<=",t),onResults:async t=>{for(const a of t){n.throwIfAborted_(i);try{await s.Asset.remove({assetId:a,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){n.error(r+" failed",{assetId:a,error:e})}}}})}t.applyDeleted=function(e){return a(!0,e.createdAt,e.halt)},t.applyExcluded=function(e){return a(!1,e.createdAt,e.halt)}},76386:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)((()=>(0,s.mkLogger)("progress.Progress")));t.ProgressRateMs=(0,r.lazy)((()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=3?5:1.5))),t.tellWebProgressUpdated=(0,r.lazy)((async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch((e=>h().warn(".tellWebProgressUpdated: failed",{error:e})))}),(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},44694:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryTermToFuzzyDate=void 0;const r=i(98725),s=(0,i(19851).lazy)((()=>new r.FuzzyDateParser({fuzzyDateParsing:!0,fuzzyYearParsing:!0})));t.queryTermToFuzzyDate=function(e){return s().parse(e)}},43786:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToString=t.NormieQuerySymbols=t.SetQuerySymbols=t.isTrueTerm=t.flatTerms=t.findTerm=t.hasNsTerm=t.isQuery=t.isClause=t.isAndClause=t.isOrClause=t.isTerm=void 0;const r=i(40958),s=i(22573),n=i(38639),a=i(51926),o=i(54993);function l(e){return"object"==typeof e&&(0,s.notBlank)(e.term)&&(null==e.not||"boolean"==typeof e.not&&(null==e.ns||(0,a.isString)(e.ns)))}function u(e){return"object"==typeof e&&Array.isArray(e.queries)}function c(e){return"or"===e?.type&&u(e)}function d(e){return"and"===e?.type&&u(e)}function h(e){return d(e)||c(e)}function f(e,t){if(l(e))return t(e)?e:void 0;for(const i of e.queries){const e=f(i,t);if(null!=e)return e}}t.isTerm=l,t.isOrClause=c,t.isAndClause=d,t.isClause=h,t.isQuery=function(e){return l(e)||h(e)},t.hasNsTerm=function(e,t){return null!=f(e,(e=>e.ns===t))},t.findTerm=f,t.flatTerms=function e(t){return l(t)?[t]:(0,r.flatMap)(t.queries,e)},t.isTrueTerm=function(e){return(0,n.isTrue)(e?.not)?(0,n.isFalse)(e?.term):(0,n.isTrue)(e?.term)},t.SetQuerySymbols={not:"¬",and:"∧",or:"∨"},t.NormieQuerySymbols={not:"-",and:"AND",or:"OR"},t.queryToString=function e(i,r=t.SetQuerySymbols){if(null==i)return"";if(l(i)){let e=i.term;return null==i.term.match(/^[a-z]+$/i)&&(e='"'+e.replace(/"/g,'\\"')+'"'),`${(0,n.isTrue)(i.not)?r.not:""}${null==i.ns?"":i.ns+":"+(0,o.toS)(i.op)}${e}`}return"("+i.queries.map((t=>e(t,r))).join(` ${"or"===i.type?r.or:r.and} `)+")"}},7573:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeTerm=t.isAssetTerm=t.AssetTermNs=t.AssetTermDateNs=t.AssetTermBoolNs=t.normalizeQuery=void 0;const r=i(48884),s=i(75020),n=i(40958),a=i(76790),o=i(22573),l=i(38639),u=i(50989),c=i(54993),d=i(44694),h=i(43786);function f(e){return(0,a.sortBy)((0,n.uniqBy)(e,h.queryToString),(e=>[(0,h.isTerm)(e)?0:(0,h.isOrClause)(e)?1:2,(0,h.queryToString)(e).replace(/[¬(]+/g,"")]))}t.normalizeQuery=function e(t){if((0,h.isTerm)(t))return g(t);const i=t.queries.map(e);if(0===i.length)throw new Error("empty query");if(1===i.length)return i[0];const[s,n]=(0,r.partition)(i,h.isTerm),[a,o]=(0,r.partition)(n,(e=>e.type===t.type));for(const e of a)s.push(...e.queries);const l={type:t.type,queries:f([...s,...o])};return l.queries.every((e=>(0,h.isTerm)(e)&&e.not))?e({type:"and"===t.type?"or":"and",queries:f(l.queries.map((e=>({...e,not:!1}))))}):l},t.AssetTermBoolNs=(0,u.strEnum)("deleted","excluded","liked","hidden"),t.AssetTermDateNs=(0,u.strEnum)("date","updated");const m={delete:t.AssetTermBoolNs.deleted,trash:t.AssetTermBoolNs.deleted,trashed:t.AssetTermBoolNs.deleted,exclude:t.AssetTermBoolNs.excluded,remove:t.AssetTermBoolNs.excluded,removed:t.AssetTermBoolNs.excluded,like:t.AssetTermBoolNs.liked,fav:t.AssetTermBoolNs.liked,fave:t.AssetTermBoolNs.liked,faved:t.AssetTermBoolNs.liked,favorite:t.AssetTermBoolNs.liked,favourite:t.AssetTermBoolNs.liked,hide:t.AssetTermBoolNs.hidden,archive:t.AssetTermBoolNs.hidden,archived:t.AssetTermBoolNs.hidden},p={kw:s.TagRoots.Keywords,keyword:s.TagRoots.Keywords,keywords:s.TagRoots.Keywords,dir:s.TagRoots.fs,directory:s.TagRoots.fs,folder:s.TagRoots.fs};function g(e){if((0,o.blank)(e.ns)&&null!=e.term.match(/^\d{4}[-\d]*$/)&&null!=(0,d.queryTermToFuzzyDate)(e.term))return{ns:"date",term:e.term};if("when"===(0,c.toS)(e.ns).toLowerCase())return g({...e,ns:t.AssetTermDateNs.date,term:e.term.replace(/\//g,"-")});let i=(0,o.notBlankOr)(e.ns,e.term).toLowerCase();if(i=m[i]??i,t.AssetTermBoolNs.includes(i)){let t=!(0,l.isFalse)(e.term);return!0===e.not&&(t=!t),{ns:i,term:(0,c.toS)(t)}}if(t.AssetTermNs.includes(i))return{...e,ns:i};if("before"===i||"after"===i){if(null!=e.op)throw new Error(i+": doesn't support operators");const r="after"===i&&!0!==e.not||!0===e.not;return{ns:t.AssetTermDateNs.date,op:r?">":"<",term:e.term}}return i!==e.term.toLowerCase()?{not:e.not,op:e.op,ns:p[i]??i,term:e.term}:e}t.AssetTermNs=(0,u.strEnum)(...t.AssetTermDateNs.values,...t.AssetTermBoolNs.values),t.isAssetTerm=function(e){return(0,h.isTerm)(e)&&t.AssetTermNs.includes(g(e).ns)},t.normalizeTerm=g},33693:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseQuery_=void 0;const s=r(i(31704)),n=i(19851),a=i(50213),o=i(7282),l=i(38835),u=i(31586),c=r(i(70471)),d=(0,n.lazy)((()=>(0,a.mkLogger)("query.QueryParser")));t.parseQuery_=function(e){try{const t=new s.default.Parser(s.default.Grammar.fromCompiled(c.default)).feed(e.trim()).finish();if(t.length>1&&!(0,o.isProd)()&&d().throw("parseQuery(): ambiguous grammar!",{input:e}),null==t[0])throw new Error("invalid query");return d().debug("parseQuery()",{input:e,result:t[0]}),t[0]}catch(t){const i=t.token?.col,r=`Query syntax error${(0,u.gt0)(i)?" around column "+i:""}: "${e}"`;throw d().warn("parseQuery(): bad query",{msg:r,err:t}),new Error(r+l.NonRetriableErrorFlag+l.DoNotSendErrorFlag)}}},23523:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryToSql=t.queryStringToSql_=t.defaultAssetQuery=void 0;const r=i(19851),s=i(50213),n=i(66649),a=i(89724),o=i(70417),l=i(28874),u=i(42231),c=i(22573),d=i(38639),h=i(98553),f=i(54993),m=i(57038),p=i(43487),g=i(44694),y=i(43786),v=i(7573),w=i(33693),b=(0,r.lazy)((()=>(0,s.mkLogger)("query.QueryToSql")));function S(e,t,i){if((0,y.isTerm)(t))return function(e,t,i){return(0,v.isAssetTerm)(t)?function(e,t){switch(t.ns){case v.AssetTermNs.date:case v.AssetTermNs.updated:return function(e,t){const i=t.op??"=",r="date"===t.ns?"Asset.capturedAtLocal":"updated"===t.ns?"Asset.updatedAt":void 0;if(null==r)throw new Error("internal error: unexpected namespace for "+(0,h.stringify)(t));const s="Asset.updatedAt"===r?n.datedToMillis:a.maybeDatedToLocal,l=(0,g.queryTermToFuzzyDate)(t.term),u=s(l),c=l?.following()?.toDateTime(),d=s(c?.minus({second:1})),f=(0,o.max)([u,d]);if(null==l||null==u||null==f)throw new Error((0,y.queryToString)(t,y.NormieQuerySymbols)+" can't be parsed as a date");if("="===i)return e.whereBetween(r,[u,f]);if("<"===i)return e.where(r,i,u);if("<="===i)return e.where(r,i,f);if(">="===i)return e.where(r,i,u);if(">"===i)return e.where(r,i,f);throw new Error("internal error: unexpected op for "+(0,h.stringify)(t))}(e,t);case v.AssetTermNs.hidden:return e.where("Asset.hidden",_(t));case v.AssetTermNs.excluded:return M({qb:e,column:"Asset.excludedAt",whereNull:0===_(t)});case v.AssetTermNs.deleted:return M({qb:e,column:"Asset.deletedAt",whereNull:0===_(t)});case v.AssetTermNs.liked:return e.where("Asset.rating",P(t)?">=":"<",l.Settings.likeRating.valueOrDefault);default:throw new Error("not asset term:"+(0,y.queryToString)(t))}}(e,t):function(e,t,i){const r=t.term.startsWith("/"),s="="===t.op,n=function(e,t){if(null==t||"fs"!==e.ns)return e.term;const i=e.term.split("/"),r=i.findIndex(c.notBlank);if(-1===r)return e.term;const s=i[r];return i[r]=t.get(s)??s,i.join("/")}(t,i);if(r||s)return e.whereIn("Asset.id",(0,m.knex)()("AssetTag").join("Tag","Tag.id","AssetTag.tagId").select("assetId").whereLike("Tag._path",t.ns+(r?"":"%")+n.replace(/\//g,u.TagSep).replace(/\*/g,"%")+u.TagSep+(s?"":"%")));let a=(0,m.knex)()("AssetTag").join("tag_fts","tag_fts.rowid","AssetTag.tagId").select("assetId");const o="path:"+T(n.replace(/\//g," + "));if((0,c.blank)(t.ns)){if((0,d.isTrue)(t.not))throw new Error("Cannot negate without a namespace ("+(0,y.queryToString)(t)+")");a=a.where("tag_fts","MATCH",o)}else a=a.where("tag_fts","MATCH","(root:"+T(t.ns)+((0,d.isTrue)(t.not)?" NOT ":" AND ")+o+")");return e.whereIn("Asset.id",a)}(e,t,i)}(e,t,i);for(const r of t.queries)e=(0,y.isAndClause)(t)?e.andWhere((e=>S(e,r,i))):e.orWhere((e=>S(e,r,i)));return e}function P(e){const t=(0,d.isTrue)(e.term);return!0===e.not?!t:t}function _(e){return P(e)?1:0}function T(e){return e.includes("*")?e.split("*").map(T).join(" * "):`"${(0,f.toS)(e).replace(/"/g,'""')}"`}function M({qb:e,column:t,whereNull:i}){return i?e.whereNull(t):e.whereNotNull(t)}function E(){return p.Asset.ops().query().where("Asset.shown",1).join("AssetTag","AssetTag.assetId","Asset.id")}function k(e,t=E(),i){return e=(0,v.normalizeQuery)(e),(0,y.hasNsTerm)(e,v.AssetTermBoolNs.hidden)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.excluded)||(0,y.hasNsTerm)(e,v.AssetTermBoolNs.deleted)||(t=t.andWhere({"Asset.hidden":0,"Asset.excludedAt":null,"Asset.deletedAt":null})),t.andWhere((t=>S(t,e,i)))}t.defaultAssetQuery=E,t.queryStringToSql_=function(e,t=E()){const i=(0,w.parseQuery_)(e);return null==i?(b().warn("assetQuery("+e+"): parsed to null"),t):k(i,t)},t.queryToSql=k},70471:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};function s(e){return e[0]}Object.defineProperty(t,"__esModule",{value:!0}),t.parseTerm=void 0;const n=r(i(80265)),a=i(40958),o=i(54993);function l(e){if(null==e[0]&&["and","or"].includes((0,o.toS)(e[1]).toLowerCase()))throw new Error("Unmatched "+e[1]);return{not:null!=e[0]?.[0]?.value,ns:e[0]?.[1]?.value,op:e[0]?.[3]?.value,term:e[1]}}function u(e){return e[0]?.value}t.parseTerm=l;const c=n.default.compile({qstr:[{match:/"(?:[^\\"]|\\.)*?"/,value:e=>e.slice(1,-1).replace(/\\"/g,'"')},{match:/'(?:[^\\']|\\.)*?'/,value:e=>e.slice(1,-1).replace(/\\'/g,"'")}],lp:"(",rp:")",not:/[-¬]/,col:":",op:/<=?|>=?|=/,or:/ +(?:or|OR|Or|∨|\|{1,2}) +/,and:/(?:and|AND|And|∧|\&{1,2}) +/,str:/[^\s:\(\)"'][^\s:\(\)]*/,ws:/ +/}),d={Lexer:c,ParserRules:[{name:"Expression$ebnf$1",symbols:[]},{name:"Expression$ebnf$1$subexpression$1",symbols:[c.has("or")?{type:"or"}:or,"Clause"]},{name:"Expression$ebnf$1",symbols:["Expression$ebnf$1","Expression$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Expression",symbols:["Clause","Expression$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[1]))]);return 1===t.length?t[0]:{type:"or",queries:t}}},{name:"Clause$ebnf$1",symbols:[]},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("and")?{type:"and"}:and],postprocess:s},{name:"Clause$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Clause$ebnf$1$subexpression$1",symbols:["__","Clause$ebnf$1$subexpression$1$ebnf$1","Factor"]},{name:"Clause$ebnf$1",symbols:["Clause$ebnf$1","Clause$ebnf$1$subexpression$1"],postprocess:e=>e[0].concat([e[1]])},{name:"Clause",symbols:["Factor","Clause$ebnf$1"],postprocess:function(e){const t=(0,a.compact)([e[0],...e[1].map((e=>e[2]))]);return 1===t.length?t[0]:{type:"and",queries:t}}},{name:"Factor",symbols:["Term"],postprocess:s},{name:"Factor",symbols:[c.has("lp")?{type:"lp"}:lp,"_","Expression","_",c.has("rp")?{type:"rp"}:rp],postprocess:function(e){const t=(0,a.compact)(e[2]);return 1===t.length?t[0]:t}},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[c.has("not")?{type:"not"}:not],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[c.has("op")?{type:"op"}:op],postprocess:s},{name:"Term$ebnf$1$subexpression$1$ebnf$2",symbols:[],postprocess:()=>null},{name:"Term$ebnf$1$subexpression$1",symbols:["Term$ebnf$1$subexpression$1$ebnf$1",c.has("str")?{type:"str"}:str,c.has("col")?{type:"col"}:col,"Term$ebnf$1$subexpression$1$ebnf$2"]},{name:"Term$ebnf$1",symbols:["Term$ebnf$1$subexpression$1"],postprocess:s},{name:"Term$ebnf$1",symbols:[],postprocess:()=>null},{name:"Term",symbols:["Term$ebnf$1","Value"],postprocess:l},{name:"Value",symbols:[c.has("qstr")?{type:"qstr"}:qstr],postprocess:u},{name:"Value",symbols:[c.has("str")?{type:"str"}:str],postprocess:u},{name:"_$ebnf$1",symbols:[c.has("ws")?{type:"ws"}:ws],postprocess:s},{name:"_$ebnf$1",symbols:[],postprocess:()=>null},{name:"_",symbols:["_$ebnf$1"]},{name:"__",symbols:[c.has("ws")?{type:"ws"}:ws]}],ParserStart:"Expression"};t.default=d},22968:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeRebuildLibrary=t.forceRebuildLibraryLater=t.rebuildLibraryOperationCrit=void 0;const r=i(45393),s=i(28874),n=i(98553),a=i(43487),o=i(54017),l=i(20958),u=i(33567);function c(){return{name:l.OperationNames.rebuildLibrary,value:(0,n.stringify)({AssetVersion:r.AssetVersion,AssetFileVersion:r.AssetFileVersion})}}t.rebuildLibraryOperationCrit=c,t.forceRebuildLibraryLater=function(){a.Asset.dbl.runf((e=>e.update({version:0}))),o.AssetFile.dbl.runf((e=>e.update({version:0}))),l.Operation.dbl.runf((e=>e.where(c()).delete()))},t.maybeRebuildLibrary=async function(){return s.Settings.skipLibraryRebuild.valueOrDefault?void 0:l.Operation.applyOnce_(c(),(()=>(new u.LibraryRebuild).doneLatch))}},33567:function(e,t,i){"use strict";var r,s,n,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LibraryRebuild=void 0;const c=i(19851),d=i(83412),h=i(25764),f=i(8769),m=i(76752),p=i(28874),g=i(15674),y=i(22573),v=i(42659),w=i(31586),b=i(12168),S=i(12236),P=i(35580),_=i(49796),T=i(94710),M=i(18209);class E extends d.DoneWrapper{constructor(){super("LibraryRebuild",(()=>u(this,r,"m",a).call(this)),h.EndableRanks.first),r.add(this),this.assetFileEta=new m.ETA,this.assetEta=new m.ETA,this.assetFilesUpdated=0,this.assetsUpdated=0,this.initialAssetTodoCount=(0,M.outdatedAssetCountSync)(),this.initialAssetFileTodoCount=(0,M.outdatedAssetCountSync)(),this.assetFileTodo=(0,c.lazy)((()=>(0,M.outdatedAssetFileCountSync)()),5*v.secondMs),s.set(this,(0,c.lazy)((()=>_.Progress.insertNew({uri:S.RebuildingURI,volume:"🔄",scanningPct:0})))),o.set(this,((e,t,i)=>{"updateAssetFile"===e.fn?(this.assetFilesUpdated++,this.assetFileEta.push(i),u(this,r,"m",n).call(this)):"repairAsset"===e.fn&&(this.assetsUpdated++,this.assetEta.push(i),u(this,r,"m",n).call(this))})),T.Task.ee.on("resolved",u(this,o,"f")),this.doneLatch.observe(u(this,r,"m",l).call(this))}assetTodo(){return(0,M.outdatedAssetCountSync)()}}t.LibraryRebuild=E,s=new WeakMap,o=new WeakMap,r=new WeakSet,n=async function({force:e=!1,done:t=!1}={}){const i=u(this,s,"f").call(this);if(e||!(0,w.gt)(i.updatedAt,Date.now()-v.secondMs))if((t??this.isDone())&&"done"!==i.state){const e=[];this.assetFilesUpdated>0&&e.push(`Updated file metadata for ${(0,b.fmt)(this.assetFilesUpdated)} files (roughly ${(0,b.fmt)(this.assetFileTodo())} remain).`),this.assetsUpdated>0&&e.push(`Refreshed ${(0,b.fmt)(this.assetsUpdated)} assets (roughly ${(0,b.fmt)(await this.assetTodo())} remain).`),i.dek=e,i.upsert({state:"done",hed:"Finished rebuilding your library 🎉",completePct:100,incompletePct:0,scanningPct:0})}else{let e="Rebuilding your library";const t=this.assetFileTodo(),r=await this.assetTodo(),s=(this.assetFileEta.etaMs(t/(0,g.maxConcurrentImports)())??0)+(this.assetEta.etaMs(r)??0),n=[];t>0&&n.push(`Updating file metadata (${(0,b.fmt)(this.assetFilesUpdated)} processed)`),r>0&&n.push(`Refreshing assets and previews (${(0,b.fmt)(this.assetsUpdated)} processed`);const a=t+r,o=this.assetFilesUpdated+this.assetsUpdated,l=(0,w.clamp)(0,100,Math.round(o/(a+o)*100)),u=(0,m.fmtEstimate)(s);(0,y.notBlank)(u)&&(e+=", "+u+"…"),i.dek=n,i.upsert({state:"processing",hed:e,completePct:l,incompletePct:100-l,scanningPct:0})}},a=function(){T.Task.ee.off("resolved",u(this,o,"f"))},l=async function(){this.logger.info("Starting library rebuild...");const e=p.Settings.forceFilters.getState();try{p.Settings.forceFilters.envValue=!0;const e=P.TaskList.instance(),t=await this.assetFileTodo(),i=await this.assetTodo();if(this.logger.info(".run()",{assetFileTodo:t,assetTodo:i}),0===t&&0===i)return;let s=!1;for(;!s;)s=(await(0,M.enqueueAssetFileUpdates)()).done,this.logger.info("run(): waiting for asset updates to complete..."),await e.awaitDrain(["updateAssetFile"],s?0:p.Settings.taskListCap.valueOrDefault/2);for(s=!1;!s;)s=(await(0,M.enqueueAssetUpdates)()).done,await e.awaitDrain(["repairAsset","assetPostUpsertTasks"],s?0:p.Settings.taskListCap.valueOrDefault/2);await u(this,r,"m",n).call(this,{done:!0,force:!0}),this.logger.info("rebuild complete!")}catch(e){(0,f.onError)("LibraryUpdater.run() failed",e)}finally{p.Settings.forceFilters.setState(e)}}},18209:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.enqueueAssetUpdates=t.outdatedAssetCount=t.enqueueAssetFileUpdates=t.outdatedAssetFileCountSync=t.outdatedAssetCountSync=t.outdatedAssetFileCount=t.currentUriRoots=void 0;const r=i(50213),s=i(45393),n=i(70417),a=i(45200),o=i(5696),l=i(7014),u=i(40958),c=i(45599),d=i(41400),h=i(20214),f=i(54993),m=i(43487),p=i(54017),g=i(94710),y=(0,c.defer)((()=>(0,r.mkLogger)("sync.UpdateQueue")));async function v(){return[...await(0,h.thenCollect)((0,l.volumes)(),(async e=>(0,a.nativePath2uri)(e.mountpoint,e))),o.PSLIB_ROOT_URI].map(f.toS)}t.currentUriRoots=v,t.outdatedAssetFileCount=async function(){const e=await v();return p.AssetFile.dbl.pluckFirstf((t=>t.count("AssetFile.id").distinct().where("version","!=",s.AssetFileVersion).andWhere((t=>e.forEach((e=>t.orWhereLike("AssetFile.uri",e+"%")))))))},t.outdatedAssetCountSync=function(){return m.Asset.outdatedCount()},t.outdatedAssetFileCountSync=function(){return p.AssetFile.dbl.pluckFirstf((e=>e.count("id").where("version","!=",s.AssetFileVersion)))},t.enqueueAssetFileUpdates=async function(){const e=[];for(const t of await v())e.push(await p.AssetFile.dbl.batched({maxResults:g.Task.freeSlots(),onResults:async e=>{const t=[];for(const i of e)t.push({fn:"updateAssetFile",args:{assetFileId:i.id,path:await(0,a.uri2nativePath)(i.uri),skipAssetRepair:!0}});g.Task.add(t),y().info("Scheduled updateAssetFile",{tasks:t})},qb:(e,i)=>(e=e.select({id:"AssetFile.id",uri:"AssetFile.uri"}).distinct().orderBy("AssetFile.id","asc").where("AssetFile.version","!=",s.AssetFileVersion).andWhereLike("AssetFile.uri",t+"%"),(0,u.isNotEmpty)(i)&&(e=e.andWhere("AssetFile.id",">",(0,n.max)(i.map((e=>e.id))))),e)}));return y().tap({msg:"enqueueAssetFileUpdates",level:"info",result:{done:e.every((e=>e.done)),tasksAdded:(0,n.sumf)(e,(e=>e.resultCount))}})},t.outdatedAssetCount=async function(){const e=await v();return m.Asset.dbl.pluckFirstf((t=>t.count("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").where("Asset.version","!=",s.AssetVersion).andWhere((t=>e.forEach((e=>t.orWhereLike("AssetFile.uri",e+"%")))))))},t.enqueueAssetUpdates=async function(){const e=[];for(const t of await v())e.push(await m.Asset.dbl.pluckBatched({maxResults:g.Task.freeSlots(),onResults:e=>(g.Task.add(e.map((e=>({fn:"repairAsset",args:{assetId:e}})))),y().info("Scheduled repairAsset for ",{assetIds:e}),(0,d.delay)(1)),qb:(e,i)=>(e=e.select("Asset.id").distinct().leftJoin("AssetFile","AssetFile.assetId","Asset.id").orderBy("Asset.id","asc").where("Asset.version","!=",s.AssetVersion).andWhereLike("AssetFile.uri",t+"%"),(0,u.isNotEmpty)(i)&&(e=e.andWhere("Asset.id",">",(0,n.max)(i))),e)}));return y().tap({msg:"enqueueAssetUpdates",level:"info",result:{done:e.every((e=>e.done)),tasksAdded:(0,n.sumf)(e,(e=>e.resultCount))}})}},3996:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=t.isFileInSync=void 0;const a=i(19851),o=i(50213),l=i(79781),u=i(56519),c=i(56038),d=i(59189),h=i(38835),f=i(95696),m=i(48368),p=i(181),g=i(69589),y=i(28874),v=i(28544),w=i(47783),b=i(87001),S=i(40958),P=i(76790),_=i(22573),T=i(42659),M=i(55835),E=i(31586),k=i(43487),D=i(54017);t.isFileInSync=async function(e){return new C(f.PosixFile.for(e)).alreadySynced()};const x=new d.SerialLaterQueue;class C{constructor(e,t=(0,g.forceContextOrSetting)()){this.file=e,this.ctx=t,r.set(this,void 0),this.rejectedAssetIds=new Set,this.rejectedSiblingIds=new Set,this.alreadySynced=(0,c.timedLazy)("sync-file.AssetFileFinder.alreadySynced: "+this.file,(async()=>n(this,r,"f").tap({msg:"alreadySynced",result:null!=await this.priorIfSynced()}))),this.newAssetFile_=(0,c.timedLazy)("sync-file.AssetFileFinder.newAssetFile: "+this.file,(async()=>{const e=await(new D.AssetFile).updateFromFile_(this.file);return null==e?n(this,r,"f").throw("AssetFile.updateFromFile returned null",{fatal:!1}):e})),this.tags_=(0,a.lazy)((async()=>{const e=await(0,w.readTags)(this.file);if(null==e)throw new Error(this.file+" doesn't have metadata");return e})),this.imageHash=(0,a.lazy)((()=>y.Settings.useImageHashes.valueOrDefault?(0,m.imageHash)(this.file):void 0)),this.dominantLabhashes=(0,a.lazy)((()=>(0,u.thenMap)(this.imageHash(),(e=>(0,S.uniq)(e.dominantColors.filter((e=>e.pct>5)).map((e=>e.labhash))))))),this.capturedAtLocal=(0,a.lazy)((async()=>{const e=await this.capturedAt_();return n(this,r,"f").tap({msg:"capturedAtLocal",result:e?.local,meta:{capturedAt:e}})})),this.mapSibling=e=>this.newAssetFileForAsset(e?.getAsset()),this.apply_=(0,c.timedLazy)("sync-file.AssetFileFinder: "+this.file,(async()=>{if((0,_.blank)(await this.file.uri_()))throw new Error("Cannot import, file URI is blank for "+this.file);{const e=await this.byExistingAsset_();if(null!=e)return n(this,r,"f").info("Found existing asset for file"),e}const e=await this.newAssetFile_(),t=await x.enqueue((async()=>{const t=await this.byExistingAsset_();if(null!=t?.assetId)return n(this,r,"f").info("Found existing asset for file after acquiring lock",{withExistingAsset:t}),t.assetId;const i=new k.Asset;return i.capturedAtLocal=e.capturedAtLocal,i.addAssetFile(e),i.upsert(),i.id}));return e.assetId=t,e.upsert()})),this.byExistingAsset_=()=>(0,c.time)("sync-file.AssetFileFinder.byExistingAsset: "+this.file,(async()=>{const e=[{name:"byUri",f:()=>this.byUri()},{name:"byNormalizedPathUri",f:()=>this.newAssetFileForAsset(this.assetByNormalizedPathUri())},{name:"bySha",f:()=>this.newAssetFileForAsset(this.assetBySha())},{name:"hasTags",f:async()=>{await this.tags_()}},{name:"validFile",f:async()=>{await(0,p.throwIfInvalidFile_)(this.file)}},{name:"byCapturedAtOrImageHash",f:()=>this.newAssetFileForAsset(this.assetByCapturedAtAndImageHash())}];for(const{name:t,f:i}of e)try{const e=await(0,c.time)("sync-file.assetFileFinder."+t+": "+this.file,i);if(null!=e)return n(this,r,"f").info("apply(): "+t,{assetFileId:e.id,assetId:e.assetId}),e;n(this,r,"f").debug("apply(): "+t+": returned null")}catch(e){throw n(this,r,"f").debug("apply(): "+t+" rejected: "+e),e}})),s(this,r,(0,o.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")"),"f")}async prior(){return this.byUri()}async priorIfSynced(){if(this.ctx.forceSync)return;const e=await this.prior();return!0===await(e?.matchesFile())?e:void 0}async newAssetFileForAsset(e){const t=await e;if(null!=t){if(null!=t.id){const e=await this.newAssetFile_();return t.addAssetFile(e),e.insert(),n(this,r,"f").debug("newAssetFileForAsset() upsert success!",{af:e}),e}n(this,r,"f").throw("newAssetFileForAsset(): given non-persisted Asset")}}async capturedAt_(){return(await this.tags_()).capturedAt}async byUri(e=this.file){const t=await e.uri_();if(null!=t)return D.AssetFile.ops().firstf((e=>e.whereIn("uri",[...(0,b.uriEncodingVariants)(t),this.file.fileuri()])));n(this,r,"f").warn("byUri() uri is null",{file:e})}async assetByNormalizedPathUri(){const e=await this.file.normalize();return e.nativePath===this.file.nativePath?void 0:(await this.byUri(e))?.getAsset()}async assetBySha(){const e=await this.file.sha_();return k.Asset.findFirstByFile((t=>(t=t.where("AssetFile.sha",e),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds))),this.rejectedSiblingIds.size>0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),t)))}async assetByCapturedAtAndImageHash(){const e=await this.capturedAt_();if(null==e)return n(this,r,"f").throw("Cannot import, capturedAt is null"+h.InternalErrorFlag);if(y.Settings.strictDeduping.valueOrDefault)return this.firstSimilarAsset(D.AssetFile.ops().allf((t=>t.where({capturedAtLocal:e.local}))));const t=y.Settings.maxContemporaryAdoptionAssets.valueOrDefault,i=()=>{let i=D.AssetFile.query();return(0,E.gt0)(t)&&(i=i.limit(t)),i.orderByRaw(`abs(capturedAtLocal - ${e.local})`)},s=Math.max(T.secondMs,y.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault);return(0,c.time)("sync-file.AssetFileFinder.assetByCapturedAtAndImageHash: "+this.file,(async()=>{{const t=e.localBoundaries({delta:s});if(null==t)n(this,r,"f").warn("Failed to fetch localBoundaries, cannot fetch similar assets by localtime",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("captured-at",i().whereBetween("capturedAtLocal",[t.start,t.end]))??(y.Settings.checkBasenameMatches.valueOrDefault?this.firstSimilarAssetByQuery("basename",i().whereILike("uri","%/"+this.file.name+"%")):void 0);if(null!=e)return e}}const t=await this.imageHash();if(null==t)return void n(this,r,"f").warn("assetByCapturedAtAndImageHash: no imageHash");const a=await this.dominantLabhashes();if((0,S.isNotEmpty)(a)){const t=e.localBoundaries({delta:4*s});if(null==t)n(this,r,"f").error("Failed to fetch localBoundaries, cannot fetch similar assets by wide localtime + image hash",{ca:e,delta:s});else{const e=this.firstSimilarAssetByQuery("wide captured-at and dominant color",i().whereBetween("capturedAtLocal",[t.start,t.end]).andWhere((e=>e.whereIn("mode0",a).orWhereIn("mode1",a).orWhereIn("mode2",a))));if(null!=e)return e}}const o=this.firstSimilarAssetByQuery("image hash",i().where("meanHash",t.meanHash).orWhere("diffHash",t.diffHash).orWhere("dctHash",t.dctHash));if(null!=o)return o;if(y.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const r={};for(let e=0;e0&&(t=t.whereNotIn("AssetFile.id",Array.from(this.rejectedSiblingIds))),this.rejectedAssetIds.size>0&&(t=t.whereNotIn("AssetFile.assetId",Array.from(this.rejectedAssetIds)));const i=await this.firstSimilarAsset(D.AssetFile.ops().all(t));return null!=i&&n(this,r,"f").info("Found similar asset by "+e,{result:i}),i}async firstSimilarAsset(e){const t=await this.newAssetFile_(),i=await this.capturedAtLocal();if(null==t)throw new Error("Failed to update from "+this.file);const s=(0,P.sortBy)(e.filter((e=>!this.rejectedSiblingIds.has(e.id)&&!this.rejectedAssetIds.has(e.assetId))),(e=>[(0,M.mapOr)(i,(t=>Math.abs(e.capturedAtLocal-t)),-e.capturedAtLocal),e.id]));for(const e of s)if(null!=e){await e.getNativePath();const i=D.AssetFile.ops().findBy({assetId:e.assetId});await Promise.all(i.map((e=>e.getNativePath())));const s=(0,l.whyNotSameAsset)(t,e,i);if(null==s)return n(this,r,"f").info("Found sibling AssetFile",e),k.Asset.ops().findById(e.assetId);this.rejectedSiblingIds.add(e.id),n(this,r,"f").debug("Contemporary assetFile not similar: "+s,e?.uri)}}}t.AssetFileFinder=C,r=new WeakMap},34274:function(e,t,i){"use strict";var r,s,n,a,o=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=t.importFileToResult_=void 0;const u=i(19851),c=i(50213),d=i(73568),h=i(38835),f=i(95696),m=i(62105),p=i(74128),g=i(181),y=i(69589),v=i(28874),w=i(40958),b=i(22573),S=i(38639),P=i(59455),_=i(64526),T=i(19113),M=i(94710),E=i(3996),k=i(90901);t.importFileToResult_=async function(e){const t=_.Library.instanceRequired_();return(0,p.syncReport)().wrap_({path:e.path,from:"AssetFileImporter",fn_:()=>new D(f.PosixFile.for(e.path),t.assetFileRepository(),e).apply_()})};class D{constructor(e,t,i){r.add(this),this.file=e,this.repo=t,this.start=Date.now(),s.set(this,void 0),n.set(this,void 0),this.whyRejected=(0,u.lazy)((async()=>{const e=[],t=await this.file.uri_();if(null==t)e.push("Cannot make URI"+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);else{if(!0===await this.file.isDeletedUri(t))e.push("File was deleted");else if(this.ctx.forceFilters||null==await this.prior()){const t=await(0,m.whyRejectFile)(this.file,(0,T.libraryFileFiltersFor)(this.file));null!=t&&e.push(t)}l(this,s,"f").throwIfAborted_();const i=await this.prior();if((0,w.isNotEmpty)(e)&&null!=i&&(l(this,s,"f").info("Deleting prior AssetFile",{rejected:e,prior:i}),i.delete(),this.ctx.skipAssetRepair?l(this,s,"f").info("Skipping asset repair",{assetId:i.assetId}):(l(this,s,"f").info("Scheduling asset repair",{assetId:i.assetId}),M.Task.addOne("repairAsset",{assetId:i.assetId,forceRebuildPreviews:(0,S.isTrue)(i.shown)}))),null!=i){const t=i.getAsset();null!=t?.deletedAt&&e.push("Asset is marked as deleted"),null!=t?.excludedAt&&e.push("Asset is marked as excluded")}if(l(this,s,"f").throwIfAborted_(),0===e.length&&(null==i||!await i.inSyncWithFile())){const t=await(0,g.whyInvalidFile)(this.file.nativePath);(0,b.blank)(t)||e.push(t)}}return e})),this.assetFile_=(0,u.lazy)((async()=>{const e=await l(this,n,"f").apply_(),t=e.getAsset();return l(this,s,"f").info("assetFileFinder.apply_() result",{asset:t,assetFile:e}),null==t?l(this,s,"f").throw("assetFile.getAsset() was null",{srcAssetFile:e}):null==t.id?l(this,s,"f").throw("repoAssetFile asset has null id",{asset:t}):e})),this.prior=(0,u.lazy)((()=>l(this,n,"f").prior())),this.apply_=(0,u.lazy)((()=>l(this,r,"m",a).call(this))),this.ctx=(0,y.forceContextOrSetting)(i),o(this,s,(0,c.mkLogger)("sync-file."+this.toString()),"f"),o(this,n,new E.AssetFileFinder(e,this.ctx),"f")}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return l(this,n,"f").newAssetFile_()}}t.AssetFileImporter=D,s=new WeakMap,n=new WeakMap,r=new WeakSet,a=async function(){l(this,s,"f").throwIfAborted_();const e=await l(this,s,"f").tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if((0,w.isNotEmpty)(e)){const t=e.join(", ");return{path:this.file.nativePath,state:p.SyncFileStates.rejected,details:t}}l(this,s,"f").throwIfAborted_();const t=await l(this,s,"f").tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.isNoop(this.ctx))return{path:this.file.nativePath,state:p.AssetFileSyncStates.noop,assetId:t.assetId,assetFileId:t.id,assetFile:t,asset:t.getAsset(),uri:t.uri};l(this,s,"f").throwIfAborted_();const i=await l(this,s,"f").tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return l(this,s,"f").throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return l(this,s,"f").throw("_apply(): unexpected null assetFileId");const n=i.uri;if(null==n)return l(this,s,"f").throw("_apply(): unexpected null assetFile.uri");const a=i.getAsset();if(null==a)return l(this,s,"f").throw("_apply(): unexpected null assetFile.getAsset()");let o;await l(this,s,"f").tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault}),l(this,s,"f").throwIfAborted_();try{o=await(0,k.assetPostUpsertTasks_)({asset:a,...this.ctx})}catch(e){e instanceof d.AbortError?l(this,s,"f").warn("aborted (caller/process after me will complete)",{error:e}):l(this,s,"f").throw("Post-upsert tasks failed",{error:e})}return{path:this.file.nativePath,state:i.syncState??p.SyncFileStates.synced,assetId:a.id,assetFileId:r,assetFile:i,asset:a,uri:n,uris:[n,...(0,P.toA)(o?.newAssetFileUris)]}}},41844:function(e,t,i){"use strict";var r,s,n,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=t.mayCopyAssetsToLibrary=void 0;const u=i(50213),c=i(74128),d=i(81674),h=i(57902),f=i(4936),m=i(28874),p=i(47783),g=i(14245),y=i(67083),v=i(16170),w=i(54979),b=i(98604),S=i(40958),P=i(22573),_=i(98553),T=i(68708),M=i(89937),E=i(59455),k=i(54017),D=i(94710);t.mayCopyAssetsToLibrary=async function(){return m.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,d.p)()},t.AssetFileRepository=class{constructor(e){r.add(this),this.originalsDir=e,this.logger=(0,u.mkLogger)("AssetFileRepository")}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,P.blank)(e.nativePath))return"blank nativePath";if(!0!==m.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,d.l)())return"no active subscription";if(await e.notExists({refresh:!0}))return"file doesn't exist";if(e.isDescendantOf(this.originalsDir))return e+" already contained by "+this.originalsDir;if(e.isDescendantOf(m.Settings.libraryDir.valueOrDefault))return e+" already contained by "+m.Settings.libraryDir.valueOrDefault;const t=await(0,w.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,v.isMimeTypeIncluded)(t,m.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(M.PS_LIBRARY_PROTOCOL))return e;const t=(0,S.uniqBy)((0,E.toA)(e.librarySiblings()?.filter((t=>t.sha===e.sha))).concat(k.AssetFile.sameAssetFileInLibrary(e)),(e=>e.id));for(const i of t)if(await i.exists()){if(i.assetId!==e.assetId){this.logger.warn("Existing library asset file with a matching SHA is associated to a different asset. Requesting repair of the two impacted assets.",{af:e,prior:i});const t=i.assetId;e.getAsset()?.addAssetFile(i),D.Task.addOne("repairAsset",{assetId:t,forceSync:!0})}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e){const t=await l(this,r,"m",s).call(this,e);return null!=t&&(await l(this,r,"m",n).call(this,e,t),await l(this,r,"m",o).call(this,e,t)),t}async maybeCopyToLibrary_(e,t){const i=Date.now(),s=await e.posixFile_();null==s&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(s);if(!(0,P.blank)(e))return this.logger.tap({level:h.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const a=e.getAsset();null==a&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const u=await this.existingLibraryAssetFile(e);if(null!=u){const e=await u.posixFile_();if(null!=e){const d=await l(this,r,"m",n).call(this,s,e),h=null!=await l(this,r,"m",o).call(this,s,e),f=null!=await u.upsertIfNeeded_(void 0,t);return!h&&(0,S.isEmpty)(d)&&!f||(0,c.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.synced,details:"Found and synced prior replica already in your library "+(0,_.stringify)({src:s.nativePath,upsertNeeded:f,copiedSidecars:d,copiedInferredMetadata:h}),elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),u}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:u})}}const u=await this.importFile_(s);if(null==u)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(u.nativePath===s.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:u});const d=await a.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);const f=d.upsert();return a.addAssetFile(d),(0,c.syncReport)().onProgress({path:u.nativePath,from:"maybeCopyToLibrary()",state:c.SyncFileStates.copied,details:"Copied into your library from "+s.nativePath,elapsedMs:Date.now()-i,url:(0,b.mkAssetUrl)(a.id)?.toString()}),f}},r=new WeakSet,s=async function(e){const t=await(0,p.readCapturedAt)(e),i=(0,f.pathToLibraryAsset)(t?.date,e);if(this.logger.debug("importFile("+e+")",{capturedAt:t,assetPath:i}),null==i)throw new Error(e.nativePath+" failed to create a library path");const r=this.originalsDir.join(...i),s=await this.findLibraryFileWithSameContents(e,r);if(null!=s)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:s}),s;const n=await r.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:n,dest:r}),e.copyFile_(n)},n=async function(e,t){const i=await e.existingSidecars(),s=[];for(const e of i)s.push(await l(this,r,"m",a).call(this,e,t));return(0,S.compact)(s)},a=async function(e,t){for(const i of await t.existingSidecars())if(await(0,p.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)},o=async function(e,t){if(null==e||null==t||e.eql(t))return;const i=await(0,p.readTags)(e);if(null!=i){if(m.Settings.writeGeolocationTagsToLibraryCopies.valueOrDefault){const e=(0,g.geolocationToXmp)(i);(0,T.isEmptyObj)(e)||await(0,p.writeTags_)(t,e)}return(0,y.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred)}this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}},90901:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPostUpsertTasks_=t.assetPostUpsertTasks=void 0;const r=i(50213),s=i(92434),n=i(73568),a=i(99331),o=i(39250),l=i(38835),u=i(57159),c=i(48604),d=i(66106),h=i(69589),f=i(40958),m=i(45599),p=i(23838),g=i(31586),y=i(64526),v=i(88224),w=i(43487),b=i(41844),S=i(68640),P=(0,m.defer)((()=>(0,r.mkLogger)("sync-file.AssetPostUpsertTasks"))),_=(0,m.defer)((()=>new o.LastOneInWins("Asset tasks")));async function T(e){const t=e,i=e,r=(0,g.toGt0)(t.asset?.id)??(0,g.toGt0)(i.assetId);if(null==r)throw new Error("assetPostUpsertTasks_(): unexpected null assetId"+l.InternalErrorFlag);const o=(0,h.forceContextOrSetting)(e),m=P().addContext(`.postUpsertAssetTasks_(Asset:${r})`);if(m.abortable=o.halt,o.skipPreviews&&o.skipAssetTagging)return void m.info("skipped (skipPreviews && skipAssetTagging)");const T=t.asset??w.Asset.ops().findById(r);if(null==T)return m.throw("unexpected null asset",{asset:T});try{return await _().enqueue({key:r,abortable:m.abortable,fn:()=>async function(e,t,i){const r=(0,h.forceContextOrSetting)(i),n=t.id,a=t.getAssetFiles({refresh:!0}),o={newAssetFileUris:[],previewsUpdated:!1,tagResult:void 0,transcoded:!1};if(e.throwIfAborted_(),(0,f.isEmpty)(a)&&(await w.Asset.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${n} had no asset files. Deleted.`)),await(0,b.mayCopyAssetsToLibrary)())for(const[t,i]of(0,p.groupBy)(a,(e=>e.sha)).entries()){e.throwIfAborted_();try{for(const r of i)r.isInLibrary()&&await r.exists()&&e.debug("no-op for file SHA: already in library.",{sha:t,uri:r.uri});for(const e of i)if(await e.exists()){const t=await y.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,r);if(null!=t){o.newAssetFileUris.push(t.uri);continue}}}catch(r){e.warn("Failed to copy variation to library, but we'll try to continue",{sha:t,uris:i.map((e=>e.uri)),error:r})}}e.throwIfAborted_();const l=r.skipPreviews?void 0:await(0,S.updateAssetPreviews_)({asset:t,assetFiles:t.getAssetFiles(),...r}),u=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles({refresh:!0}).find((e=>e.id===t?.assetFileId));return null==i?P().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):i}const i=e.getShown();return null!=i?i:(0,s.bestExistingAssetFile)(e.getAssetFiles())}(t,l);if(null==u)return e.throw("null primaryOrShownAssetFile_()",{asset:t});const m=await u.posixFile_();if(!0!==r.skipPreviews&&t.isVideo()){if(null==m)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});o.transcoded=null!=await(0,d.transcode_)(m,c.Previews.instance().ap(n).mp4(),{force:r.forceRebuildPreviews,halt:r.halt})}return e.throwIfAborted_(),t.markShownAndUpsert_(u),r.skipAssetTagging?e.info("skipping asset tagging"):o.tagResult=await(0,v.tagAndUpsertAsset_)(t),o}(m,T,{...e,...o})})}catch(e){if(e instanceof n.AbortError)return void m.warn("aborted, next caller will clean up my mess",{error:e});const t=[e];if(!(0,a.ending)()){m.error("failed, marking asset unshown",{error:e});try{T.markUnshownAndUpsert()}catch(e){m.error("failed to mark asset unshown",{upsertError:e}),t.push(e)}}throw new u.WrappedError("Failed to post-process assset "+T.id,{causes:t})}}t.assetPostUpsertTasks=function(e){try{return T(e)}catch(e){if(e instanceof n.AbortError)return void P().warn("aborted, next caller will clean up my mess",{error:e});throw e}},t.assetPostUpsertTasks_=T},61989:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAsset_=t.updateAsset=void 0;const r=i(48884),s=i(50213),n=i(45393),a=i(79184),o=i(79781),l=i(92434),u=i(56519),c=i(70417),d=i(69589),h=i(28874),f=i(40958),m=i(22573),p=i(38639),g=i(50357),y=i(43487),v=i(54017),w=i(3996),b=i(90901);async function S(e){const t=(0,d.forceContextOrSetting)(e),i=e.assetId,r=(0,s.mkLogger)(`sync-file.UpdateAsset(${i})`);r.abortable=t.halt;const S=y.Asset.ops().findById(i);if(null==S)return r.throw("no such asset");const _=S.getAssetFiles({refresh:!0});if((0,f.isEmpty)(_))return r.warn("No asset files: deleting."),S.delete(),{asset:S,rejected:"Empty asset (no AssetFiles)"};const T=S.$clone(),M=S.getShown()?.$clone();for(const e of _)r.throwIfAborted_(),await e.upsertIfNeeded_(void 0,t);_.some((e=>(0,p.isTrue)(e.deleted)||(0,m.notBlank)(e.rejected)))&&S.clear(),await P(r,_);const E=(0,l.sortAssetFiles)(_),k=E?.[0];if((0,f.isEmpty)(E)||null==k)return r.warn("No existing files. Skipping for now."),S.markUnshownAndUpsert(),{asset:S,rejected:"Empty asset (no AssetFiles after sorting). Un-showing Asset:"+i};if(!k.isVersionUpToDate())return r.warn("Best file needs update, and we already tried to update all files. Skipping this asset.",{bestAcceptedAF:k}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${k.id}, could not be updated. Un-showing Asset:${i}`};const D=await k.capturedAt();if(null==D)return r.warn("Best file failed to extract a captured-at",{bestAcceptedAF:k}),S.markUnshownAndUpsert(),{asset:S,rejected:`Best AssetFile:${k.id}, failed to extract a captured-at. Un-showing Asset:${i}`};const x=new Set,[C,A]=await(0,u.partitionAsync)(E,(e=>(0,o.isSimilarAssetFile)(e,k)));if(r.throwIfAborted_(),(0,f.isNotEmpty)(A)){const e=await(0,a.aggregateAssetFiles)(A);for(const t of e){if((0,f.isEmpty)(t))continue;const e=y.Asset.ops().insertOne({capturedAtLocal:t[0].capturedAtLocal,shown:!1,version:0});x.add(e.id);for(const i of t)e.addAssetFile(i);v.AssetFile.dbl.runf((i=>i.update({assetId:e.id,shown:0}).whereIn("id",(0,f.compact)(t.map((e=>e.id)))))),r.info("Pushed rejected asset files into new asset",{rejectAssetId:e.id,rejectCluster:t.map((e=>({id:e.id,uri:e.uri})))})}}function F(e){return(0,f.uniq)(C.map((t=>t[e])))}const I=await Promise.all(C.map((e=>e.capturedAt()))),O=h.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,L=I.map((e=>e?.localBoundaries({delta:O}))),R=(0,c.min)(L.map((e=>e?.start)))??D.localBoundaries({delta:O})?.start,N=(0,c.max)(L.map((e=>e?.end)))??D.localBoundaries({delta:O})?.end,B=v.AssetFile.ops().all(v.AssetFile.query().limit(h.Settings.maxContemporaryAdoptionAssets.valueOrDefault).orderByRaw(`abs(AssetFile.capturedAtLocal - ${k.capturedAtLocal})`).select("AssetFile.*").distinct().join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.assetId","!=",i).andWhere("Asset.version","!=",n.AssetVersion).andWhere((e=>(e=e.whereIn("AssetFile.sha",F("sha")),null==R||null==N?r.warn("external asset file check: unset start or end localtime boundary",{capturedAts:I,startBoundary:R,endBoundary:N}):e=e.orWhereBetween("AssetFile.capturedAtLocal",[R,N]),e.orWhereIn("AssetFile.meanHash",F("meanHash")).orWhereIn("AssetFile.diffHash",F("diffHash")).orWhereIn("AssetFile.dctHash",F("dctHash"))))));if(r.throwIfAborted_(),h.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const e=await k.posixFile();if(null==e)r.info("bestAcceptedAF has no posixFile, cannot expand query for fuzzy dates",{bestAcceptedAF:k});else{const i=new w.AssetFileFinder(e,t);for(const e of[...C,...B])i.rejectedAssetIds.add(e.assetId),i.rejectedAssetIds.add(e.id);let s=h.Settings.maxContemporaryAdoptionAssets.valueOrDefault;for(;--s>0;){r.throwIfAborted_();const e=await i.assetByCapturedAtAndImageHash();if(null==e){r.info("allowFuzzyDateImageHashMatches(): no additional assets found to adopt");break}if(r.info("allowFuzzyDateImageHashMatches(): found asset with similar image",{a:e}),null!=e){i.rejectedAssetIds.add(e.id);for(const t of e.getAssetFiles())r.info("found asset file by fuzzy date and image hash",{uri:t.uri,assetId:e.id}),B.push(t),i.rejectedAssetIds.add(t.id)}}}}r.info("asset file candidates for adoption: ",B.map((e=>e.posixPathFromGrandparent)));const j=[];for(const e of B){r.throwIfAborted_();try{await e.updateFromFile_(),(0,o.isSimilarAssetFile)(e,k)&&(r.info("adopting similar asset file",{af:e}),x.add(e.assetId),e.shown=!1,S.addAssetFile(e),e.upsert(),j.push(e))}catch(t){r.warn("Error updating external asset file. Leaving asset file record as-is.",{af:e,error:t})}}r.info("fetched expansion",{retainAFs:C.map((e=>e.id)),rejectAFs:A.map((e=>e.id)),externalAssetFiles:B.map((e=>e.posixPathFromGrandparent)),similarAssetFiles:j.map((e=>e.posixPathFromGrandparent))}),await P(r,[...C,...j]),t.skipPreviews&&t.skipAssetTagging?(r.info("skipping previews and tagging",t),S.upsert()):await(0,b.assetPostUpsertTasks_)({...t,asset:S});const z=!(0,g.eql)(T,S),V=!(0,g.eql)(M,S.getShown()),W=!(z||V||t.forceRebuildPreviews||t.forceSync);return r.tap({msg:"updateAsset() result",level:"info",result:{asset:S,assetIdsToUpdate:Array.from(x),assetFiles:S.assetFiles,skipped:W},meta:{ctx:t,assetChanged:z,primaryAssetFileChanged:V}})}async function P(e,t){const[i,s]=(0,r.partition)(t,(e=>e.isVersionUpToDate()));for(const t of s){e.throwIfAborted_();const r=i.find((e=>e.sha===t.sha));if(null!=r){e.info("backfilling",{sibling:r,dest:t});const i=await t.updateFromShaSibling_(r);null!=i&&i.upsert()}}}t.updateAsset=async function(e){try{const t=await S(e);return{id:e.assetId,skipped:null==t?.asset,...t}}catch(t){return{id:e.assetId,error:t}}},t.updateAsset_=S},93755:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFileIfNeeded=t.handleAssetFileUriChange=t.updateAssetFile_=t.updateAssetFile=void 0;const r=i(50213),s=i(92434),n=i(98314),a=i(74128),o=i(69589),l=i(87001),u=i(40958),c=i(22573),d=i(68708),h=i(43487),f=i(54017),m=i(94710);async function p(e){const t=Date.now(),i=e,s=e,n=s.af?.id??i.assetFileId,u=(0,r.mkLogger)(`updateAssetFile(${n})`),d=s.af??f.AssetFile.ops().findById(n);if(null==d)return u.throw("db record not found",{assetFileId:n});const h=await d.posixFile_(),p=(0,o.forceContextOrSetting)(e),v={id:n,assetFileId:n,path:h?.nativePath,uri:d?.uri};if(null==h){const e=["cannot resolve URI"];return(0,c.blank)(d.mountpoint)||e.push("is "+d.mountpoint+" mounted?"),(0,a.syncReport)().onProgress({path:d.uri,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:e.join(": "),state:a.SyncFileStates.skipped}),{...v,error:"file for URI not found"}}const w=await(h?.isDeletedUri(d.uri));if(null==w)return u.info("no-op: file URI points to an unmounted volume",v),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:((0,c.toNotBlank)(d.mountpoint)??"volume")+" is not currently mounted",state:a.SyncFileStates.skipped}),{...v,skipped:!0};const b=e.whyReject??await d.whyRejected();if(w||!(0,c.blank)(b)){const e={...v,rejected:b,deleted:w};return u.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:h.nativePath,elapsedMs:Date.now()-t,from:"updateAssetFile_()",details:w?"file no longer exists":"rejected: "+b,state:a.SyncFileStates.deleted}),d.delete(),!0!==p.skipAssetRepair&&m.Task.addOne("repairAsset",{assetId:d.assetId}),e}const S=await h.uri_();if(!await(0,l.uriIsEquivalent)(S,d.uri)){const e=await g(d,S,p);if(null!=e)return{...v,...e}}return!p.forceSync&&await d.matchesFile()?(u.info("no-op: file already matches db record",v),d.touch(),{...v,skipped:!0}):{...v,...await y(d,p)}}async function g(e,t,i){const n=(0,r.mkLogger)(`handleAssetFileUriChange(${e.id})`),a=(0,u.uniq)([...(0,l.uriEncodingVariants)(e.uri),...(0,l.uriEncodingVariants)(t)]);n.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:a});const o=f.AssetFile.ops().allf((t=>t.whereIn("uri",a).andWhereNot({id:e.id})));if((0,u.isNotEmpty)(o)){n.warn("Found other AssetFiles with equivalent URIs.",{afIds:o.map((e=>e.id))});const t=[e,...o],r=(0,s.sortAssetFiles)(t);if((0,u.isEmpty)(r))return n.warn("sortAssetFiles returned undefined",{arr:t.map((e=>(0,d.pick)(e,"id","uri"))),variants:a}),{error:"sortAssetFiles returned undefined"};const l=t.map((e=>e.id));for(const e of r)if(await e.exists()){f.AssetFile.dbl.runf((t=>t.whereIn("id",l.filter((t=>t!==e.id))).delete()));const r=y(e,i);return h.Asset.dbl.runf((e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,u.uniq)(t.map((e=>e.assetId)))))),r}}n.info("no-op, no duplicate URIs.")}async function y(e,t){const i=Date.now();return null!=await e.upsertIfNeeded_(void 0,t)&&h.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:await e.getNativePath(),elapsedMs:Date.now()-i,from:"updateAssetFileIfNeeded()",state:e.syncState??a.SyncFileStates.unknown}),{assetFileId:e.id}}t.updateAssetFile=async function(e){try{return await p(e)}catch(t){return{id:e.assetFileId,...e,error:(0,n.errorToS)(t)}}},t.updateAssetFile_=p,t.handleAssetFileUriChange=g,t.updateAssetFileIfNeeded=y},68640:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=void 0;const r=i(99331),s=i(38835),n=i(48604),a=i(50213),o=i(69589),l=i(87001),u=i(40958),c=i(45599),d=i(50357),h=i(31586),f=i(68708),m=i(59455),p=i(43487),g=(0,c.defer)((()=>(0,a.mkLogger)("sync-file.UpdateAssetPreviews")));t.updateAssetPreviews_=async function(e){const t=e.assetId??e.asset?.id??(0,m.toA)(e.assetFiles).find((e=>(0,h.gt0)(e.assetId)))?.assetId,i=(0,o.forceContextOrSetting)(e),a=g().addContext(".Asset:"+t);if(i.skipPreviews)return void a.warn("skipPreviews is true: no-op");if(!(0,h.gt0)(t))return a.throw("invalid assetId",{assetId:t});const c=e.asset??p.Asset.ops().findById(t);if(null==c)return a.throw("Asset:"+t+" not found");a.throwIfAborted_(i.halt);try{const e=await c.getExistingAssetFiles();if((0,u.isEmpty)(e))return void a.warn("no existing assetFiles",{asset:c});const r=n.Previews.instance().ap(t),o=await r.readInfo();a.throwIfAborted_(i.halt);const h=await(0,n.buildAssetPreviews_)({...i,assetId:t,assetFiles:e}),m=e.find((e=>e.id===h?.assetFileId))??e.find((e=>(0,l.uriIsEquivalent)(h?.uri,e.uri)));a.info("buildAssetPreviews_()",{result:h,primaryAssetFile:m});const p=await(m?.posixFile_());if(null==m||null==p||!0!==await(p?.exists()))return a.throw("buildAssetPreviews_() returned invalid assetFileId"+s.InternalErrorFlag,{newInfo:h,assetFiles:e.map((e=>(0,f.pick)(e,"id","uri"))),primaryAssetFile:m,primaryPosixFile:p});const g=(0,d.eql)(o,h),y=null==h||g;return{...h,noop:y}}catch(e){throw(0,r.ending)()||(a.warn("Failed to update previews. Un-showing asset "+t,{error:e}),c.markUnshownAndUpsert()),e}}},94019:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsToSync=t.scanPaths=t.logger=void 0;const r=i(19851),s=i(50213),n=i(56519),a=i(87290),o=i(34102),l=i(16287),u=i(45969),c=i(43334),d=i(28874),h=i(45200),f=i(69375),m=i(7014),p=i(41400),g=i(31586),y=i(92244),v=i(46832);t.logger=(0,r.lazy)((()=>(0,s.mkLogger)("sync.PathsToSync")));const w=(0,r.lazy)((async()=>{const e=[];for(const t of await(0,m.volumes)()){if(!0===t.ignorable||!1===t.ok||(c.isMac||(0,u.isDocker)())&&"/"===t.mountpoint||(0,f.isExcludedMountpoint)(t.mountpoint)||!(0,g.gt0)(t.size))continue;const i=await(0,v.toUriPath)(t.mountpoint,(0,h.nativePath2uri)(t.mountpoint,t));null!=i&&e.push(i)}return e}));async function b(){const e=[],i=[],r=d.Settings.argvScanPaths.toNotEmpty()??d.Settings.scanPaths.values;for(const s of r)if(await(0,l.isReadableDirectory)(s)){const r=await(0,v.toUriPath)(s);null==r?(e.push(s),(0,t.logger)().warn("Ignoring scanPath element: failed to create URI path",s)):i.push(r)}else(0,t.logger)().warn("Ignoring scanPath element: not readable directory",s);return{result:i,noUriPaths:e}}t.scanPaths=b,(0,p.later)((()=>{(0,o.ee)().on("volumesChanged",(()=>{w.unset()}))})),t.pathsToSync=async function(){const e=[];if(d.Settings.argvScanPaths.isNotEmpty()){for(const i of d.Settings.argvScanPaths.values){const r=await(0,v.toUriPath)(i);null!=r?e.push(r):(0,t.logger)().warn("pathsToSync(): Ignoring scanPath element: failed to create URI path",i)}return e}e.push(...(await b()).result),!0===d.Settings.scanAllDrives.value&&e.push(...await w());const i=await(0,n.thenMapOr)((0,a.libraryOriginalsDirPosixFile)(),v.posixFileToUriPath,(()=>(0,t.logger)().throw("libraryOriginalsDir was null",{libraryDir:d.Settings.libraryDir.valueOrDefault,originalsDir:d.Settings.originalsDir.value})));d.Settings.scanLibraryFirst.valueOrDefault&&e.unshift(i),d.Settings.scanLibraryLast.valueOrDefault&&e.push(i);const r=await(0,n.filterAsync)({name:"pathsToSync",arr:e,f:e=>!y.nativePathBlocklist.has(e.nativePath)&&(0,l.isReadableDirectory)(e.nativePath)});return(0,t.logger)().info("pathsToSync",r),r}},98622:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runTimeIsStale=t.SyncCron=void 0;const r=i(1708),s=i(17415),n=i(28874),a=i(41400),o=i(30301),l=i(31586);t.SyncCron=(0,o.lazy)((()=>{const e=n.Settings.syncCronTZ.valueOrDefault??(0,s.toValidIanaZone)(r.env.TZ);return n.Settings.syncCron.cron(null==e?void 0:{timezone:e})})),(0,a.later)((()=>{n.Settings.syncCron.watchLater((()=>t.SyncCron.unset())),n.Settings.syncCronTZ.watchLater((()=>t.SyncCron.unset()))})),t.runTimeIsStale=function(e){return null==e||(0,l.lte)((0,t.SyncCron)().nextRun(new Date(e))?.getTime(),Date.now())}},92244:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncPathsForUI=t.bestStable=t.isStale=t.bestPathToSync=t.stalePathsToSync=t.pathsAndTimesToSync=t.nativePathBlocklist=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(23560),o=i(22277),l=i(87290),u=i(57902),c=i(28874),d=i(40958),h=i(76790),f=i(42659),m=i(75240),p=i(31586),g=i(20958),y=i(49796),v=i(94019),w=i(98622),b=(0,s.lazy)((()=>(0,n.mkLogger)("sync.SyncPaths")));t.nativePathBlocklist=new o.TTLSet(10*f.minuteMs);const S=10*f.minuteMs;async function P(){const e=await(0,v.pathsToSync)(),t=c.Settings.forceSync.valueOrDefault?[]:await y.Progress.times();return b().tap({msg:"pathsAndTimesToSync()",level:u.LogLevels.info,result:e.map((e=>({...e,...t.find((t=>t.uri===e.uri))})))})}function _(e,t){return null==e.lastStartedAt||null==e.lastCompletedAt||(0,p.lte)(e.lastStartedAt,t)||(0,w.runTimeIsStale)(e.lastCompletedAt)}function T(){return g.Operation.getFirstPendingOp({name:g.OperationNames.forceRestartSync})}async function M(e){const t=T(),i=t?.createdAt,s=e.filter((e=>_(e,i)));if((0,d.isEmpty)(s))return(0,a.isSyncService)()&&t?.markCompleted(),b().tap({msg:"bestStable(): No stale paths to sync!",level:"info",result:void 0,meta:{arr:e,forceRestartOp:t}});{const e=(0,r.greatestBy)(s,(e=>e.lastUpdatedAt));if(null!=e&&(0,p.gt)(e.lastUpdatedAt,Date.now()-10*f.minuteMs))return b().tap({msg:"bestStable(): returning most recently updated",level:"info",result:{...e,why:"recently updated"}})}const n=(0,r.leastBy)(s,(e=>[e.lastStartedAt??0,e.lastCompletedAt??0]));return b().tap({msg:"bestStable(): returning least-recently-started or least-recently-completed:",level:"info",result:null==n?void 0:{...n,why:"least recently started or completed"},meta:{stale:s}})}function E(e,t){return null==e.lastStartedAt?"new":null==e.lastCompletedAt?"todo":(0,p.gt)(e.lastUpdatedAt,Date.now()-f.minuteMs)?"syncing":_(e,t)?"stale":"synced"}function k(e){return null==e?void 0:new Date(e).toISOString()}function D(e){if(null==e)return;const t=Date.now()-e;return t<2*f.secondMs?"just now":(0,m.fmtDuration)(t)+" ago"}t.pathsAndTimesToSync=P,t.stalePathsToSync=async function(){const e=await P(),t=T(),i=t?.createdAt,r=e.filter((e=>_(e,i)));return(0,h.sortBy)(r,(e=>[null!=e.lastUpdatedAt&&Date.now()-Se.nativePath)),t=await M(e),i=(0,l.libraryOriginalsDirPosixFile)()?.nativePath,r=T()?.createdAt;return e.map((e=>({path:e.nativePath,library:i===e.nativePath,status:E(e,r),isNext:e.nativePath===t?.nativePath,lastStartedISO:k(e.lastStartedAt),lastStarted:D(e.lastStartedAt),lastCompletedISO:k(e.lastCompletedAt),lastCompleted:D(e.lastCompletedAt)})))}},46832:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.posixFileToUriPath=t.toUriPath=void 0;const r=i(53265),s=i(45200),n=i(22573),a=i(68708),o=i(54993);async function l(e,t){if((0,a.isObject)(e)&&!(0,n.blank)(e.nativePath)&&!(0,n.blank)(e.uri))return e;const i=(0,r.resolve)((0,o.toS)(e)),l=await t??await(0,s.nativePath2uri)(i);return null==l?void 0:{nativePath:i,uri:l.toString()}}t.toUriPath=l,t.posixFileToUriPath=function(e){return l(e.nativePath,e.uriObject_())}},7656:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rebuildTagAssetCounts=t.DirectAssetCountForTagQuery=t.RecursiveAssetCountForTagQuery=t.nonLeafTagIds=void 0;const r=i(50213),s=i(56038),n=i(95704),a=i(38156),o=i(42659),l=i(45599),u=i(41400),c=i(31586),d=i(51926),h=(0,l.defer)((()=>(0,r.mkLogger)("tag.TagAssetCounts")));function f(e){return e.prepare((0,d.compressWhitespace)("SELECT"," t1.id,"," count(t2.id) AS cnt","FROM"," Tag t1"," JOIN Tag t2 ON t1.id = t2.parentId","GROUP BY"," 1","HAVING"," cnt > 0")).pluck().all()}async function m(e,i=[]){const r=e.prepare(t.RecursiveAssetCountForTagQuery).pluck(),o=e.prepare(t.DirectAssetCountForTagQuery).pluck(),l=e.prepare("UPDATE Tag SET assetCount = :assetCount, updatedAt = :updatedAt WHERE id = :tagId"),c=new Set(f(e)),d=new a.PushProgressObserver({op:"Rebuilding tag asset counts"},e.prepare("SELECT count(*) FROM Tag").pluck().get());await(0,n.withIdBatches)({db:e,tableName:"Tag",primaryKeyColumnName:"id",whereClauses:i,async fn(e){for(const t of e){const e=!c.has(t);(0,s.timeSync)("db.rebuildTagAssetCounts("+(e?"leaf":"cte")+")",(()=>{const s=(e?o:r).get({tagId:t});l.run({tagId:t,assetCount:s,updatedAt:Date.now()}),d.incrProgress(),h().debug("_rebuildTagAssetCounts()",{isLeaf:e,whereClauses:i,tagId:t,assetCount:s})})),t%10==0&&(h().throwIfAborted_(),await(0,u.delay)(1))}}}),d.completed()}t.nonLeafTagIds=f,t.RecursiveAssetCountForTagQuery=(0,d.compressWhitespace)("WITH RECURSIVE descendants(id) AS ("," VALUES (:tagId)"," UNION"," SELECT Tag.id"," FROM Tag, descendants"," WHERE Tag.parentId = descendants.id",")","SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," descendants"," JOIN AssetTag ON AssetTag.tagId = descendants.id"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL"),t.DirectAssetCountForTagQuery=(0,d.compressWhitespace)("SELECT"," count(DISTINCT Asset.id) AS assetCount","FROM"," AssetTag"," JOIN Asset ON Asset.id = AssetTag.assetId","WHERE"," AssetTag.tagId = :tagId"," AND Asset.shown = 1"," AND Asset.hidden = 0"," AND Asset.excludedAt IS NULL"," AND Asset.deletedAt IS NULL;"),t.rebuildTagAssetCounts=async function(e,t=o.minuteMs){if(await(0,s.time)("db.rebuildNullTagAssetCounts",(()=>m(e,["assetCount IS NULL"]))),(0,c.gt0)(t)){const i=e.prepare("SELECT min(updatedAt) FROM Tag").pluck().get(),r=Date.now()-i;if(rm(e)))}},69032:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.displayNameForVolsha=t.fixFileRootTag=t.runTagMaintenance=t.forceRunTagMaintenance=t.tagFtsRebuild=void 0;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(1728),c=i(56038),d=i(34102),h=i(49076),f=i(69589),m=i(28874),p=i(42231),g=i(85087),y=i(98770),v=i(59107),w=i(63870),b=i(7014),S=i(22573),P=i(42659),_=i(41400),T=i(75240),M=i(31586),E=i(34666),k=i(51926),D=i(75020),x=i(54017),C=i(48723),A=i(98784),F=i(7656),I=(0,n.lazy)((()=>(0,a.mkLogger)("tag.TagSql")));t.tagFtsRebuild=(0,n.lazy)((()=>(0,c.time)("db.rebuildTagFts",(()=>A.TagFts.rebuild()))),10*P.minuteMs),t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return I().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)};const O=((0,o.isTest)()?5:30)*P.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:O,f:async e=>{const i=(0,f.forceContextOrSetting)(e),r=Date.now(),s=I().addContext(".runTagMaintenance()");s.info("starting",{ctx:i});try{s.info("validating all tags..."),C.Tag.validate_(),s.throwIfAborted_(i?.halt),await L(),i.recountAllTags&&(s.info("rebuilding tag search index..."),await(0,t.tagFtsRebuild)(),s.info("rebuilding tag asset counts..."),await(0,F.rebuildTagAssetCounts)(C.Tag.dbl.db().db,0))}catch(e){I().warn("runTagMaintenance() failed",e)}const n=Date.now()-r,a=(0,M.clamp)(O,15*P.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),I().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const L=(0,y.lazyFsAsync)("updateTagMountpoints",(async()=>{I().info("updating tag mountpoints...");const e=C.Tag.findByPath([D.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(m.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())await N(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}));function R(){t.tagFtsRebuild.unset(),L.unset()}async function N(e){if(null==e||2!==e.depth||!e._path.startsWith(D.TagRoots.fs+p.TagSep))return;const i=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===D.LibraryTagName)return void(1!==e.ordinal&&(i.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),C.Tag.clear()));if((0,f.forceContextOrSetting)().forceSync&&(0,S.notBlank)(e.displayName)&&(0,E.gt)(e.updatedAt,Date.now()-(0,w.volumeMetadataTtlMs)()))return void i.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,T.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const r=await(0,t.displayNameForVolsha)(e.name);(0,S.notBlank)(r)?(e.maybeUpsertDisplayName(r),i.info("updated tag",{id:e.id,path:e.path,displayName:r}),C.Tag.clear()):i.debug("cannot update tag: no current volume.",{id:e.id,path:e.path})}(0,_.later)((()=>{(0,d.ee)().on("clearCache",R),m.Settings.libraryDir.watchLater(R)})),t.fixFileRootTag=N,t.displayNameForVolsha=(0,u.memoizeAsync)((async e=>{const t=(0,a.mkLogger)("displayNameForVolsha("+e+")"),i=await(0,b.volumes)();if(null!=i){const r=i.find((t=>(0,g.volsha)(t.uuid)===e));return t.info("find()",{vol:r}),null!=r?m.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,S.notBlank)(r.label)?r.label.trim():"/"===r.mountpoint?m.Settings.tagDisplayNameFSRoot.valueOrDefault+(m.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+(0,h.hostname)():""):(0,S.notBlankOr)((0,k.stripPrefixSuffix)(r.mountpoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep):x.AssetFile.dbl.pluckFirstf((t=>t.select("mountpoint").whereLike("uri","psfile://"+e+"/%").limit(1)))}}),{name:"tag.displayNameForVolsha",maxSize:64,timeoutMs:(0,w.volumeMetadataTtlMs)()}),(0,_.later)((()=>{v.mountpoints.watch((()=>t.displayNameForVolsha.clear()))}))},5379:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});try{i(93944).install()}catch{}const r=i(69554),s=i(38790),n=i(53978),a=i(43380),o=i(5670),l=i(98392),u=i(31503),c=i(1739);!async function(){await new r.CLI(o.ServiceNames.web).add(l.ExposeArg,u.LogArgs,n.TimingArg,a.WriteSettingsArg,s.ColorArgs).parse(),new c.WebService}()},13808:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AboutRouter=void 0;const s=r(i(7252)),n=i(45255),a=i(81168),o=i(76596),l=i(51773),u=i(81674),c=i(28874),d=i(85087),h=i(7014),f=i(38639),m=i(42659),p=i(75240),g=i(55835),y=i(31586),v=i(20214),w=i(13538),b=i(83104),S=i(12168),P=i(77948),_=i(49796),T=i(92244),M=i(8283);t.AboutRouter=class{router(){return s.default.Router().get("/about",(0,l.wrap)("AboutRouter",this.about.bind(this)))}async about(e,t,i){const r=n.ShortCommandTimeoutMs+m.secondMs,s=await(0,w.thenOrTimeoutAs)({p:(0,P.systemInformation)(),timeoutMs:r,as:[{term:"System information",defn:"Failed to fetch system information: timeout after "+(0,o.fmtMs)(r),defnClass:"fail"}]}),l=await(0,w.thenOrTimeout)((0,v.thenMap)((0,h.volumes)(),(e=>e.map((e=>({ignorable:e.ignorable,mountpoint:e.mountpoint,uuid:e.uuid,volsha:(0,g.map)(e.uuid,d.volsha),size:(0,S.fmtBytes)(e.size,2),free:(0,S.fmtBytes)(e.available,2),full:(0,y.gt0)(c.Settings.minDiskFreeGb.valueOrDefault)&&(0,y.lt)(e.available,c.Settings.minDiskFreeGb.valueOrDefault*S.GB),label:e.label,remote:!0===e.remote?{remote:e.remote,host:e.remoteHost,share:e.remoteShare}:void 0}))).filter((e=>!0!==e.ignorable)))),r);l===b.Timeout&&s.push({term:"volumes() timeout",defn:"Failed to fetch volume metadata: timeout after "+(0,o.fmtMs)(r),defnClass:"fail"});const E=null==_.Progress.db()?void 0:await(0,w.thenOrTimeout)((0,T.syncPathsForUI)(),n.ShortCommandTimeoutMs);E===b.Timeout&&s.push({term:"sync paths timeout",defn:"Failed to fetch sync path metadata: timeout after "+(0,o.fmtMs)(n.ShortCommandTimeoutMs),defnClass:"fail"});const k=await(0,u.b)();return(0,M.render)(e,t,"about",{title:"About PhotoStructure",systemInfo:s,volumes:Array.isArray(l)?l.map((e=>({...e,mountpoint:(0,a.wbrPath)(e.mountpoint)}))):void 0,syncPaths:Array.isArray(E)?E:void 0,subTier:await(0,u.t)(),subTrial:(0,f.isTrue)(k?.l?.trial),subEmail:k?.l?.sub,subExpiresInDuration:(0,g.map)(k?.l?.exp,(e=>(0,p.fmtDuration)(e.getTime()-Date.now(),1))),subExpiresAt:(0,g.map)(k?.l?.exp,m.fmtIsoDate)})}}},76020:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AdminPostRouter=void 0;const s=r(i(7252)),n=i(45608),a=i(34102),o=i(51773),l=i(40749),u=i(62327),c=i(65238),d=i(18454),h=i(2858),f=i(7014),m=i(42659),p=i(41400),g=i(98553),y=i(98401),v=i(14611),w=i(53791),b=i(35758),S=2*m.secondMs;t.AdminPostRouter=class{router(){return s.default.Router().post("/admin/restart",(0,o.wrap)("AdminHealthRouter:restart",this.restart.bind(this))).post("/admin/bounce",(0,o.wrap)("AdminHealthRouter:bounce",this.bounce.bind(this))).post("/admin/refresh/:id",(0,o.wrap)("AdminHealthRouter:refresh",this.refresh.bind(this))).post("/admin/clear-library",(0,o.wrap)("AdminHealthRouter:clear-library",this.clearLibrary.bind(this))).post("/admin/clear-caches",(0,o.wrap)("AdminHealthRouter:clear-caches",this.clearCaches.bind(this))).post("/admin/recheck-tools",(0,o.wrap)("AdminHealthRouter:recheck-tools",this.recheckTools.bind(this))).post("/admin/repair-db",(0,o.wrap)("AdminHealthRouter:repair-db",this.repairDb_.bind(this))).post("/admin/run-maintenance",(0,o.wrap)("AdminHealthRouter:repair-db",this.maintenance_.bind(this))).post("/admin/shutdown",(0,o.wrap)("AdminHealthRouter:shutdown",this.shutdown.bind(this)))}async restart(e,t,i){await(0,v.restartLibrary_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Restarted library...",timeout:S},url:"/splash"})}async refresh(e,t,i){const r=e.params.id,s=d.HealthCheck.findById(r);if(null==s)throw new Error("No health check found with id="+(0,g.stringify)(r));const n=await s.refresh();(0,u.sendRedirectionToast)({response:t,toast:{text:"Health check "+r+": "+n.level,timeout:S},url:"/health"})}async bounce(e,t,i){(0,p.delay)(m.secondMs).then((()=>(0,n.exit)({reason:"/bounce requested by "+e.ip,status:0}))),(0,u.sendRedirectionToast)({response:t,toast:{text:"Restarting webserver...",timeout:15*m.secondMs},url:"/splash"})}async clearLibrary(e,t,i){await(0,h.clearLibraryDirSetting)(),(0,v.restartLibrary_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Prior library was unset. Restarting...",timeout:S},url:"/splash"})}async clearCaches(e,t,i){await(0,f.clearVolumesCache)({deleteFileCache:!0}),await(0,c.clearReaddirCaches)(),(0,a.ee)().emit("clearCache"),"/health"===(0,l.referrer)(e)?(0,u.sendRedirectionToast)({response:t,toast:{text:"Cleared caches.",timeout:S},url:"/health"}):(0,u.sendServerToast)({response:t,toast:{text:"Cleared caches."},reload:!0})}async recheckTools(e,t,i){(0,a.ee)().emit("clearToolCache"),(0,u.sendRedirectionToast)({response:t,toast:{text:"Cleared tool caches.",timeout:S},url:"/health"})}async repairDb_(e,t,i){(0,b.dbModelRepair)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Started library database repair...",timeout:S},url:"/splash"})}async maintenance_(e,t,i){(0,y.cleanup_)(),(0,u.sendRedirectionToast)({response:t,toast:{text:"Started library maintenance jobs...",timeout:S},url:"/"})}async shutdown(e,t,i){(0,p.delay)(S).then((()=>(0,w.shutdown)("requested by "+e.ip))),(0,u.sendServerToast)({response:t,toast:{text:"Shutdown initiated."}})}}},13831:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiAssetRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(97352),o=i(56519),l=i(4867),u=i(76596),c=i(57159),d=i(51773),h=i(62327),f=i(86580),m=i(81674),p=i(72308),g=i(45969),y=i(28874),v=i(40958),w=i(76790),b=i(75761),S=i(38639),P=i(55835),_=i(31586),T=i(68708),M=i(21605),E=i(41942),k=i(75020),D=i(54993),x=i(43487),C=i(37094),A=i(69853),F=i(48723),I=i(94710),O=i(73407),L=(0,n.mkLogger)("web.ApiAssetRouter"),R=["hidden","excludedAt","deletedAt"];t.ApiAssetRouter=class{constructor(e){this.previews=e}wrapApi(e,t){return(i,r,s)=>(0,h.wrapWithToast)({response:r,f:async()=>{const s=(0,_.toGt0)(i.params.assetId);if(null==s)return r.sendStatus(400);const n=await(0,o.thenMapOr)(x.Asset.ops().findById(s,{shown:1}),(e=>t(i,s,e)),(()=>this.onMissingAsset(i,s)));if(L.debug(e,{result:n}),null!=n)return(0,d.jsonOrRedirect)(n,r);throw new c.WrappedError("Asset "+s+" wasn't found",{retriable:!1,doNotSend:!0,fatal:!1})}})}router(){return s.default.Router().get("/api/asset/:assetId/info",this.wrapApi("ApiAssetRouter.assetInfo",this.assetInfo.bind(this))).get("/api/asset/:assetId/streams",this.wrapApi("ApiAssetRouter.assetInfo",this.assetStreams.bind(this))).get("/api/asset/:assetId",this.wrapApi("ApiAssetRouter.asset",this.asset.bind(this))).put("/api/asset/:assetId",this.wrapApi("ApiAssetRouter.save",this.save.bind(this))).put("/api/asset/:assetId/resync",this.wrapApi("ApiAssetRouter.resync",this.resync.bind(this)))}async assetInfo(e,t,i){const r=i.getAssetFiles(),s=i.getShown(),n=(0,P.map)(s,(e=>e.getNativePath())),a=(0,p.isLocalhost)(e.ip)&&!(0,g.isDocker)();if(y.Settings.resyncAssetOnVisit.valueOrDefault&&I.Task.addOne("repairAsset",{assetId:t,forceSync:!1,forceRebuildPreviews:!1}),null==s||null==n)return void L.error("no shown AssetFile found for "+t,{asset:i,shown:s,shownPathP:n});L.debug("assetInfo()",{assetId:t,shown:s,shownPathP:n,ip:e.ip,showOpenFile:a});const l=i.getTags(),c=await(0,o.mapAsync)({name:"api.assetInfo.tags",arr:l,f:e=>e.toApiTag()}),h=await(0,o.mapAsync)({name:"api.assetInfo.files",arr:r,f:e=>e.toApi(this.previews,s.sha)});return(0,w.sortByInPlace)(h,(e=>[!e.shown,!e.exists,e.nativePath])),{assetId:t,capturedAtLocale:s.capturedAtLocale((0,d.requestLang)(e)),...(0,T.pick)(s,"mimetype","focalLength","iso","aperture","shutterSpeed"),durationHMS:(0,P.map)(s.durationMs,u.durationHMS),fps:s.fps,files:h,tags:c,showOpenFile:a}}async onMissingAsset(e,t,i){const r="next"===e.query.from;L.info("onMissingAsset()",{query:(0,T.entries)(e.query),params:(0,T.entries)(e.params),assetId:t});const s=(0,_.toInt)(String(e.query.priorAssetId)),n=(0,P.mapOr)(i,(e=>e.id),(()=>s));if(null==n)return void L.warn("onMissingAsset(): no context asset available");const l=await(0,o.thenMapOr)(i,(e=>e.capturedAtLocal),(()=>x.Asset.dbl.pluckFirstf((e=>e.select("capturedAtLocal").where({id:n})))));let u=x.Asset.shownUnhidden(x.Asset.query().select("id").limit(1).whereNotIn("id",(0,v.compact)([t,s])));u=r?u.andWhere("capturedAtLocal","<",l).orderBy("capturedAtLocal","desc"):u.andWhere("capturedAtLocal",">",l).orderBy("capturedAtLocal","asc");const c=x.Asset.dbl.pluckFirst(u);return L.warn("Asset redirect",{fromAssetId:n,priorAssetId:s,fromTime:l,toAsset:c}),(0,a.mapGt0)(c,(t=>(0,E.mkReplace)((0,b.assetUrl)({assetId:t,params:[e.query,e.params]}),{text:`Asset ${n} is no longer available.`,type:"info"})))}async asset(e,t,i){const r=i.getShown();if(null==r)return L.error("no shown AssetFile found for "+t+", disabling (for now)."),i.upsert({shown:!1}),L.error("Asset un-shown."),I.Task.addOne("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),this.onMissingAsset(e,t,i);i.getBeforeAfterId();const s={...i.partialSimpleAsset(),name:r.basename,width:r.width,height:r.height,rotation:r.rotation??0,capturedAtLocale:r.capturedAtLocale((0,d.requestLang)(e)),aspectRatio:(0,f.aspectRatio)(r),durationHMS:(0,P.map)(r.durationMs,u.durationHMS),downloadable:await r.originalDownloadable({brief:!0}),contextTag:await i.whenApiTag(),beforeAssetId:i.beforeId,afterAssetId:i.afterId};if(r.isVideo){const r=await i.videoSources();return await i.getExistingAssetFiles(),(0,v.isEmpty)(r)?(L.warn("no existing files for "+t+", trying to repair, but redirecting user now."),I.Task.addOne("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}),this.onMissingAsset(e,t,i)):{...s,videoAttrs:i.videoAttrs(),videoSources:r}}return{...s,imgAttrs:await i.fitAttrs(this.previews)}}async assetStreams(e,t,i){const r=(0,_.toInt)((0,D.toS)(e.query.limit),{defaultValue:k.BeforeAfterStreamLimit}),s=i.getStreams(r);return L.tap({msg:"assetStreams",result:{assetId:t,assetStreams:await(0,o.mapAsync)({name:"assetStreams",arr:s,f:e=>e.toApi()})}})}async save(e,t,i){if(await(0,m.l)())return L.warn("save(): disabled"),{showTryPlusToast:!0};const r=i.isActive(),s={hidden:(0,S.toBoolean)(e.body.hidden),excludedAt:(0,P.map)((0,S.toBoolean)(e.body.excluded),(e=>e?Date.now():null)),deletedAt:(0,P.map)((0,S.toBoolean)(e.body.deleted),(e=>e?Date.now():null)),rating:(0,P.map)((0,S.toBoolean)(e.body.liked),(e=>e?y.Settings.likeRating.valueOrDefault:null))};if(!(0,v.isEmpty)((0,T.keys)(s))){L.info("save()",{obj:s,body:e.body}),C.AssetRevision.insert(...(0,T.entries)((0,T.omit)(s,...R)).map((([e,r])=>({assetId:t,field:e,priorValue:i?.[e],newValue:r}))));const n=null===s.deleted?null:null!=s.deleted?-1:s.rating;void 0!==n&&await(0,O.writeAssetTags_)(t,{Rating:n}),i.upsert(s),i.isActive()!==r&&F.Tag.deltaAssetCountAndAncestors(i.tagIds(),i.isActive()?1:-1)}const n=i.partialSimpleAsset(),a=(0,M.normalizeRotation)((0,_.toInt)(e.body.rotation));return null!=a&&0!==a&&(await(0,A.setAssetRotation_)(t,a,this.previews),n.rotation=a),n}async resync(e,t){return x.Asset.dbl.runf((e=>e.where({id:t}).update({version:0}))),await(0,l.thenOrTimeoutError)({p:I.Task.addOne("repairAsset",{assetId:t,forceSync:!0,forceRebuildPreviews:!0}).donePromise(),timeoutMs:y.Settings.taskTimeoutMs.valueOrDefault}),{v:x.Asset.dbl.pluckFirstf((e=>e.where({id:t}).select("updateCount")))}}}},53881:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSearchRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(68178),l=i(28874),u=i(7014),c=i(40958),d=i(22573),h=i(38639),f=i(31586),m=i(12168),p=i(32790),g=i(54993),y=i(43487),v=i(48722),w=i(43786),b=i(7573),S=i(33693),P=i(23523),_=(0,n.mkLogger)("web.ApiSearchRouter");t.ApiSearchRouter=class{router(){return s.default.Router().get("/api/search",(0,a.wrap)("ApiSearchRouter.get",this.get.bind(this)))}async get(e,t){const i=(0,g.toStr)(e.query.q," "),r=p.AssetQueryOrderByColumns.validOrElse((0,g.toStr)(e.query.orderby,","),p.AssetQueryOrderByColumns.capturedAt),s=(0,h.isTrue)(e.query.asc),n={column:r===p.AssetQueryOrderByColumns.capturedAt?"Asset.capturedAtLocal":"Asset.updatedAt",order:s?"asc":"desc"},a=(0,f.toGt0)((0,g.toStr)(e.query.offset));if(_.debug("get()",{q:i,orderBy:n,offset:a}),(0,d.blank)(i))return t.json({});const T=(0,b.normalizeQuery)((0,S.parseQuery_)(i));let M=(0,P.defaultAssetQuery)().select({id:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"}).orderBy([n,"Asset.id"]).limit(512);const E=(0,w.findTerm)(T,(e=>"fs"===e.ns))?await(0,u.mountpointToVolsha)():void 0;null!=a&&(M=M.offset(a));const k=null==a?await async function(e,t,i){const r=await function(e,t){return y.Asset.dbl.pluckFirst((0,P.queryToSql)(e,(0,P.defaultAssetQuery)().countDistinct("Asset.id"),t))}(t,i),{emptyTrashQuery:s,removeAssetsQuery:n}=function(e){const t=1===(0,w.flatTerms)(e).length,i=t&&(0,w.isTrueTerm)((0,w.findTerm)(e,(e=>e.ns===b.AssetTermBoolNs.deleted)));return{emptyTrashQuery:i,removeAssetsQuery:!i&&t&&(0,w.isTrueTerm)((0,w.findTerm)(e,(e=>e.ns===b.AssetTermBoolNs.excluded)))}}(t);if(0===r)return{description:s?"No assets are marked for trash.":n?"No assets are marked for removal.":"No matching assets."};const a="Found "+(0,m.plur)(r,"asset");if(!s&&!n)return{description:a};const u=await function(e,t){return y.Asset.dbl.pluckFirst((0,P.queryToSql)(e,(0,P.defaultAssetQuery)().join("AssetFile","AssetFile.assetId","Asset.id").countDistinct("AssetFile.id"),t))}(t,i),c=a+" ("+(0,m.plur)(u,"file")+")",d={expectedAssetFileCount:String(u)};if(s){const t="Empty trash";return{description:c,buttonText:t,buttonIcon:"trash_forever",promptTitle:t,refreshOnActivation:!0,...l.Settings.enableEmptyTrash.valueOrDefault?{buttonClass:"error",buttonTitle:null,prompt:[`

    Are you sure you want to permanently delete ${(0,m.plur)(u,"file")} comprising ${(0,m.plur)(r,"asset")}?

    `,"","

    To proceed, please enter the number of files that will be deleted:

    "].join("\n"),formAction:(0,o.requestedUri)(e).with({path:"/api/system/empty-trash",query:d}).toString()}:{buttonClass:"disabled",buttonTitle:'This is disabled. See the "enableEmptyTrash" setting.',prompt:null,formAction:null}}}if(n){const t="Remove assets";return{description:c,buttonText:t,buttonIcon:"warning",promptTitle:t,refreshOnActivation:!0,...l.Settings.enableRemoveAssets.valueOrDefault?{buttonClass:"warning",buttonTitle:null,prompt:["

    Are you sure you want to remove "+(0,m.plur)(r,"asset")+" (comprised of "+(0,m.plur)(u,"file")+") from your library?

    ","","

    To proceed, please enter the number of files that will be removed:

    "].join("\n"),formAction:(0,o.requestedUri)(e).with({path:"/api/system/remove-assets",query:d}).toString()}:{buttonClass:"disabled",buttonTitle:'This is disabled. See the "enableRemoveAssets" setting.',prompt:null,formAction:null}}}throw new Error("internal error (mkBanner)")}(e,T,E):void 0;M=(0,P.queryToSql)(T,M,E).distinct();const D=(0,c.compact)(y.Asset.dbl.all(M).map(v.toAssetId)),x={query:{q:i,normalized:(0,w.queryToString)(T,w.NormieQuerySymbols),orderBy:r,asc:s,offset:a??0,nextOffset:D.length<512?void 0:D.length+(a??0)},banner:k,assetIds:D};return _.debug(".get("+(0,w.queryToString)(T)+") result",x),t.json(x)}validatePostRequest(e,t){return _.debug("validatePostRequest",{req_query:e.query,req_body:e.body}),this.validatePost((0,g.toStr)(e.query.expectedAssetFileCount," "),e.body.answer,t)}async validatePost(e,t,i){_.debug("validatePost",{expectedAssetFileCount:e,answer:t});const r=(0,f.toInt)((0,g.toS)(e));if(null==r)return"Canceled: the expected number of files was missing from the request.";const s=(0,f.toInt)(t);if(null==s)return"Canceled: missing user input.";const n=await y.Asset.dbl.pluckFirst(i().join("AssetFile","Asset.id","AssetFile.assetId").countDistinct("AssetFile.id"));return r!==n?`Canceled: the number of files has changed from ${(0,m.fmt)(r)} to ${(0,m.fmt)(n)}. Reload this page and try again.`:s!==r?`Canceled: you entered "${t??""}" and we expected "${r}".`:{assetFileCount:n}}}},21598:function(e,t,i){"use strict";var r,s=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},n=this&&this.__classPrivateFieldSet||function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSplashRouter=void 0;const a=i(18405),o=i(18454),l=i(37805),u=i(42659),c=i(62220),d={loading:"⏳ Loading...",welcome:"👋 Welcome!",ready:"✅ Ready",failed:"⚠️ Something's not right. Gathering details..."};class h extends a.ServerSentEventsRouter{constructor(){super("/sse/splash"),r.set(this,null)}runStateEvent(e=o.HealthCheck.runState()){const t=e===c.RunStates.loading;return t&&this.streams.length>0?n(this,r,s(this,r,"f")??setInterval((()=>{this.writeToStreams(this.runStateEvent())}),u.secondMs),"f"):null!=s(this,r,"f")&&(clearInterval(s(this,r,"f")),n(this,r,null,"f")),this.logger.tap({msg:"runStateEvent()",level:"warn",result:t?{event:"msg",data:o.HealthCheck.loadingMsg()??d[e]}:{event:"settled",data:d[e]},meta:{state:e}})}firstEvents(){return[{event:"version",data:l.version},this.runStateEvent()]}}t.ApiSplashRouter=h,r=new WeakMap},49296:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiSystemRouter=void 0;const s=r(i(7252)),n=i(19851),a=i(50213),o=i(97352),l=i(71567),u=i(51773),c=i(62327),d=i(74128),h=i(28874),f=i(69385),m=i(40958),p=i(38639),g=i(25763),y=i(31586),v=i(12168),w=i(54993),b=i(53791),S=i(43487),P=i(20958),_=i(94710),T=i(22968),M=(0,n.lazy)((()=>(0,a.mkLogger)("web.ApiSystemRouter")));function E(e){return async(t,i,r)=>{const s=(0,w.toStr)(t.query.expectedAssetFileCount," "),n=(0,o.extractInt)(t.body.answer);M().debug("validatePostCounts",{expectedAssetFileCount:s,answer:n});const a=(0,y.toInt)((0,w.toS)(s));if(null==a)return(0,c.sendWarningServerToast)({response:i,toast:{text:"Canceled",details:"The expected number of files was missing from the request"}});const l=(0,y.toInt)(n);if(null==l)return(0,c.sendWarningServerToast)({response:i,toast:{text:"Canceled",details:"User answer was missing"}});const u=await async function(e,t){var i,r;return M().tap({msg:`countAssetFiles(${t})`,result:(i=e.locals)[r="countAssetFiles-"+t]??(i[r]=await S.Asset.dbl.pluckFirst(S.Asset.shownRemovable(t).join("AssetFile","Asset.id","AssetFile.assetId").countDistinct("AssetFile.id")))})}(i,e);return a!==u?(0,c.sendWarningServerToast)({response:i,toast:{text:"Canceled",details:`The number of files has changed from ${(0,v.fmt)(a)} to ${(0,v.fmt)(u)}. Reload this page and try again.`}}):l!==a?(0,c.sendWarningServerToast)({response:i,toast:{text:"Canceled",details:`You entered "${n??""}" and we expected "${a}".`}}):r()}}async function k(e){M().warn("setting "+e+" to unshown...");const t=Date.now(),i={shown:0,updatedAt:t};i[e]=t;const r=S.Asset.dbl.run(S.Asset.shownRemovable(e).update(i)),s=_.Task.addOne(function(e){if("deletedAt"===e)return _.TaskNames.applyDeleted;if("excludedAt"===e)return _.TaskNames.applyExcluded;throw new Error("invalid RemovableColumn "+e)}(e),{createdAt:t});M().warn("updated assets and scheduled task",{result:r,obj:i,task:s})}async function D(e,t){return await k("deletedAt"),(0,c.sendServerToast)({response:t,reload:!0,toast:{text:"Emptied trash",details:"Assets have been removed from your library and files will be deleted in the background.",type:"success"}})}async function x(e,t){return await k("excludedAt"),(0,c.sendServerToast)({response:t,reload:!0,toast:{text:"Assets have been removed from your library.",type:"success"}})}t.ApiSystemRouter=class{constructor(e){this.openFileService=e,this.getState=(e,t)=>{const i={paused:(0,f.isPaused)()};return t.json(i)},this.getHasEmail=(e,t)=>{t.json({hasEmail:(0,g.isEmailMaybe)(h.Settings.email.value)})},this.postSystem=async(e,t)=>{const i=e.body,r=[];M().info("post()",{body:e.body}),(0,p.mapTrue)(i.pause,(()=>{(0,f.pause)(!0),r.push("Sync was paused")})),(0,p.mapTrue)(i.resume,(()=>{(0,f.pause)(!1),r.push("Sync was resumed")})),await(0,p.mapTrue)(i.restartSync,(async()=>{l.StdoutWrite.restartSync(),r.push("Sync restart was requested")})),await(0,p.mapTrue)(i.forceRestartSync,(async()=>{P.Operation.markOpCompleted({name:"forceRestartSync"},{value:"canceled (force-restarted)"}),P.Operation.ensurePendingOp({name:"forceRestartSync"}),l.StdoutWrite.restartSync(),r.push("Sync force-restart was requested")})),await(0,p.mapTrue)(i.rebuildLibrary,(async()=>{(0,T.forceRebuildLibraryLater)(),l.StdoutWrite.restartSync(),r.push("Library rebuild was requested")})),(0,p.mapTrue)(i.showSyncReports,(()=>{this.openFileService((0,d.syncReportReadme)()),r.push("Opened your sync reports directory")})),(0,p.mapTrue)(i.shutdown,(async()=>{const t="requested by "+e.ip;(0,b.shutdown)(t),r.push("Shutdown "+t)})),(0,m.isNotEmpty)(r)?(0,c.sendServerToast)({response:t,toast:{type:"info",text:r.join(". ")}}):(t.status(400),(0,c.sendServerToast)({response:t,toast:{text:"Nothing requested.",type:"warning"}}))}}router(){return s.default.Router().get("/api/system/state",(0,u.wrap)("state",this.getState)).get("/api/system/hasEmail",(0,u.wrap)("hasEmail",this.getHasEmail)).post("/api/system",((e,t)=>(0,c.wrapWithToast)({response:t,f:()=>this.postSystem(e,t)}))).post("/api/system/empty-trash",c.requirePlus,(0,c.requireEnabled)(h.Settings.enableEmptyTrash),E("deletedAt"),D).post("/api/system/remove-assets",c.requirePlus,(0,c.requireEnabled)(h.Settings.enableRemoveAssets),E("excludedAt"),x)}}},19583:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ApiTagRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(97352),o=i(45255),l=i(76596),u=i(51773),c=i(62327),d=i(28874),h=i(34238),f=i(40958),m=i(31586),p=i(41942),g=i(75020),y=i(27776),v=i(54993),w=i(64526),b=i(43487),S=i(48723),P=(0,n.mkLogger)("ApiTagRouter");function _({name:e,f:t}){return(0,u.wrap)(e,(async(i,r)=>{const s=(0,m.toInt)(i.params.tagId),n=(0,u.extractTagPath)(i.path).map(h.percentDecode),a=(0,u.getSeed)(i),o=(0,u.getFit)(i),l=(0,f.mapNotEmptyOr)(n,(e=>S.Tag.findByIdOrPath(s,e)),(()=>S.Tag.root())),d=null==l?void 0:t(i,l,{tagId:l.id,tagPath:l.path,seed:a,fit:o});return P.debug(e,{result:d,tagPath:n,seed:a,url:i.url}),null==l||null==d?(0,c.send404Toast)({text:"Failed to find tag "+s??n.join("/"),response:r}):(0,u.jsonOrRedirect)(d,r)}))}t.ApiTagRouter=class{router(){return s.default.Router().get("/api/tag*",_({name:"ApiTagRouter.tagGallery",f:this.tagGallery.bind(this)})).get((0,g.nextAssetsUrl)(":tagId",{}),_({name:"ApiTagRouter.tagAssets",f:this.tagAssets.bind(this)})).get((0,g.nextChildTagsUrl)(":tagId",{}),_({name:"ApiTagRouter.childTags",f:this.childTags.bind(this)}))}tagGallery(e,t,i){if(P.debug("tagGallery()",{tag:t}),null==i.seed)return P.debug("tagGallery(): no seed, redirecting..."),(0,p.mkReplace)((0,y.mkTagFullPath)(t.path,e.query));if(d.Settings.fastForwardEmptyTags.valueOrDefault){const i=t.firstNonInterstitialTagId();if(i!==t.id){const t=S.Tag.findById(i);if(null!=t)return(0,p.mkReplace)((0,y.mkTagFullPath)(t.path,e.query),{text:"Skipping to first non-empty child tag…",uuid:"redirect-to-tag",onlyShowUuidOnce:!0,type:"info"})}}const r={fullPath:e.originalUrl,fit:i.fit,...t.toApiTag(),...this.childTags(e,t,i),...this.tagAssets(e,t)};return 0===t.id&&0===b.Asset.shownCount()&&((0,l.isRecentMs)(w.Library.instance()?.start,o.ShortCommandTimeoutMs)?r.startingUp=!0:r.emptyLibrary=!0),r}childTags(e,t,i){const r=(0,m.toInt)((0,v.toS)(e.query.offset))??0,s=(0,m.toInt)((0,v.toS)(e.query.limit))??4;P.debug("childTags() got ",{thisOffset:r,limit:s,query:e.query});const n={tagId:t.id,offset:r,limit:s,seed:i.seed};n.limit=(0,a.firstGt0)(n.limit,4);const o=t.getChildrenCount(),l=0===o?[]:t.getPagedChildren(n);P.debug("childTags()",{crit:n,childTagCount:o,children:l});const u=l.length+r,c=u{const t=e.getRelatedAssetIds({seed:i.seed+e.id,limit:g.ThumbsPerSample});return(0,f.isNotEmpty)(t)?{...e.toApiTag(),assetIds:t}:void 0})));return P.tap({msg:"childTags result",result:{tagId:t.id,childTags:d,childTagCount:o,nextChildTags:c},meta:{nextOffset:u}})}tagAssets(e,t){const i={offset:(0,m.toInt)((0,v.toS)(e.query.offset),{defaultValue:0})},r=t.getPagedAssetIds(i),s=r.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetOpenGraph=void 0;const r=i(48884),s=i(48604),n=i(28874),a=i(16170),o=i(31586);t.getAssetOpenGraph=async function(e,t){if(null==(t=(0,o.toGt0)(t))||!(0,o.gt0)(n.Settings.openGraphTargetWidth.valueOrDefault))return;const i=s.Previews.instance()?.ap(t);if(null==i)return;const l=await i.readInfo();if(null==l)return;const u=[];if((0,a.isVideoMimeType)(l.mimetype)){u.push({property:"og:video",content:e.with({path:"/video/"+t}).toString()});const r=await i.mp4().exists()?"video/mp4":l.mimetype;u.push({property:"og:video:type",content:r},{property:"og:video:width",content:l.width.toString()},{property:"og:video:height",content:l.height.toString()})}else{const s=(await i.widths("fit")??[]).map((e=>({width:e,path:"/img/"+t+"/fit/"+e})));"image/jpeg"===l.mimetype&&s.push({width:l.width,path:"/img/"+t+"/actual"});const a=(0,r.leastBy)(s,(e=>Math.abs(e.width-n.Settings.openGraphTargetWidth.valueOrDefault)));if(null!=a){u.push({property:"og:image",content:e.with({path:a.path}).toString()},{property:"og:image:type",content:"image/jpeg"},{property:"og:image:width",content:a.width.toString()});const t=a.width/(l.width/l.height);(0,o.gt0)(t)&&u.push({property:"og:image:height",content:Math.round(t).toString()})}}return u}},18848:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cspHandler=void 0;const s=r(i(2525)),n=i(19851),a=i(50213),o=i(28874),l=i(49586),u=i(40958),c=(0,n.lazy)((()=>(0,a.mkLogger)("web.WebSecurity")));t.cspHandler=function(e,t,i){(e.secure||(0,l.isHttpsRequest)(e.headers))&&null==o.Settings.upgradeInsecureRequests.value&&(c().warn('Secure https request detected: setting "upgradeInsecureRequests" to true.'),o.Settings.upgradeInsecureRequests.tmpValue=!0);const r=(0,u.compactBlanks)(["'self'",o.Settings.cspDirective.valueOrDefault]),n=(0,u.compactBlanks)(["'self'","'strict-dynamic'",`'nonce-${t.locals.cspNonce}'`,o.Settings.cspDirective.valueOrDefault]);s.default.contentSecurityPolicy({directives:{defaultSrc:["'self'"],scriptSrc:n,styleSrc:r,baseUri:r,formAction:["'self'","https://account.photostructure.com"],objectSrc:["'none'"],upgradeInsecureRequests:o.Settings.upgradeInsecureRequests.valueOrDefault?[]:null},reportOnly:o.Settings.cspReportOnly.valueOrDefault})(e,t,i)}},81100:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requestAssetRepair=t.ImgActualRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(62327),l=i(52121),u=i(55835),c=i(31586),d=i(68708),h=i(43487),f=i(54017),m=i(94710),p=(0,n.mkLogger)("web.ImgActualRouter");function g(e){return m.Task.addOne("repairAsset",{assetId:e,forceSync:!0,forceRebuildPreviews:!0})}t.ImgActualRouter=class{constructor(e){this.previews=e}router(){return s.default.Router().get("/img/:assetId/:assetFileId/actual(.*)?",(0,a.wrap)("ImgActualRouter.assetImg",this.assetFileImg.bind(this))).get("/img/:assetId/actual(.*)?",(0,a.wrap)("ImgActualRouter.assetImg",this.assetImg.bind(this))).get("/dl/:assetId/:assetFileId",(0,a.wrap)("ImgActualRouter.assetFileImg",this.assetFileImg.bind(this)))}async assetImg(e,t){const i=(0,c.toInt)(e.params.assetId);if(!(0,c.gt0)(i))return(0,o.sendServerToast)({response:t,toast:{text:"Missing assetId in request",type:"warning"},httpStatusCode:400});const r=f.AssetFile.ops().findOneBy({assetId:i,shown:1});return null==r?(p.info("Unknown assetId",e.originalUrl),this.repairAssetLaterAndSendPreview(i,e,t)):this.sendAssetFile(e,t,r)}async assetFileImg(e,t){const i=(0,c.toInt)(e.params.assetId);if(!(0,c.gt0)(i))return(0,o.send404Toast)({response:t,text:'Request was missing "assetId"',httpStatusCode:400});const r=(0,c.toInt)(e.params.assetFileId);if(!(0,c.gt0)(r))return(0,o.send404Toast)({response:t,text:'Request was missing "assetFileId"',httpStatusCode:400});const s=f.AssetFile.ops().findOneBy({id:r,assetId:i});return null==s?(0,o.send404Toast)({response:t,text:"Bad request: no such asset file "+r}):this.sendAssetFile(e,t,s)}async sendAssetFile(e,t,i){const r=i.assetId,s=await i.posixFile_(),n=e.path.split("/").includes("dl")||(0,a.truthyQuery)(e,"dl");if(null==s||await s.isEmpty())return n?(0,o.send404Toast)({response:t,text:"Asset file "+i.uri+" was missing"}):this.repairAssetLaterAndSendPreview(r,e,t);if(n)return p.info("Sending download",{assetId:r,af:i,nativePath:s.nativePath}),t.download(s.nativePath,s.base);const c=e.headers["user-agent"],h=await(0,l.prepFileForBrowser)({nativePath:s.nativePath,userAgent:c,...(0,d.pick)(i,"width","height","sha","mimetype","rotation","mimetype")});return null==h?(p.warn("cannot send file (null result from prepFileForBrowser)",{assetId:r,af:i}),g(r),(0,o.send404Toast)({response:t,text:`Failed to get browser-friendly preview for Asset ${r}.`,details:"I'll try to fix it."})):(p.info("sendAssetFile(): sending supported file: "+h),t.sendFile(h,(e=>(0,u.map)(e,(e=>p.warn("failed to send file",{error:e,assetId:r,af:i}))))))}async repairAssetLaterAndSendPreview(e,t,i){g(e);const r=await this.previews.ap(e).largestFileForReducer("fit");null!=r?i.sendFile(r.nativePath):(h.Asset.ops().upsertOne({id:e,shown:!1}),(0,o.send404Toast)({response:i,text:`Asset ${e} is missing preview images.`,details:"I'll try to fix it, but it will be hidden for now."}))}},t.requestAssetRepair=g},4950:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ImgRouter=void 0;const s=r(i(7252)),n=i(76760),a=r(i(9288)),o=i(48884),l=i(50213),u=i(45255),c=i(81168),d=i(37628),h=i(51773),f=i(13940),m=i(28874),p=i(16170),g=i(34238),y=i(51140),v=i(11371),w=i(55835),b=i(31586),S=i(54993),P=i(54017),_=(0,l.mkLogger)("web.ImgRouter");t.ImgRouter=class{constructor(e){this.previews=e}router(){const e=(0,h.wrap)("ImgRouter",this.streamImage.bind(this));return s.default.Router().get("/img/:assetId/:reducer/:width",e)}async streamImage(e,t,i){const r=await this.getFileFromRequest(e,t);if(null!=r){if("setHeader"in t&&(0,b.gt)(r.width,500)){const e=P.AssetFile.dbl.pluckFirstf((e=>e.where({assetId:r.assetId,shown:1}).select("uri")))??"/asset-"+r.assetId+"."+r.file.ext,i=(0,w.map)(e,g.uriToBasename);if(_.debug("streamImage(): AssetFile URI",{shownUri:e,basename:i}),null!=i)try{t.setHeader("X-basename",(0,c.ensureSuffixIgnoreCase)(i,"."+r.file.ext))}catch(e){_.warn("streamImage(): setHeader error",{error:e})}else _.warn("streamImage(): failed to extract basename",{result:r})}return t.sendFile(r.file.nativePath)}}async getFileFromRequest(e,t){const i=e.params,r=(0,b.toInt)(i.assetId),s=v.ReducerNames.getCI(i.reducer)??"fit",l=(0,b.toInt)(i.width);if(null==r||null==s&&null==l)return _.warn("getFileFromRequest(): bad request",{assetId:r,reducer:s,width:l}),void t.sendStatus(y.HttpStatus.BadRequest);const h=this.previews.ap(r),g=h.fileForWidth(s,l);if(await g.exists())return{assetId:r,width:l,file:g};if(m.Settings.placeholderThumbs.valueOrDefault){const e=(0,d.stringShaToBuffer)((0,S.toS)(r)).toString("hex").slice(0,6),t=await(0,f.imageCacheDir_)();if(null==t)return;const i=t.join((0,c.splitEvery)(e,3).join(n.sep)+"-8w.png");return await i.applyIfEmpty_({fn_:t=>(0,a.default)({create:{width:8,height:8,channels:3,background:"#"+e}}).png().toFile(t.nativePath),timeoutMs:u.ShortCommandTimeoutMs}),{assetId:r,width:8,file:i}}const w=await h.widths(s)??[],P=await h.readInfo(),T=(0,p.isImageMimeType)(P?.mimetype)&&(0,p.isMimeTypeSupportedByBrowser)(P?.mimetype)?P?.width:void 0,M=(0,o.leastBy)([...w,T],(e=>(0,b.gt0)(e)&&Math.abs(l-e)));return null==M||M===l?(_.warn("Missing file, and no other widths found",{path:g.nativePath,assetId:r,reducer:s,requestedwidth:l,existingWidth:M}),void t.sendStatus(y.HttpStatus.NotFound)):M===T?(_.debug("redirecting to image actual",{assetId:r,reducer:s,width:l,f:g,existingWidth:M}),void t.redirect(["/img",r,"actual"].join("/"))):(_.debug("replacing requested width",{assetId:r,reducer:s,width:l,f:g,existingWidth:M}),void t.redirect(["/img",r,s,M].join("/")))}}},76018:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.siteManifest=t.ManifestRouter=void 0;const s=r(i(7252)),n=i(19851),a=i(50213),o=i(51773),l=i(68178),u=i(70854),c=i(28874),d=(0,n.lazy)((()=>(0,a.mkLogger)("web.ManifestRouter")));async function h({requestUri:e,id:t}){return{id:t??"com.photostructure",name:"PhotoStructure",start_url:e.with({path:c.Settings.defaultHomepagePath.valueOrDefault,query:null,fragment:null}).toString(),display:"fullscreen",icons:[{src:"/192.png",sizes:"192x192",type:"image/png"},{src:"/512.png",sizes:"512x512",type:"image/png"},{src:"/images/logo-gradient.svg",sizes:"any",type:"image/svg+xml"}],theme_color:"#845BAC",background_color:"#845BAC"}}t.ManifestRouter=class{router(){return s.default.Router().get("/site.webmanifest",(0,o.wrap)("SiteManifest",this.siteManifest.bind(this)))}async siteManifest(e,t,i){const r=await((0,u.LibraryUIDStore)()?.readUid_().catch((()=>{}))),s=(0,l.requestedUri)(e,{protocol:"http",host:c.Settings.hostname.value}),n=await h({id:r,requestUri:s});d().debug("siteManifest",n),t.type("application/manifest+json").json(n)}},t.siteManifest=h},16271:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAssetFileRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(72308),l=i(31586),u=i(54017),c=(0,n.mkLogger)("web.OpenAssetFileRouter");t.OpenAssetFileRouter=class{constructor(e){this.openFileService=e}router(){return s.default.Router().get("/api/openAssetFile/:assetFileId",(0,a.wrap)("OpenAssetFileRouter.assetFile",this.assetFile.bind(this)))}async assetFile(e,t){if(c.info("assetFile(): got request",{url:e.originalUrl,ip:e.ip}),!(0,o.isLocalhost)(e.ip))return c.info("Non-localhost request",{url:e.originalUrl,ip:e.ip}),t.sendStatus(400);const i=(0,l.toInt)(e.params.assetFileId);if(!(0,l.gt0)(i))return c.info("Missing assetFileId",e.originalUrl),t.sendStatus(400);const r=u.AssetFile.ops().findOneBy({id:i});if(null==r)return c.info("Invalid assetFileId",e.originalUrl),t.sendStatus(400);const s=await r.posixFile_();return null==s||await s.clear().notExists()?(c.info("File not found",{url:e.originalUrl,af:r,file:s}),t.sendStatus(400)):(c.info("Requesting openFileService("+s.nativePath+")...",{url:e.originalUrl,ip:e.ip}),this.openFileService(s.nativePath),t.sendStatus(204))}}},24255:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PingRouter=void 0;const s=r(i(7252)),n=i(99331),a=i(51140);t.PingRouter=class{router(){return s.default.Router().get("/ping",((e,t)=>t.sendStatus((0,n.ending)()?a.HttpStatus.ServiceUnavailable:a.HttpStatus.OK)))}}},39761:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getPlansLicense=t.getPlansBilling=t.getPlansActivate=t.getPlansPick=t.PlansRouter=void 0;const s=r(i(7252)),n=i(19851),a=i(50213),o=i(88158),l=i(37805),u=i(51773),c=i(68178),d=i(33603),h=i(70114),f=i(28874),m=i(22573),p=i(42659),g=i(59455),y=(0,n.lazy)((()=>(0,a.mkLogger)("web.PlansRouter")));async function v(e,t){return await S({req:e,res:t,remotePath:"/plans/pick"})}async function w(e,t){return await S({req:e,res:t,remotePath:"/",params:{skipIndex:!0}})}async function b(e,t){return await S({req:e,res:t,remotePath:"/"})}async function S({req:e,res:t,remotePath:i,params:r={}}){const s=(0,c.requestedUri)(e).with({path:"/plans/license"}),n=await(0,d.sids)({timeoutMs:4*p.secondMs}),a=new URL("https://account.photostructure.com"+i);return a.searchParams.append("version",l.version),a.searchParams.append("uids",n.join(",")),(0,m.mapNotBlank)(f.Settings.coupon.value,(e=>a.searchParams.append("coupon",e))),a.searchParams.append("redirectToLibraryUrl",s.toString()),(0,o.mapEntries)(r,((e,t)=>a.searchParams.append(e,t))),y().info("GET /plans/pick",{redirectToLibraryUrl:s.toString()}),t.redirect(a.toString())}async function P(e,t){try{(0,m.mapNotBlankOr)(e.query.license,(async e=>{await(0,h.writeLicense)(e,3*p.secondMs),y().info("getPlansLicense(): Saved new license",e)}),(()=>{y().info("getPlansLicense(): no license in request",e.originalUrl)}))}catch(t){y().error("getPlansLicense(): Failed to save license",{err:t,url:e.originalUrl})}const i=(0,m.notBlankOr)((0,g.toA)(e.query.then)[0],"/settings");y().info("getPlansLicense(): redirecting to "+i),t.redirect(i)}t.PlansRouter=class{router(){return s.default.Router().get("/plans/pick",(0,u.wrap)("GET /plans/pick",v)).get("/plans/activate",(0,u.wrap)("GET /plans/activate",w)).get("/plans/billing",(0,u.wrap)("GET /plans/billing",b)).get("/plans/license",(0,u.wrap)("GET /plans/license",P))}},t.getPlansPick=v,t.getPlansActivate=w,t.getPlansBilling=b,t.getPlansLicense=P},37380:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressProvider=void 0;const r=i(58587),s=i(1708),n=i(89788),a=i(54557),o=i(19851),l=i(50213),u=i(56519),c=i(18454),d=i(43334),h=i(69385),f=i(40958),m=i(38639),p=i(42659),g=i(96249),y=i(49769),v=i(12236),w=i(54993),b=i(43487),S=i(54017),P=i(49796),_=(0,o.lazy)((()=>(0,l.mkLogger)("web.ProgressWithAssets")));t.ProgressProvider=class{constructor(e=10){this.maxLen=e,this.priorRecentAssets=new a.FifoCache(15,15*p.secondMs),this.testProgressStatesByVolume=new Map}async updates(){return(0,u.thenMap)(this.states(),(e=>({states:e})))}async states(){if((0,h.isPaused)())return[{volume:"⏸",state:"paused",hed:"Paused",dek:["Processing is paused. Resume via the navigation menu"+(d.isElectron?" or the system tray menu":"")+"."],recentAssetIds:[]}];const e=await c.HealthCheck.errorResults();if((0,f.isNotEmpty)(e))return _().warn("health check is failing",{errors:e}),[{volume:"⚠️",state:"paused",hed:"Health checks failed. Click for details.",dek:(0,f.uniq)((0,g.flatten)(e.map((e=>e.msg)))),recentAssetIds:[]}];const t=this.recentProgress();return _().debug("recentProgressWithAssets()",t),(0,f.isEmpty)(t)&&(0,m.isTrue)(s.env.TEST_PROGRESS)?this.testProgress():t}recentProgress(){const e=P.Progress.ops().allf((e=>e.where("updatedAt",">",Date.now()-p.minuteMs).whereNotNull("state").orderBy("volume")));(0,f.filterInPlace)(e,(e=>!(!(0,r.pidExists)(e.pid)&&"done"!==e.state&&(_().warn("Incomplete progress is from a dead process",{progress:e}),e.upsert({state:null}),1))));const t=[],i=new Set;for(const r of e){const e="done"===r.state,s=r.toSyncState(),n=this.priorRecentAssets.get((0,w.toS)(r.id))??[];if(!e){const e=((0,v.noRecentAssetIdsProgress)(s)?[]:S.AssetFile.recentAssetIdsByUriRoot((0,v.isRebuildProgress)(s)?void 0:s.uri,p.minuteMs,this.maxLen+i.size)).filter((e=>!i.has(e)&&!n.includes(e)));(0,f.isNotEmpty)(n)&&e.length>=this.maxLen&&e.splice(0,this.maxLen-1),n.unshift(...e),n.length=this.maxLen,this.priorRecentAssets.set((0,w.toS)(r.id),n);for(const e of n)i.add(e)}t.push({...s,recentAssetIds:n})}return t}async testAssetIds(e){const t=(0,y.getOrSet)(this.testProgressStatesByVolume,e,(()=>new n.BoundedList(this.maxLen))),i=b.Asset.dbl.pluckFirstf((e=>b.Asset.shownUnhidden(e).select("id").orderByRaw("random()").first()));return null!=i&&t.push(i),t.toA()}async testProgress(){const e=Math.round(Date.now()/(30*p.secondMs))%3,t=(d.isWin?["C:","D:","E:"]:["/","/home/bob/pictures","/mnt/nas"])[e];return[{volume:t,state:"processing",hed:"Processing, about 32 minutes remaining",dek:["Processing C:\\Users\\mrm\\Pictures\\20161214-pixel\\DCIM\\Camera\\IMG_20160903_090736.jpg","Processed 445 images and videos. 1,386 remain to be processed."],completePct:40,incompletePct:25,scanningPct:35,recentAssetIds:await this.testAssetIds(t)}]}}},8283:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.render=void 0;const r=i(72993),s=i(19851),n=i(50213),a=i(7282),o=i(81674),l=i(72308),u=i(45969),c=i(43334),d=i(28874),h=i(69385),f=i(38639),m=i(13538),p=i(2322),g=i(48723),y=(0,s.lazy)((()=>(0,n.mkLogger)("web.PugHelpers")));t.render=async function(e,t,i,s={}){const n=e.headers["user-agent"];t.setHeader("Feature-Policy","autoplay 'self'");const v=[],w=!0===n?.toLowerCase().includes("electron")&&(0,l.isLocalhost)(e.ip)||(0,f.isTrue)(e.query.electron);w&&(v.push("electron"),c.isMac?v.push("mac"):c.isWin?v.push("win"):c.isLinux&&v.push("linux")),(0,a.isDev)()&&v.push("is-dev"),(0,p.isChrome)(n)?v.push("chrome"):(0,p.isSafari)(n)?v.push("safari"):(0,p.isFirefox)(n)&&v.push("firefox"),(0,p.isIphone)(n)?v.push("iphone"):(0,p.isIpad)(n)&&v.push("ipad"),(0,h.isPaused)()&&v.push("is-paused"),(0,l.isLocalhost)(e.ip)&&!(0,u.isDocker)()&&v.push("is-localhost");try{!0===await(0,m.thenOrTimeout)((0,o.p)(),250)&&v.push("is-plus")}catch{}d.Settings.enableArchive.valueOrDefault&&v.push("enable-archive"),d.Settings.enableDelete.valueOrDefault&&v.push("enable-delete"),d.Settings.enableRemove.valueOrDefault&&v.push("enable-remove");const b={bodyClass:v.join(" "),isDocker:(0,u.isDocker)(),isElectron:w,isDev:a.isDev,nonce:t.locals.cspNonce,hasEmail:d.Settings.email.hasValue(),...s};y().debug("render()",{ua:n,template:i,options:b,headers:e.headers}),t.render(i,{rootTags:null==g.Tag.db()?void 0:g.Tag.roots(),title:(0,r.AppName)(),...b})}},8446:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SSEHealthRouter=void 0;const r=i(22911),s=i(18405),n=i(18454),a=i(72901),o={event:"done",data:{done:!0}};function l(e){return null==e?void 0:{event:"result",data:e}}class u extends s.ServerSentEventsRouter{constructor(){super("/sse/health")}firstEvents(e,t){return this.sendResults(t),[]}async sendResults(e){const t=[],i=[];i.push(n.HealthCheck.summary());for(const e of n.HealthCheck.all()){const r=e.toResultSync();i.push(r),("pending"===r.level||e.isStale())&&t.push(e)}e.write((0,a.mkEventStream)(...i.map(l))),this.logger.debug("sendResults (sync)",{pending:t.map((e=>e.id)),resolved:i.map((e=>e.id))});for await(const i of r.Deferred.toAsyncIterable(t.map((e=>e.result())))){const t=(0,a.mkEventStream)(l(i),l(n.HealthCheck.summary()));this.logger.debug("sendResults (async)",{result:i,chunk:t}),e.write(t)}e.write((0,a.mkEventStream)(l(n.HealthCheck.summary()),o),(()=>this.endStream(e)))}}t.SSEHealthRouter=u},44143:function(e,t,i){"use strict";var r,s,n=this&&this.__classPrivateFieldGet||function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SSEProgressRouter=void 0;const a=i(18405),o=i(72901),l=i(51140),u=i(40958),c=i(94383),d=i(76386);class h extends a.ServerSentEventsRouter{constructor(e){super(c.ApiProgressPath),r.add(this),this.updatesProvider=e}firstEvents(){return setTimeout((()=>n(this,r,"m",s).call(this)),250),[]}router(){return super.router().patch(d.ApiProgressPatchPath,this.onSendUpdates.bind(this))}async onSendUpdates(e,t){try{return this.logger.debug("Received PATCH, sending updates.",{remotePort:e.socket?.remotePort}),await n(this,r,"m",s).call(this),t.sendStatus(l.HttpStatus.OK)}catch(e){return this.logger.warn("onSendUpdates(): Failed to send updates",{error:e}),t.sendStatus(l.HttpStatus.InternalServerError)}}}t.SSEProgressRouter=h,r=new WeakSet,s=async function(){if(!this.ended&&!(0,u.isEmpty)(this.streams))try{const e=await this.updatesProvider.updates();if(null==e)return void this.logger.warn("Failed to fetch updates");if(this.ended)return;const t=(0,o.mkEventStream)({data:e});(0,u.filterInPlace)(this.streams,(e=>!e.destroyed));for(const e of this.streams)try{e.write(t)}catch{}}catch(e){this.logger.warn("Failed to send updates",e)}}},59898:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsRouter=void 0;const s=r(i(7252)),n=i(51168),a=i(76760),o=i(50213),l=i(7282),u=i(45255),c=i(71567),d=i(87290),h=i(55939),f=i(34102),m=i(51773),p=i(83278),g=i(66106),y=i(81674),v=i(43205),w=i(45969),b=i(43334),S=i(4936),P=i(28874),_=i(2858),T=i(40958),M=i(22573),E=i(38639),k=i(42659),D=i(75240),x=i(98553),C=i(55835),A=i(68708),F=i(13538),I=i(12168),O=i(59455),L=i(54993),R=i(78339),N=i(57064),B=i(8283),j=(0,o.mkLogger)("web.SettingsRouter");t.SettingsRouter=class{constructor(e=d.libraryDirPosixFile,t=R.librarySettings,i=N.suggestedLibraryDirs){this.libraryDir=e,this.settings=t,this.libraryDirSuggester=i}router(){return s.default.Router().get("/setting",((e,t)=>t.redirect("/settings"))).get("/settings",(0,m.wrap)("GET /settings",this.get.bind(this))).post("/settings",(0,m.wrap)("POST /settings",this.post.bind(this)))}async get(e,t){const{err:i,libraryDir:r}=e.body;let s;try{await(0,_.readSettings)(),s=await(0,F.thenOrTimeoutError)(this.requestSettings(e),P.Settings.statTimeoutMs.valueOrDefault)}catch(e){return j.warn("readSettings() took too long. Redirecting to the health check page.",e),t.redirect("/health")}try{return await(0,F.thenOrTimeoutError)(this.renderSettings(e,t,s,r,i),P.Settings.statTimeoutMs.valueOrDefault)}catch(e){return j.warn("requestSettings() took too long. Redirecting to the health check page.",e),t.redirect("/health")}}async renderSettings(e,t,i,r,s){(0,f.ee)().emit("clearCache");let o=await(0,F.thenOrTimeoutMaybe)(this.libraryDirSuggester(),u.ShortCommandTimeoutMs)??[];if(!/choose a different directory/i.test((0,L.toS)(s))){const e=await N.SuggestedLibraryDir.for(r);null!=e&&o.unshift(e)}(0,T.isEmpty)(o)&&(o=void 0);const c=this.libraryDir();(0,M.blank)(s)&&(0,w.isDocker)()&&(null==c||await c.isNotDirectory())&&(s=`PS_LIBRARY_DIR, ${c?.nativePath??"/ps/library"}, doesn't exist: please add it as a bind mount.`);const d=await(0,F.thenOrTimeoutMaybe)((0,g.getVideoToolDetails_)((0,l.isProd)()?void 0:e.query),u.ShortCommandTimeoutMs),A=await(0,h.picturesDir)(),O=await(0,y.b)(),R={err:s,...i,autoUpdateCheck:i.autoUpdateCheck??!0,allowUserAgent:i.allowUserAgent??!0,reportErrors:i.reportErrors??!0,welcome:(0,C.mapOr)((0,l.isProd)()?void 0:e.query.welcome,E.isTrue,(()=>!(0,_.libraryHasSettings)())),title:null==c?"Welcome!":"Settings",videoToolDetails:d,picturesPath:A,jsonScanPaths:(0,C.map)(P.Settings.scanPaths.value,x.stringify),delimiter:a.delimiter,exampleScanPath:[A,b.isWin?"D:\\PHOTOS":b.isMac?"/Volumes/External HD/Pictures":"/mnt/nas/homes/photos"].join(a.delimiter),currentLibraryDir:(0,C.map)(c,(e=>e.nativePath)),minFreeAvailable:(0,I.fmtBytes)(P.Settings.minDiskFreeGb.valueOrDefault*I.GB),suggestedLibraryDirs:o,samplePath:(0,S.pathToLibraryAsset)(n.DateTime.now(),p.BaseFile.for("photo.jpg")).join(a.sep),subTier:await(0,y.t)(),subTrial:(0,E.isTrue)(O?.l?.trial),subEmail:O?.l?.sub,subExpiresInDuration:(0,C.map)(O?.l?.exp,(e=>(0,D.fmtDuration)(e.getTime()-Date.now(),1))),subExpiresAt:(0,C.map)(O?.l?.exp,k.fmtIsoDate),userAgent:await(0,v.systemUserAgent)()};j.info("rendering settings",R),(0,m.disableCache)(t),await(0,B.render)(e,t,"settings",R)}async post(e,t){const i=e.body,r=(0,M.toNotBlank)("libraryDirCustom"===i.libraryDirRadio?i.libraryDir:i.libraryDirRadio),s=i=>this.renderSettings(e,t,u,r,i),n=r??P.Settings.libraryDir.valueOrDefault;if((0,M.blank)(n))return s("Please choose a directory for your library.");const o=(0,a.resolve)(n),u=this.requestSettings(e);j.info("POST",{libraryDir:o,settings:u,body:i}),(0,l.isTest)()&&(0,c.stdoutWrite)({post:i,settings:u,method:e.method,libraryDir:o});try{const e=await(0,R.saveLibrarySettings)(o,u);if("error"in e)return j.info("error saving library settings",{result:e}),s(e.error);j.info("saved library settings. Waiting for bookkeeping to finish...",e),await e.ready,j.info("ready. Redirecting to /splash...",e)}catch(e){return s(e)}return t.redirect("/splash")}requestSettings(e){const{scan:t,scanPath:i,copyAssets:r,autoUpdateCheck:s,allowUserAgent:n,reportErrors:a}=e.body,o={...this.settings()};return(0,M.notBlank)(t)&&(o.scanAllDrives="scanAllDrives"===t,o.scanPath=(0,T.compactBlanks)((0,O.toA)(i))),(0,M.notBlank)(r)&&(o.copyAssets="copyEnabled"===r),o.allowUserAgent=(0,E.toBoolean)(n),o.autoUpdateCheck=(0,E.toBoolean)(s),o.reportErrors=(0,E.toBoolean)(a),j.tap({msg:"requestSettings()",level:"info",result:o,meta:{req_body:(0,A.pick)(e.body,"scan","scanPath","copyAssets","autoUpdateCheck","allowUserAgent","reportErrors")}})}}},77203:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SpaRouter=void 0;const s=r(i(7252)),n=i(51773),a=i(68178),o=i(75710),l=i(8283);t.SpaRouter=class{router(){const e=(0,n.wrap)("SpaRouter",this.get.bind(this));return s.default.Router().get("/tag*",e).get("/asset/:assetId",(0,n.wrap)("SpaRouter.Asset",this.getAsset.bind(this))).get("/search",e)}async getAsset(e,t,i){const r=await(0,o.getAssetOpenGraph)((0,a.requestedUri)(e),e.params.assetId);return(0,l.render)(e,t,"app",null==r?{}:{meta:r})}get(e,t,i){if(!e.path?.startsWith("/tag")||null!=(0,n.getSeedOrRedirect)(e,t))return(0,l.render)(e,t,"app",{})}}},2314:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.VideoRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(40958),l=i(55835),u=i(31586),c=i(54017),d=(0,n.mkLogger)("web.VideoRouter");t.VideoRouter=class{constructor(e){this.previews=e}router(){return s.default.Router().get("/video/:assetId",(0,a.wrap)("VideoRouter",this.videoImage.bind(this)))}async videoImage(e,t,i){const r=e.params,s=(0,u.toInt)(r.assetId);if(!(0,u.gt0)(s))return d.warn("Malformed request (missing assetId)",{params:e.params}),t.sendStatus(400);const n=this.previews.ap(s).mp4();if(await n.exists())return d.info("streaming transcoded video",n),t.sendFile(n.nativePath);const a=c.AssetFile.ops().findBy({assetId:s,shown:1});if((0,o.isEmpty)(a))return d.warn("Malformed request (bad assetId)",{params:e.params}),t.sendStatus(400);const h=a[0],f=await(0,l.map)(h,(e=>e.posixFile_()));return null!=f&&h.isVideo&&await f.exists()?t.sendFile(f.nativePath):(d.warn("Shown assetFile isn't a video",h),t.sendStatus(400))}}},1739:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebService=void 0;const s=r(i(7252)),n=r(i(2525)),a=r(i(77598)),o=r(i(1708)),l=i(19851),u=i(50213),c=i(97352),d=i(71567),h=i(99331),f=i(45608),m=i(56519),p=i(38835),g=i(57159),y=i(41293),v=i(27821),w=i(78147),b=i(68178),S=i(43394),P=i(62327),_=i(30576),T=i(95696),M=i(43899),E=i(8797),k=i(63664),D=i(18454),x=i(21525),C=i(45657),A=i(33603),F=i(39471),I=i(29325),O=i(28874),L=i(2858),R=i(63870),N=i(7014),B=i(55111),j=i(51140),z=i(93493),V=i(41400),W=i(55835),U=i(62220),q=i(13538),H=i(459),G=i(27776),$=i(64526),J=i(18449),K=i(95629),Y=i(37158),X=i(8400),Z=i(13808),Q=i(76020),ee=i(13831),te=i(53881),ie=i(21598),re=i(49296),se=i(19583),ne=i(18848),ae=i(81100),oe=i(4950),le=i(76018),ue=i(16271),ce=i(24255),de=i(39761),he=i(37380),fe=i(8446),me=i(44143),pe=i(59898),ge=i(77203),ye=i(2314),ve=i(98949),we=i(43268);function be(e,t){t.endsWith(".js")&&e.setHeader("Content-Type","application/javascript")}const Se=(0,u.mkLogger)("web.WebService"),Pe=e=>(0,E.showFileInFolder)(T.PosixFile.for(e));t.WebService=class{constructor(){this.setup=(0,l.lazy)((async()=>{if(Se.debug("setup(): started"),o.default.on("SIGPIPE",(()=>{})),O.Settings.libraryDir.watchLater((()=>ke.unset())),await(0,m.rejected)(this.service.ready))return void Se.error("setup(): failed, service.ready was rejected");await(0,z.setupShimDelegates)();const e=this.app;if(e.use((new w.RequestLogger).router),e.use(((e,t,i)=>{t.locals.cspNonce=a.default.randomBytes(16).toString("hex"),i()})),O.Settings.trustProxy.hasValue()){const t=O.Settings.trustProxy.value,i="true"===t||"false"!==t&&(0,c.mapGte0Or)(t,(e=>e),t);e.set("trust proxy",i),Se.info("trust proxy set",{value:i})}if(e.use(P.expressErrorHandlerWithToast),(0,J.sentryEnabled)())try{e.use(i(16436).Handlers.requestHandler())}catch(e){Se.warn("Failed to initialize Sentry requestHandler",{error:e})}if(O.Settings.disabledHelmetMiddleware.valueOrDefault.includes(B.HelmetPlugins.all))Se.warn("DANGER: disabledHelmetMiddleware includes 'all': not enabling any Helmet middleware.");else{O.Settings.disabledHelmetMiddleware.valueOrDefault.includes(B.HelmetPlugins.contentSecurityPolicy)||e.use(ne.cspHandler);const t={contentSecurityPolicy:!1};for(const e of O.Settings.disabledHelmetMiddleware.valueOrDefault.filter((e=>e!==B.HelmetPlugins.all)))t[e]=!1;e.use((0,n.default)(t))}e.use(b.addXSettingsHandler),e.use(we.json()),e.use(we.urlencoded({extended:!1}));const t=M.ProjectPath.Public(),r=M.ProjectPath.Views();if(Se.info("setup()",{libraryDir:O.Settings.libraryDir.valueOrDefault,publicRoot:t,viewsRoot:r}),L.libraryHasSettings.watch((()=>e.set("etag",(0,L.libraryHasSettings)()))),e.set("views",r),e.set("view engine","pug"),e.use((new ce.PingRouter).router()),e.use((new y.ApiHealthRouter).router()),e.use((0,_.viewRouter)({path:"/splash",view:"splash"})),e.use((new ie.ApiSplashRouter).router()),e.use((0,_.viewRouter)({path:"/health",view:"health"})),e.use((new fe.SSEHealthRouter).router()),e.use((new Q.AdminPostRouter).router()),e.get("/status",((e,t)=>t.redirect("/health"))),e.use(await(0,S.serveStaticGz)(t)),e.use(s.default.static(t,{setHeaders:be})),e.use((new Z.AboutRouter).router()),e.use((new ve.WelcomeRouter).router()),e.use((new de.PlansRouter).router()),e.use(Ee()),(0,I.isPacked)()||(e.use("/die",((e,t)=>{Se.info("/die was requested",{url:e.originalUrl}),t.sendStatus(j.HttpStatus.Accepted),(0,f.exit)({reason:"/die",status:1})})),e.use("/test-sentry",((e,t)=>{(0,K.sendToSentry)(new g.WrappedError("test message sent to sentry at "+new Date)),t.sendStatus(j.HttpStatus.Accepted)}))),e.use(((e,t,i)=>(0,h.ending)()?(Se.info("ending(): returning 500",{requestUri:(0,b.requestedUri)(e)}),t.sendStatus(500)):function(){const e=D.HealthCheck.runState();switch(e){case U.RunStates.loading:return _e();case U.RunStates.welcome:return Me();case U.RunStates.ready:return ke()??ke.refresh()??Te();case U.RunStates.failed:return Te();default:throw new H.UnreachableCaseError(e)}}()(e,t,i))),(0,J.sentryEnabled)())try{e.use(i(16436).Handlers.errorHandler())}catch(e){Se.warn("Failed to initialize Sentry error handling",{error:e})}const l=O.Settings.httpPort.valueOrDefault,u=O.Settings.exposeNetworkWithoutAuth.valueOrDefault,v=$.Library.instance();null!=v?D.HealthCheck.addLoadingMsg("Loading library..."):D.HealthCheck.addLoadingMsg("Starting...");const T=async()=>{Se.info("setup(): http server callback",{httpPort:l,expose:u});const e=[O.Settings.httpPort];null!=v&&e.push(O.Settings.libraryDir),(0,d.stdoutWriteSettings)(...e),null==v?((0,A.sids)((0,R.commandTimeoutMs)()).catch((e=>Se.warn("failed to prefetch sids",e))),(0,N.volumes)().catch((e=>Se.warn("failed to prefetch volumes",e)))):(await(0,L.maybeUpgradeSystemSettings)(),await(0,L.maybeUpgradeLibrarySettings)(),await v.ready,ke.unset()),await(0,X.libraryHealthCheckSetup)(),await D.HealthCheck.awaitSettled(),await(0,q.thenOrTimeout)((0,C.r)(),(0,R.commandTimeoutMs)()),null!=v&&((0,x.isHealthCheckLevelFatal)((await(0,k.getLocalHealthSummary)()).level,"sync")?Se.warn("setup(): health check failed, so we're not starting sync."):d.StdoutWrite.restartSync())},E=u?e.listen(l,T):e.listen(l,O.Settings.localhost.valueOrDefault,T);return E.on("error",(e=>{Se.warn("http.server.onError()",e),"EADDRINUSE"===e.code&&(0,f.exit)({reason:"Port "+l+" is already in use: is PhotoStructure already running?"+p.FatalErrorFlag+p.DoNotSendErrorFlag+p.WebFatalErrorFlag,error:e,status:3})})),new F.EndableServer("http.WebService",E)})),this.app=(0,s.default)(),this.service=new Y.Service("web"),this.setup()}};const _e=(0,l.lazy)((()=>(0,v.redirectRouter)("/splash"))),Te=(0,l.lazy)((()=>(0,v.redirectRouter)("/health"))),Me=(0,l.lazy)((()=>(0,v.redirectRouter)("/welcome"))),Ee=(0,l.lazy)((()=>(new pe.SettingsRouter).router())),ke=(0,l.lazy)((()=>{const e=$.Library.instance();if(null==e)return Se.warn("libraryRouter invoked before library is set up."),void setImmediate((()=>ke.unset()));Se.info("Setting up library router for "+(0,W.map)(e,(e=>e.rootDir)));const t=e.previews(),i=new he.ProgressProvider,r=s.default.Router();return r.use((new le.ManifestRouter).router()),r.use(new re.ApiSystemRouter(Pe).router()),r.use((new se.ApiTagRouter).router()),r.use(new ee.ApiAssetRouter(t).router()),r.use((new te.ApiSearchRouter).router()),r.use((new ge.SpaRouter).router()),r.use(new ue.OpenAssetFileRouter(Pe).router()),r.use(new ae.ImgActualRouter(t).router()),r.use(new oe.ImgRouter(t).router()),r.use(new ye.VideoRouter(t).router()),r.use(new me.SSEProgressRouter(i).router()),r.use("/",((e,t)=>{Se.debug("in root route",{res_headersSent:t.headersSent,res_headers:t.getHeaders()}),t.redirect(302,(0,G.mkHomeFullPath)(e.query))})),r}));(0,V.later)((()=>{O.Settings.libraryDir.watchLater((()=>ke.unset()))}))},98949:function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WelcomeRouter=void 0;const s=r(i(7252)),n=i(50213),a=i(51773),o=i(18454),l=i(81674),u=i(28874),c=i(51140),d=i(57064),h=i(39761),f=i(8283);t.WelcomeRouter=class{constructor(){this.logger=(0,n.mkLogger)("WelcomeRouter")}router(){return s.default.Router().get("/welcome",(0,a.wrap)("GET /welcome",this.get.bind(this))).post("/welcome",(0,a.wrap)("POST /welcome",this.post.bind(this)))}async get(e,t){return"welcome"!==o.HealthCheck.runState()?t.redirect(c.HttpStatus.Found,"/"):((0,d.suggestedLibraryDirs)(),(0,f.render)(e,t,"welcome",{}))}async post(e,t){return!u.Settings.pickPlanOnWelcome.valueOrDefault||await(0,l.p)()?t.redirect("/settings"):(0,h.getPlansPick)(e,t)}}},90858:e=>{"use strict";e.exports=require("@iarna/toml")},53705:e=>{"use strict";e.exports=require("@photostructure/tz-lookup")},16436:e=>{"use strict";e.exports=require("@sentry/node")},64770:e=>{"use strict";e.exports=require("assert")},58587:e=>{"use strict";e.exports=require("batch-cluster")},87550:e=>{"use strict";e.exports=require("better-sqlite3")},43268:e=>{"use strict";e.exports=require("body-parser")},6858:e=>{"use strict";e.exports=require("commander")},36507:e=>{"use strict";e.exports=require("croner")},66261:e=>{"use strict";e.exports=require("events")},77988:e=>{"use strict";e.exports=require("exiftool-vendored")},7252:e=>{"use strict";e.exports=require("express")},66150:e=>{"use strict";e.exports=require("fast-xml-parser")},68817:e=>{"use strict";e.exports=require("file-type")},44652:e=>{"use strict";e.exports=require("fs-extra")},28787:e=>{"use strict";e.exports=require("he")},2525:e=>{"use strict";e.exports=require("helmet")},31832:e=>{"use strict";e.exports=require("knex")},51168:e=>{"use strict";e.exports=require("luxon")},93973:e=>{"use strict";e.exports=require("ml-kmeans")},80265:e=>{"use strict";e.exports=require("moo")},31704:e=>{"use strict";e.exports=require("nearley")},4927:e=>{"use strict";e.exports=require("papaparse")},83058:e=>{"use strict";e.exports=require("picomatch")},22915:e=>{"use strict";e.exports=require("platform-folders")},57272:e=>{"use strict";e.exports=require("plist")},85949:e=>{"use strict";e.exports=require("process")},57160:e=>{"use strict";e.exports=require("punycode.js")},38064:e=>{"use strict";e.exports=require("semver")},9288:e=>{"use strict";e.exports=require("sharp")},93944:e=>{"use strict";e.exports=require("source-map-support")},49378:e=>{"use strict";e.exports=require("trash")},73872:e=>{"use strict";e.exports=require("type-detect")},92460:e=>{"use strict";e.exports=require("util")},75162:e=>{"use strict";e.exports=require("util/types")},29907:e=>{"use strict";e.exports=require("cluster")},76982:e=>{"use strict";e.exports=require("crypto")},34589:e=>{"use strict";e.exports=require("node:assert")},31421:e=>{"use strict";e.exports=require("node:child_process")},77598:e=>{"use strict";e.exports=require("node:crypto")},40610:e=>{"use strict";e.exports=require("node:dns")},78474:e=>{"use strict";e.exports=require("node:events")},73024:e=>{"use strict";e.exports=require("node:fs")},51455:e=>{"use strict";e.exports=require("node:fs/promises")},37067:e=>{"use strict";e.exports=require("node:http")},44708:e=>{"use strict";e.exports=require("node:https")},77030:e=>{"use strict";e.exports=require("node:net")},48161:e=>{"use strict";e.exports=require("node:os")},76760:e=>{"use strict";e.exports=require("node:path")},53916:e=>{"use strict";e.exports=require("node:path/posix")},1708:e=>{"use strict";e.exports=require("node:process")},57075:e=>{"use strict";e.exports=require("node:stream")},46466:e=>{"use strict";e.exports=require("node:stream/promises")},87997:e=>{"use strict";e.exports=require("node:timers")},57975:e=>{"use strict";e.exports=require("node:util")},38522:e=>{"use strict";e.exports=require("node:zlib")},16928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=5379);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/bin/worker.js b/bin/worker.js index 583d173..135c710 100755 --- a/bin/worker.js +++ b/bin/worker.js @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={37975:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const n=i(1708),r=i(22573),s=i(38639);function a(){return(0,s.toNotBoolean)(n.env.PS_LOG_COLOR)??(!(0,r.blank)(n.env.NO_COLOR)||["dumb","unknown"].includes(n.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(19851),r=i(7282),s=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+((0,r.isProd)()?"":`-${(0,r.nodeEnv)()}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const n=i(40958),r=i(36783),s=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let n=0;ne?.[n])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return x(e,t,i).index}function x(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function D(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=x(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await D(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),S=i(99331),b=i(95937),P=i(98314),M=i(38835),_=i(70025),E=i(8769),x=i(43334),T=i(95402),D=i(28874),k=i(63870);class C extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,n,"m",r).call(this)),i,"worker"===e?(0,k.commandTimeoutMs)():y.ShortCommandTimeoutMs),n.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,T.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+M.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&T.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,_.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,E.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,n=new WeakSet,r=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(x.isWin?3:1)*c.minuteMs,maxTasksPerProcess:D.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:D.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:D.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,k.commandTimeoutMs)(),taskTimeoutMillis:D.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(n.add(this),this.maxLength=e,r.set(this,void 0),s.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,r,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,n,"m",o).call(this,e,(e=>u(this,r,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,n,"m",o).call(this,e,(e=>u(this,r,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,r,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,r,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,n,"m",o).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,r,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,s,"f"){u(this,r,"f")[e]=c,l(this,a,e,"f")}));return u(this,s,"f")}shift(){return u(this,n,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,s,(i=u(this,s,"f"),--i),"f"),u(this,r,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,n,"m",o).call(this,u(this,s,"f")-1-e,(e=>{const i=u(this,r,"f")[e];u(this,r,"f")[e]=u(this,r,"f")[t],u(this,r,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(54993),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(94863);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},36638:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const n=i(94863);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=r},40583:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=s(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>r){const e=this.getFirst(s);null!=e&&(n=e,r=a)}}return n}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(76790),r=i(31586),s=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const n=i(19851),r=i(72993),s=i(45969),a=i(43334);t.EditionType=(0,n.lazy)((()=>a.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,n.lazy)((()=>r.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const n=i(50357),r=i(55835),s=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,n.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,n.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,n.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.omit)(e,...i),(0,s.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(31658),r=i(19851),s=i(95696);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},31658:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(19851),r=i(65843),s=i(29882);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(57975),r=i(40958),s=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(a=l(this,n,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(o=l(this,n,"f"),++o),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(n=l(this,o,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},53507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,o=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(o,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const n=i(55835),r=i(20014),s=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,n.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,n]=p(e,t);return{lat:i,lon:n}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,n.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,n=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(n)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(51455),r=i(98553);var s=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},19851:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const n=i(48161),r=i(1708),s=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,s.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:r.argv,arch:(0,n.arch)(),platform:(0,n.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(r.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:r.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(19851),r=i(32105),s=i(14593);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const a=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,a)}},56639:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(40958),r=i(55835),s=i(59455),a=i(48884);function o(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(98553),r=i(54557);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),a.size=()=>s.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const n=i(1708),r=i(31586),s=i(12168),a=i(70417);function o(){const e=(0,n.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,n.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,r.sigFigs)(o()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,r.sigFigs)(l()/s.MB,2)}},7282:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const r=n(i(1708)),s=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>r.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return r.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(40958),r=i(22573),s=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const n=(0,o.toInt)(e),r=(0,o.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(40958),r=i(42659),s=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[n,r]of(0,l.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of m(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,l.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,l.keys)(e))if(n[s]=t(s,e[s]),r++,(0,o.gt)(r,i))break;return n},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,s.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const n=i(31421),r=i(73024),s=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const x={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},T={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,n]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[n]}const k=(0,a.lazy)((()=>(0,n.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return D(e,x)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function F(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,T);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},12801:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(48161)),s=i(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const n=i(72993),r=i(50213),s=i(23560),a=i(43334);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?n.SimpleShortAppName:n.SimpleAppName];(0,s.isMainService)()&&a.isElectron||e.push((0,s.serviceName)());const t=e.join(a.isElectron?" ":"-");i(85949).title=t}catch(e){(0,r.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(41400),r=i(56409),s=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new a.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return r.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,n.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(68708),r=i(54993);function s(e){return e instanceof a?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,n||(n=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(48161)),s=n(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),S=i(24399),b=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(1708)),s=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(59455);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const n=i(5670),r=i(57150),s=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=n.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,r.logStartup)())}},28850:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,n.set(this,void 0),r.set(this,void 0),s(this,n,e,"f")}_call(){return(0,l.time)(a(this,n,"f")+(null==a(this,r,"f")?"(local)":"(remote)"),null==a(this,r,"f")?this.impl():a(this,r,"f").call(this))}setShim(e){s(this,r,e,"f")}hasShim(){return null!=a(this,r,"f")}clearShim(){s(this,r,void 0,"f")}}n=new WeakMap,r=new WeakMap},12089:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),n.add(this),this.impl=t,this.cache=i,this.toKey=a,r.set(this,void 0),s.set(this,void 0),l(this,r,e,"f")}async _call(e){return null==this.cache?u(this,n,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,n,"m",a).call(this,e),(()=>u(this,n,"m",o).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,n,"m",a).call(this,e))}}r=new WeakMap,s=new WeakMap,n=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,r,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(42659);t.ShortCommandTimeoutMs=7*n.secondMs},92322:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,n.set(this,[])}[(n=new WeakMap,Symbol.iterator)](){return r(this,n,"f")[Symbol.iterator]()}get length(){return r(this,n,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=r(this,n,"f").length-1;for(;t<=i;){const s=t+Math.floor((i-t)/2),a=this.valueOf(r(this,n,"f")[s]);if(e===a)return{found:!0,index:s};e>a?t=s+1:i=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&r(this,n,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...r(this,n,"f")];const a=t=>t<0||t>r(this,n,"f").length-1?null:(i??this.diff)(r(this,n,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return r(this,n,"f").shift()}at(e){return(0,a.at)(r(this,n,"f"),e)}toA(){return[...r(this,n,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===r(this,n,"f").length-1){const e=[...r(this,n,"f")];return r(this,n,"f").length=0,e}return r(this,n,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return r(this,n,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const n=i(1708),r=i(82328),s=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(n.stderr)||n.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(1708),r=i(95705);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},71567:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(1708)),s=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);n.write(r+"\n"),(0,o.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(40958),r=i(76790),s=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,o.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" …(+"+r+" chars)…"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const x=/^['‘’].*['‘’]$/,T=/^["“”„«»〃].*["“”„«»〃]$/;function D(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),x.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},83556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(54993);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(77598)),s=i(73913),a=i(55222);function o(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,n=224){return i.encodeBuffer(o(e,n)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,n=224){return l(e,t,i,n)}},94863:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(40958),r=i(76790),s=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,a),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,a.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function x(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,a.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,a.mapNumericOr)(t.charCodeAt(n),(e=>e),256),o=(0,a.clamp)(-256,256,r-s);i=null==i?o:(i+o)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=x,t.paddedPositionalDiff=function(e,t,i=8){return x((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(98553),r=i(88158);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},75387:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},22277:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)o(this,n,"m",r).call(this,e,t)}},84699:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},94174:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(48161)),s=n(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(42659),r=i(55835),s=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,o.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},13991:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const n=i(19851),r=i(55835),s=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,n.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function S(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function b(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):S(t)}async function P(e){const[i,n,r,s]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...n,...r,sha:s}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=S,t.assetFileImageHashFields_=b,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const n=i.capturedAt.toAssetFileFields();return null==n?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...n,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,r.map)((0,s.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),b(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),v=i(14036),w=i(45200),S=i(34238),b=(0,n.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function E(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=E;const x=["make","model","rating","cameraId","imageId","lensId","geohash"];function T(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,r.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,s.sortBy)(e,C).reverse()}function D(e){const t=S.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const n=P.indexOf(t.scheme);if(null==n)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const r=e.mtime??0,s=(0,g.parsePosixPath)(t.path),l=[];for(const t of x)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:n,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(s.ext),mtime:E(r),isEditOrUpdate:/edit|update/i.test(s.base),isCover:/cover/i.test(s.base),count:Math.abs((0,p.copySuffixCountFromName)(s.name)??0),basename:d.CmpReverseFlag+s.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return b().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function k(){return(0,r.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=D(e);if(null==t)return;const i=[];for(const e of k())i.push(t[e]);return i}t.sortAssetFiles=T,t.assetFileSortCriteriaPojo=D,t.assetFileSortFields=k,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of T(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return b().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return b().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const n=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,n.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,n.set(this,void 0),r.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,r,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,r,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,r,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,n,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,n,"f")&&clearTimeout(s(this,n,"f")),a(this,n,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},n=new WeakMap,r=new WeakMap},69591:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(87997)),s=i(31586);t.debounce=function(e,t){let i,n=[];const a=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return a.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),S=i(45599),b=i(26905),P=i(55835),M=i(31586),_=i(68708),E=i(20214),x=i(57153),T=i(85556),D=i(50213),k=i(70025),C=i(95937),F="TIMEOUT",O=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),n=(0,M.gt0)(t)?new r(F).setTimeout(t):void 0;for(null!=n&&i.push(n);;){for(let n=i.length-1;n>=0;n--){const r=i[n];if(r.isSettled){if(r.name===F)return void O().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(n,1),yield r.value}}if(i.every((e=>e.name===F)))break;try{await Promise.race(i)}catch{}}n?.clearTimeout()}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,x.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===x.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==x.PromiseStates.pending}get isResolved(){return p(this,o,"f")===x.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===x.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,o,x.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,x.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,r=I,m=function(e){if(p(this,o,"f")===x.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},27395:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(19851),r=i(40958),s=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,o.thenOrTimeoutError)(i.end(),n,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,r.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",a).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(50989);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,n.set(this,void 0),this.onEnds=[],r.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,n,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},n=new WeakMap,r=new WeakMap},99331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(7282);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=(0,n.isTest)()?e:e||r}},45608:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(1708)),s=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},60172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,n)=>{t=e,i=n})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new S(e,t,i,n)};class S extends g.ExtensibleFunction{constructor(e,t,i,l){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,r.set(this,void 0),s.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,n,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,s,0,"f"),d(this,r,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,n,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,n,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,r,"f")?void 0:Date.now()-c(this,r,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,s,(i=c(this,s,"f"),++i),"f")}},u=function(e){d(this,r,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,n,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(98553),r=i(80049);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),a=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},a.size=()=>s.size,a.callCount=()=>i,a}},22781:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,n.set(this,void 0),r.set(this,!1),s.set(this,!1)}_call(){return a(this,r,"f")?(o(this,s,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,n,"f")):(o(this,r,!0,"f"),o(this,n,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,r,!1,"f"),!0===this.runLaterIfBusy&&a(this,s,"f")&&(o(this,s,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,r,"f")}prior(){return a(this,n,"f")}async force(){return await a(this,n,"f"),this._call()}}n=new WeakMap,r=new WeakMap,s=new WeakMap},37461:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(40958),r=i(76790),s=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var S=i(20214);async function b(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const a of(0,n.compact)(await t))try{const e=await((0,l.gt0)(r)?(0,c.thenOrTimeoutError)(i(a),r):i(a));null!=e&&s.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return s}async function _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:a}){if(null==e)return[];const o=(0,n.compact)(await e);if((0,n.isEmpty)(o))return[];if((r=Math.round(r??(0,v.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:s});const u=a??(o.length<=r?w.PermissivePromises:new w.Promises(i,(()=>r))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,p.batches)((0,f.toA)(await e),t)){const e=await b(r);n.push(...await b(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await _({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await _({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,n)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,h.isFunction)(e)?e():e)}catch(e){r=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const a=await i(r,s);return null==a?n():a},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await _({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),S=i(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")}),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),n=t();return _(e,Date.now()-i),n},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>M(e,t)),i)}},42638:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),S=i(82647),b=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,o,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},4867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const n=i(40958),r=i(34546),s=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,n.compact)([(0,r.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,s.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,n.compact)([(0,r.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,s.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38639),r=i(42659),s=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},9727:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(1708)),s=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),S=i(88158),b=i(45969),P=i(43334),M=i(28874),_=i(3790);function E(e){return x().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const x=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(M.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>E(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,M.allSettings)())t.watchLater(e)}));const T=["HOME","LANG","USER"],D=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],k=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?T:D),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,M.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,M.persistedSettings)()){const n=e?i.value:i.envValue;null==n||(0,o.eql)(n,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(r.default.env,(e=>E(e)||!(0,_.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:O({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let F=!1;function O({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...k(),...i?(0,g.childProcLocale)():{},...C(n),...e??{}});for(const e of(0,M.transientSettings)())e.deleteFromEnv(r);if((0,y.isLogged)("debug")&&!F){F=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(r).map((([e,t])=>[e,(0,_.isHiddenEnvKey)(e)?"(hidden)":t])),[i,n]=(0,u.partition)(t,(([e])=>E(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(n))}return r}t.childEnv=O},84777:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(31421)),s=n(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),S=i(22911),b=i(4867),P=i(73614),M=i(70025),_=i(57159),E=i(36868),x=i(66184),T=i(45643),D=i(95402),k=i(9727),C=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function O(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,E.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,D.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,T.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{D.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,D.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,T.waitForPidExit)(i,5e3)}function I(e,i,n,r=0){const a=new Date,o=[];return(0,v.niceable)(i,n)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&O(e)}),r-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,D.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,k.spawnOptions)(n);return(0,x.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,a=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new S.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,E.endStream)(a.stdin);const v=new d.Latch;null==a.stdout?v.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==a.stderr||r?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const x=p.join("");(0,l.notBlank)(x)&&g.push(new Error(x)),!n&&(0,o.isNotEmpty)(g)&&C().warn(f+" resulted in errors:",g);const T=i.isIgnorableError??M.isIgnorableError,D=g.filter((e=>!0!==T(e)));if(D.length>0)throw 1===D.length?D[0]:new _.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:x}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,D.killPid)(a.pid,!0),e}}t.endProcess=O,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,k.spawnOptions)(n);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},3790:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const n=i(22573),r=i(41400),s=i(19851),a=i(28874);(0,r.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,s.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,n.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},34330:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),S=i(25764),b=i(99331),P=i(42638),M=i(38835),_=i(8769),E=i(57159),x=i(66003),T=i(50213),D=i(45643),k=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,T.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),a=!1!==s.ignorable;this.logger().log(a?"warn":"error","onError()",s),u(this,r,"f")||a||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=F,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,u(this,n,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,x.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=s(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),n=t?.stableBasename??1?m(i):i.base.normalize(),r=i.sibling(n);if(r.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",r.posixPathFrom((0,l.examples)()));const s=(0,d.originalsDir)();if(r.isSelfOrDescendantOf(s))return a.join("$library",r.posixPathFrom(s));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",r.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},80061:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const n=i(1708),r=i(31586),s=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},54772:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const n=i(19851),r=i(40958),s=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),v=(0,n.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const n=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:n,closeLabhashes:[n],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function S(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,n.lazy)((()=>(0,r.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return S((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=S;const b=new Map;function P(e){return(0,a.gte0)(e)?(0,s.getOrSet)(b,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const n=(0,c.unlabhash)(e),s=S(n);return null!=n&&null!=s&&((0,r.pushUniq)(s.closeLabhashes,e),(0,r.pushUniq)(s.closeRgb,(0,c.lab2rgbhex)(n))),s})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const n=i(19851),r=i(40958),s=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(E(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>x(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,r.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],n=[];for(let r=0;re>b?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-n)])}function _(e){const[t,i,n]=v(e),r=(t+16)/116,s=i/500+r,a=r-n/200,o=s*s*s,l=a*a*a,u=o>b?o:(116*s-16)/P,c=t>8?Math.pow(r,3):t/P,d=l>b?l:(116*a-16)/P;return[u*S.X,c*S.Y,d*S.Z]}function E(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function x(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=E,t.LabBitZip=(0,n.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=x;const T=new Map;function D(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function k(e){const[t,i,n]=(0,f.clampRGB)(e),r=Math.max(t,i,n),s=r-Math.min(t,i,n),a=s?r===t?(i-n)/s:r===i?2+(n-t)/s:4+(t-i)/s:0;return[60*(a<0?a+6:a),r?s/r*100:0,r/255*100]}function C(e){return F(k(e))}function F(e){const[t,i,n]=e,r=(200-i)*n/100;return[t,r>0&&r<200?i*n/100/(r<=100?r:200-r)*100:0,r/2]}function O(e){const[t,i,n]=e,r=i*(n<50?n:100-n)/100;return[t,r>0?2*r/(n+r)*100:0,n+r]}function I(e){const t=e[0]/360*6,i=e[1]/100,n=e[2]/100,r=Math.floor(t),s=n*(1-i),a=n*(1-(t-r)*i),o=n*(1-(1-t+r)*i),l=r%6;return(0,f.clampRGB)([255*[n,a,s,s,o,n][l],255*[o,n,n,a,s,s][l],255*[s,s,o,n,n,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,s.getOrSet)(T,e,(()=>D(e,t))):D(e,t)},t.minLabhash=(0,n.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,n.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=k,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(O(e))},t.hsv2hsl=F,t.hsl2hsv=O,t.hsv2rgb=I,i.c[i.s]===e&&console.log(x([0,0,0]))},42079:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const n=i(31586),r=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,n,s]=e,[a,o,l]=t,u=i-a,c=n-o,d=s-l,h=(0,r.sqrt)(n**2+s**2),f=h-(0,r.sqrt)(o**2+l**2),m=(0,r.sqrt)(c**2+d**2-f**2);return(0,r.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,n.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const s=1,a=1,o=1;function l(e,t){const[i,n,l]=e,u=(0,r.sqrt)(n**2+l**2),[c,d,h]=t,f=(u+(0,r.sqrt)(d**2+h**2))/2,m=.5*(1-(0,r.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=n*(1+m),g=d*(1+m),y=(0,r.sqrt)(p*p+l*l),v=(0,r.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let S=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);S+=2*(S<0?1:0)*Math.PI;const b=c-i,P=v-y;let M=y*v==0?0:S-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,r.sqrt)(y*v)*Math.sin(M/2),E=(i+c)/2,x=(y+v)/2;let T;y*v==0?T=w+S:(T=(w+S)/2,T-=(Math.abs(w-S)>Math.PI?1:0)*Math.PI,T+=2*(T<0?1:0)*Math.PI);const D=(E-50)**2,k=1-.17*Math.cos(T-Math.PI/6)+.24*Math.cos(2*T)+.32*Math.cos(3*T+Math.PI/30)-.2*Math.cos(4*T-63*Math.PI/180),C=1+.015*D/(0,r.sqrt)(20+D),F=1+.045*x,O=1+.015*x*k,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*T-275)/25)**2),L=2*(0,r.sqrt)(Math.pow(x,7)/(Math.pow(x,7)+Math.pow(25,7))),A=-1*Math.sin(2*I)*L;return(0,r.sqrt)(Math.pow(b/(s*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*O),2)+A*P/(a*F)*_/(o*O))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const n=i(40958),r=i(31586),s=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,n.compact)(e.map((e=>[e.rgbhex,(0,r.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,n.compact)((0,r.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,r.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const n=(0,s.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=n&&(0,r.gt0)(i)?new c(n,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,r.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,r.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},40401:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),v=i(85810),w=i(3048),S=i(76490),b=i(1971),P=(0,n.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=b.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=b.ModeCount){const i=Date.now(),n=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of x({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function D(e){const i=t,n=4*t;g=Math.round(Math.max(i,Math.min(n,e)))}const C=f.length<=g?[]:(0,r.compact)(M.slice(0,n).map((e=>{const n=(0,p.kmeans)(f,g,{...E,seed:e}),r=k(n.centroids,f.length);if(r.lengtht&&D(g-1);const s=r.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,n]of a.entries()){const r=(0,v.unlabhash)(i),s=(0,c.leastByCtx)(e,(e=>h(e.centroid,r)));null!=s&&(0,l.times)(n,(()=>t.push(s.value)))}return t.p84}(s),2);return{...n,centroids:s,description:{kIn:g,kOut:n.centroids.length,kMerged:r.length,score:o,iterations:n.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:n}),T(a,t);const O=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),I=(0,s.sortBy)(F?.centroids,(e=>-e.size)).map((e=>S.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:O,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,S.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:O,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const n of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,n)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,n))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},E=(0,n.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function x({labs:e,minK:t,thresh:i,retries:n=3}){if(n<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const r=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(r))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const s=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=r));return s.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:r,minK:t,pixelCount:e.length,filteredCount:s.length}),s):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:r,minK:t,retries:n,pixelCount:e.length,filteredCount:s.length}),x({labs:e,minK:t,thresh:.75*r,retries:n-1}))}function T(e,t){const i=e.countSum,n=e.size;D(e);const s=e.size,a=(0,r.compact)(e.top(t).map((([e,t])=>S.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:n,mergedColors:s,pixelCount:i,pctOmitted:l})}}function D(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[n,r]of[...e.entriesByCountDesc()]){const s=(0,v.unlabhash)(n),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,s)<=t));null==a?i.push({lab:s,labhash:n}):(e.delete(n),e.incr(a.labhash,r))}return e}function k(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const n=[];for(const t of e){const e=n.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?n.push(t):e.size+=t.size}const r=t/100;return(0,s.sortBy)(n.filter((e=>e.size>r)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{E.unset()}))})),t.maybeFilterGrey=x,t.dominantColorsFromModes=T,t.mergeLabhashes=D,t.mergeNearCentroids=k},85409:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const n=i(19851),r=i(31586),s=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,n.lazy)((()=>(0,s.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,r.within)(0,100,e[0])&&(0,r.within)(-110,110,e[1])&&(0,r.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,n=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),n.push(e[2])}const r=(i.stdDev??0)+(n.stdDev??0),s=r{Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const n=i(31586),r=i(68708),s=i(50989);t.isModeData=function(e){return(0,n.gt0)(e.mode0)&&(0,n.gt0)(e.mode0pct)},t.ModeDataKeys=(0,s.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,r.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,r.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const n=i(31586),r=i(39926),s=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,n.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,s.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,n.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,r.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(51168),r=i(19851),s=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const n=i(77988),r=i(19851),s=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),n=i?.groups;return null==n?void 0:f.for((0,c.parseExifDateTime)(n.start,t),(0,c.parseExifDateTime)(n.end,t),(0,a.toInt)(n.index),(0,a.toInt)(n.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>n.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>n.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,n=1){if(null==e||!e.isValid||null==t||!t.isValid)return;n=(0,a.clamp)(1,1e3,(0,a.toInt)(n,{defaultValue:1})),i=(0,a.clamp)(0,n-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),s=(t.toMillis()-r)/(n+1)*(i+1),o=e.plus({milliseconds:s});return null==o?void 0:new f(e,o,t,i,n)}constructor(e,t,i,n=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=n,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((n=>function({start:e,end:t,middle:i,field:n}){return null!=e[n]&&null!=t[n]?i[n]:void 0}({start:e,middle:t,end:i,field:n})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const n=i(77988),r=i(51168),s=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),v=i(21330),w=i(928),S=i(54261),b=i(73389),P=i(51275),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof n.ExifDate||e instanceof n.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof n.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function x(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof n.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function T(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof n.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),n=x(e);if(null!=i&&null!=n)return(0,c.gt0)(t)&&t>n-i?{start:Math.round((i+n)/2-t/2),end:Math.round((i+n)/2+t/2)}:{start:i,end:n}}function C(e,t,i,n){const[r,s]=(0,a.sortBy)([k(e,i),k(t,n)],(e=>e?.start));return null!=r&&null!=s&&null!=r&&null!=s&&(r.start===s.start||r.end>=Math.min(s.start,s.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=x,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof n.ExifDate?r.DateTime.fromObject(e):T(e)},t.datedToDateTime=T,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:n}){if(null==e||null==t)return!1;if(i??(i=D(e)),n??(n=D(t)),C(e,t,i,n))return!0;const r=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==r&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,n)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const n=i(31586),r=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,n.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(22573),r=i(31586),s=i(54557),a=i(91655),o=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(51168),r=i(40958),s=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},98247:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const n=i(77988),r=i(51168),s=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function v(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:r,month:s,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(n.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==s||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(n.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(n);return b({year:r,month:s,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(n.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof n.ExifDate&&t instanceof n.ExifTime))return;const i=new n.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:n.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof n.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=n.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},74417:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const n=i(51168),r=i(22573),s=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*s.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=n.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=n.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const n=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,n.pad2)(e.getMonth()+1),(0,n.pad2)(e.getDate()),"-",(0,n.pad2)(e.getHours()),(0,n.pad2)(e.getMinutes()),(0,n.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,n.pad2)(e.getUTCMonth()+1),(0,n.pad2)(e.getUTCDate()),"-",(0,n.pad2)(e.getUTCHours()),(0,n.pad2)(e.getUTCMinutes()),(0,n.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const s=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),v=i(79842),w=i(66649),S=i(98247),b=i(98725),P=i(928),M=i(54261),_=i(73389),E=i(89724),x=i(17415),T=i(88600),D=i(51275);function k(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,n.set(this,(0,p.lazy)((()=>(0,T.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(b.ISO_YMD_RE.exec(e)?.groups??b.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tk(e))).join("-")}toLocal(){return(0,E.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function F(e,t){if(e instanceof s.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,M.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,x.zoneToTzOffsetMinutes)((0,w.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(n=>(0,d.map)((0,P.getMonth)(e),(r=>(0,d.map)((0,P.getDay)(e),(s=>(0,d.map)((0,P.getHour)(e),(a=>(0,S.dateObjectToExifDateTime)({year:n,month:r,day:s,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",n=15*(0,h.round)(e/15),r=Math.abs(n),s=Math.floor(r/60),a=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${k(s)}:${k(a)}`},t.toExifDateTime=F,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof s.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,M.hasTime)(e)||(i??(0,v.datedToPrecisionMs)(e))>=c.dayMs?L(e):F(e,(0,D.getZoneName)(e))?.toISOString({includeOffset:t})};const O="yyyy:MM:dd HH:mm:ss.SSS",I=O+"ZZ";function L(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>k(e))).join(t)}function A(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,n]=[e,t].map(w.datedToMillis);return null==i||null==n?void 0:i-n}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,v.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,D.hasZone)(t)?I:O):void 0},t.datedToYMD=L,t.toFuzzyDate=A,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,n=1){if(null==(0,w.datedToMillis)(e)||null==(0,w.datedToMillis)(t))return;const[r,s]=[e,t].map((e=>(0,w.datedToMillis)(e))).sort(),o=(s-r)/(n+1),l=(0,D.getZoneName)(e),u=l===(0,D.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(r+o*i,{zone:u});return[e,t].some((e=>!(0,M.hasTime)(e)))?A(c):c},t.setZone=function(e,t,i){const n={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,D.hasZone)(e)},r=(0,x.normalizeZone)(t);return null!=e&&null!=r&&(0,M.hasTime)(e)?e instanceof y.DateInterval?e.setZone(r,n):F(e)?.setZone(r,n):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,v.datedToDateTime)(e);if(null==i)return;const n=(0,D.getZoneName)(e);return null!=n&&"UTC"!==n||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),v=i(68852),w=i(4001),S=i(28874),b=i(24689),P=i(79842),M=i(66649),_=i(98247),E=i(21330),x=i(54261),T=i(73389),D=i(16400),k=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,T.isDateTime)(i)?i:(0,x.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function O(e,t,i){try{const n=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=n)return n;const r=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:n=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const n=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${n})`,f:i=>O(i,n,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:n}))if(r(e))for(const e of s){const t=a(e);if(null!=t&&(0,k.isValidDate)(t))return t}}t.parseDated=I;class L{constructor(e={}){n.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>a(this,n,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>a(this,n,"m",s).call(this))),a(this,n,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,n=new WeakSet,r=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,n,"m",r).call(this,[e,t.seps,t.yearRE]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,e]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const n=i(55835),r=i(31586),s=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,n.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,r.gt0)(a(e))||(0,r.gt0)(o(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,n.map)(o(e),(t=>{const i=l(e)??0;let n=(t+i/1e3).toString();for(t<10&&(n="0"+n),0===i&&(n+=".");n.length<6;)n+="0";return n}))}},54261:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const n=i(77988),r=i(31586),s=i(68708);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof n.ExifDateTime}},73389:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const n=i(51168);t.isDateTime=function(e){return n.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const n=i(51168),r=i(19851),s=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const n=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*n(),s=n(),a=n(),l=(0,o.toGt0)(n()),u=(0,o.toGt0)(n()),c=(0,o.toGt0)(n());return{year:i,month:c,day:u,hour:l,minute:a,second:s,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(n.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const n=i(19851),r=i(76790),s=i(31586),a=i(9092),o=(0,n.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const n=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(r=>{const s=n.format(new Date(2017,r));e.set(s,r+1),"short"===i&&"en-US"===t&&e.set(s+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,r.sort)([...o().keys()])}},17415:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const n=i(77988),r=i(51168),s=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const n=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=n&&Math.abs(n-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(n)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-±+−])/,x=/[-−]/,T=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=x.test((0,h.toS)(e.groups.tzSign))?-1:1,n=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+n);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,T,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const O=/\b(?(?:Etc\/)?GMT)\b/,I=(0,s.lazy)((()=>(0,m.concatRegexp)([O,E,D,m.RegExpOptional.from(k)])));function L(e){return F(I().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},88600:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const n=i(51168),r=i(19851),s=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),v=(0,r.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),w=(0,r.lazy)((()=>(0,s.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),S=(0,r.lazy)((()=>(0,s.compact)(w().map((e=>(0,p.datedToISO)(e)))))),b=(0,r.lazy)((()=>(0,s.compact)(w().map((e=>(0,y.datedToLocal)(e)))))),P=(0,r.lazy)((()=>(0,s.compact)(w().map((e=>(0,m.datedToMillis)(e))))));function M(e){if(null==e)return!1;const t=E(e);return v().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return M(e)?e:void 0},t.isValidDate=M;const _=String(new Date("bad"));function E(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===_)return _;const t=(0,s.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const r=[];if((0,l.isNumber)(e)||r.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&r.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,x())&&r.push("year is in the future"),null==t&&null!=i&&r.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&r.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&r.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const s=n.DateTime.fromObject({year:e,month:t,day:i});s.isValid||r.push(s.invalidExplanation??"not valid")}return(0,s.compact)(r)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const n=(0,m.datedToMillis)(e);(0,u.gt)(n,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):b().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):S().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,s.uniq)((0,s.compactBlanks)(t)).join("; "))}catch(t){return v().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=E;const x=(0,r.lazy)((()=>n.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return M(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==E({year:e,month:t,day:i})}},51275:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const n=i(77988),r=i(31586),s=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof n.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==n.UnsetZoneName&&e.zone.offset(Date.now())!==n.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===n.UnsetZoneName?void 0:e.zone?.name:e instanceof n.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(50989);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(50989);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(50989);t.RepairModes=(0,n.strEnum)("dump","recover")},15056:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(50989),r=i(7311);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(50989);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=s(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),S=i(29882),b=i(45969),P=i(43334),M=i(28874),_=i(41692),E=i(32774),x=i(80612),T=i(32551),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function C(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:E.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:E.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,T.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,T.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,x.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,x.firstDir)({dirs:C(),desc:"cache"})));const F=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),M.Settings.cacheDir.watchLater(O)}));function O(){M.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{F();const e=M.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},46292:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(19851),r=i(45969),s=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(66430),r=i(45969),s=i(32774);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(76760)),s=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(22573),r=i(96706),s=i(29882);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44652),r=i(40958),s=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(48161),r=i(76760),s=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},35280:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(29882),r=i(49776),s=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(22573),r=i(54993),s=i(29882),a=i(28874);function o(e){return(0,n.toNotBlank)((0,r.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(40958),r=i(55835),s=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e),!1)}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},46296:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(76760)),s=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(76760),r=i(19851),s=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(o.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38639),r=i(7282),s=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,r.isProd)()&&!(0,s.isPacked)()&&((0,n.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38639),r=i(44198);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},44198:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(73024)),s=i(76760),a=n(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),S=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>a.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),i={...a.default.env};for(const n of e)try{const e=(0,d.debom)(r.default.readFileSync((0,g.resolve)(n))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,c.entries)(s))t.test(e)||(i[e]=n)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(50989);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(22573),r=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const a of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(a));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const a=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(1708)),s=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,a.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(58587),r=i(19851),s=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),n-a.length,r)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,n).join("; ")}},41954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(40958),r=i(26905),s=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(40958),r=i(76790),s=i(50989),a=i(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(40958),r=i(38639),s=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,n.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,r.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const n=i(38835);class r extends Error{constructor(e){super(e+n.InternalErrorFlag)}}t.InternalError=r},8769:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(22573),r=i(31586),s=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(40958),r=i(22573),s=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,n.set(this,new Map),r.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(s(this,n,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=s(this,n,"f").get(e);return null!=a&&(a.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},34102:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const n=i(78474),r=i(19851),s=i(15197);t.ee=(0,r.lazy)((()=>{const e=new n.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(73024)),s=n(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>s.default.geteuid?.())),h=(0,a.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const a=r??d(),o=null!=s?[s]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!n||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},21144:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(76760)),s=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,a.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(73024),r=i(76760);function s(e){return[...a(e)]}function*a(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function o(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,i){var n,r,s,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),v=f(i(1708)),w=i(46466),S=f(i(57975)),b=f(i(38522)),P=i(19851),M=i(40958),_=i(5233),E=i(22573),x=i(42659),T=i(50357),D=i(96249),k=i(98553),C=i(55835),F=i(31586),O=i(68708),I=i(97790),L=i(39926),A=i(51926),R=i(59455),N=i(54993),B=i(48884),z=i(22911),j=i(99331),V=i(56519),W=i(56038),H=i(31562),U=i(76850),q=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Z=i(43334),X=i(81168),Y=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),ne=i(84542),re=i(89968),se=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),Se=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,a=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=be().get(i);if(null!=n)return n;const r=(0,fe.resolve)(i),s=new Pe(r,t);return be().set(i,s),be().set(r,s),s}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,X.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,R.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(E.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,x.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>=(0,x.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>(0,x.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,H.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*x.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),ne.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,O.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,j.ending)()?1:3,timeoutMs:0,retryDelay:x.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",o).call(this,(0,X.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",o).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",o).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,Y.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new z.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,F.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new z.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),Me)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,C.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,X.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Y.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*x.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let Me=!0;t.useFsWatch=function(e){Me=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},19748:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const n=i(28874),r=i(88840),s=i(14036),a=i(29882);function o(e){return t=>n.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(r.ExtTypes.Video),t.isAssetFileExtension=o(r.ExtTypes.AssetFile)},84542:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(40958),r=i(96249),s=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,s.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},70698:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(76760),r=i(19851),s=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(76760)),s=n(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=s(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),S=i(16287),b=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await o.stat(t);return new _(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},20197:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(76760)),s=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(n.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),v=i(54557),w=i(50213),S=i(88158),b=i(56519),P=i(46292),M=i(32551),_=i(35280),E=i(87290),x=i(96706),T=i(57902),D=i(43334),k=i(78984),C=i(33995),F=i(28874),O=i(21144),I=i(83278),L=i(48313),A=i(85772),R=i(78133),N=i(46356),B=i(17217),z=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),j=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=j.get(t);if(null!=i)return i;const n=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),r=V.test(t)||n.isDirectorySync(),s=(0,R.native2posix)(n.nativePath),a=r?(0,m.ensureSuffix)(s,"/"):s;return j.set(t,a),j.set(a,a),j.set(n.nativePath,a),a}t.formatPathForGlob=W;class H{constructor(e,t,i=!0){if(n.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),z().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,z().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,S.pairToObject)(this.reason,a(this,n,"m",r).bind(this)):{}}}n=new WeakSet,r=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return z().tap({msg:"apply()",level:i?T.LogLevels.debug:T.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class U{constructor(){s.set(this,[])}push(...e){for(const t of e){if(!t.valid){z().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,s,"f").find((e=>e.pattern===t.pattern));null==e?a(this,s,"f").push(t):z().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new H((0,R.native2posix)(e),t))}toA(){return a(this,s,"f")}}s=new WeakMap;const q=new H("**/.*","hidden file"),G=new H("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new U;e.push(G,q);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new H((D.isWin?"*":"")+"/"+t.s+"/",t.desc));if(D.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,x.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}D.isLinux&&e.push(new H(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new H("**/"+t.s+"/",t.desc));function t(t,i,n){if(!(0,h.blank)(t)){const r=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===r.length&&e.push(new H(`**/${t}/${r[0]}/`,n)),r.length>1&&e.push(new H(`**/${t}/(${r.join("|")})/`,n))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new H("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new H("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const n=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",n,"Linux /var"),t("mnt",n,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Z=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:ne,notInHiddenPhotoStructureDir:se,whyNoMedia:A.whyNoMedia,notHidden:re}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:se}])),t.excludeGlobs=(0,u.lazy)((()=>{Z();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&z().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):z().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new H(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const n=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[r,s]=(0,g.partition)(n,(e=>e.pattern.endsWith("/")));return{dir:r,file:s}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const X=[{disableAllFilters:()=>!0}],Y=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Y:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Y:(0,t.excludeBundles)().dir}async function ie(e){return F.Settings.disableAllFilters.valueOrDefault?void 0:k.Predicates.whyRejected(e,...te(e))}function ne(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function re(e){return(0,b.thenNot)((0,L.isHidden)(e))}function se(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,E.libraryDirPosixFile)(),(0,E.libraryOriginalsDirPosixFile)(),...F.Settings.argvScanPaths.values,...F.Settings.scanPaths.values]));return z().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,O.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=se},88561:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const n=i(73024),r=i(22573),s=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...i]of d)for(const n of i)e[n]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,r.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const n=i(68708),r=i(17217),s=i(16287),a=i(68284);async function o(e){return(0,n.pick)(await(0,s.stat_)((0,r.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,r.toNativePath)(e)))?void 0:(0,n.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const n=i(68817),r=i(19851),s=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,r.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,n.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,s.blank)(r)||(0,s.blank)(a)?void 0:{ext:a,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),n.add(this),this.nativePath=e,r.set(this,[]),s.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,s,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,n,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,r,"f").push(e)}close(){u(this,s,"f").close()}}t.FileWatcher=m,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,r,"f"))t(e,this.nativePath)}}},73209:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p,g,y,v,w,S=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const M=i(58587),_=P(i(44652)),E=i(87997),x=i(40958),T=i(17586),D=i(42659),k=i(50357),C=i(75240),F=i(55835),O=i(31586),I=i(30976),L=i(13538),A=i(54993),R=i(7282),N=i(68852),B=i(23560),z=i(25764),j=i(38836),V=i(99331),W=i(22781),H=i(38835),U=i(55222),q=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,r,Math.max(Date.now(),S(this,r,"f",s)+1),"f",s),(0,x.compactBlanks)([U.TokenRadix.encode(S(this,r,"f",s)),B.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,O.toInt)(J.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return S(this,r,"f",o).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>S(this,n,"m",w).call(this)),e.endableRank??z.EndableRanks.postdb,(0,q.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,b(t=r,r,(i=S(t,r,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(S(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await S(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+S(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),S(r,r,"f",o).push(this)}get acquired(){return S(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await S(this,n,"m",f).call(this,e)??S(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,T.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==S(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:D.secondMs);b(this,c,setInterval((()=>S(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=S(this,c,"f")&&(clearInterval(S(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(S(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),b(this,u,!1,"f"),(0,F.map)(S(this,d,"f"),(e=>(0,E.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?S(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>S(this,n,"m",v).call(this)),(0,O.toGt0)(this.staleMs)??D.secondMs),"f"),S(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(S(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,L.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>S(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await S(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await S(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+H.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,M.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),S(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await S(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await S(this,n,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,x.filterInPlace)(S(r,r,"f",o),(e=>S(e,l,"f")!==S(this,l,"f")))},s={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(22573),r=i(51926),s=i(54993),a=i(17217);function o(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(22573),r=i(55835),s=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},14977:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=n(i(44652)),s=n(i(73024)),a=i(46466),o=n(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(s.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(77598)),s=n(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,a.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(19851),r=i(42659),s=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,n.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(22573),r=i(54993),s=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(57075),r=i(51926),s=i(54993);class a extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),a=n.pop();this._prior=a??"";let o=!1;for(const e of n)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(76760)),s=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},85772:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=s(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),S=i(88561),b=i(65238),P=i(16287),M=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),_="NoMedia",E=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+_+"$","im"),x=Object.freeze(["."+_,_]),T=Object.freeze((0,u.flatten)(x.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function D(e){return null!=E.exec(e)}t.isNoMediaName=D;const k=(0,o.lazy)((()=>new S.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=v.BaseFile.for(e),n=await i.stat();if(null==n||!n.isFile()&&!n.isDirectory())return null;if(n.isFile())return D(i.base)||await(0,w.isCachedirTagFile)(i)?k().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await k().getOrSetAsync(i.nativePath,(()=>F(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function F(e){if(D(e.base))return k().set(e.parent().nativePath,e.nativePath),M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,b.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,n=await Promise.race([O(e.nativePath,i),(0,b.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=n?n:await(0,w.isCachedirTagDirectory)(e)?M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function O(e,t){for(const i of g.isCaseSensitiveFs?T:x){if(!0===t?.aborted)return null;const n=a.default.join(e,i);if(await(0,P.exists)(n,p.LogLevels.trace))return M().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(n)})}return null}async function I(e,t,i){for(const n of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(D(n.basename))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,n.basename))});if(n.basename===w.CACHEDIR_TAG){const t=(0,a.join)(e,n.basename);if(await(0,w.isCachedirTagFile)(t))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=F,t._dirHasNoMediaChild=O},29882:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44652)),s=n(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),S=i(17217),b=i(16287),P=i(66430),M=i(5545);function _(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return C(e).some(_)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return x((0,v.posix2native)(e))},t.extname=function(e){return x(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const E=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function x(e){const t=E.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function T(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),i=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,p.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(y.isLinux?n===r:(0,p.equalsIgnoreCase)(n,r))}function C(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function F(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function O({p:e,maxLength:t}){const i=(0,S.toNativePath_)(e);if(i.length<=t)return i;const n=C(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),L([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("…"),L([...r,...s])}function I(e){return e.startsWith("\\\\")}function L(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=x,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return k(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(S.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=F,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,S.toNativePath_)(e),n=(0,S.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,p.stripPrefix)((0,v.native2posix)(n).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=O,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:n=e.length}){const r=[];for(const n of e.slice(0,i))r.push(O({p:n,maxLength:t}));return r.join(", ")+(n>i?`, and ${n-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=x(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(M.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(F(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await r.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=L,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:L(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(76760)),s=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),S=i(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,a.uniq)((0,a.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){var n,r,s,a=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),S=i(22573),b=i(42659),P=i(26905),M=i(75240),_=i(55835),E=i(31586),x=i(68708),T=i(13538),D=i(89937),k=i(12168),C=i(54993),F=i(48884),O=i(50213),I=i(45255),L=i(81168),A=i(56519),R=i(56038),N=i(31562),B=i(84777),z=i(9595),j=i(38835),V=i(70025),W=i(57902),H=i(55222),U=i(43334),q=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Z=i(34238),X=i(87001),Y=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),ne=i(32144),re=i(73209),se=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,O.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>H.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,Y.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>U.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),n=new fe(i,t);return(0,L.isString)(e)&&he().set(e,n),he().set(i,n),n}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,z.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,z.originalsDir)(),descendant:this,acceptSelf:!0}))return U.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Y.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(U.isWin||U.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,x.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(s&&a)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:a,minSizeBytes:i,timeoutMs:r,dirty:l})}return o&&n?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,T.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,E.clamp)(I.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+j.NonRetriableErrorFlag);if(r.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+j.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),U.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):U.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+j.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const n=i(40958),r=i(22573),s=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),v=i(83278),w=i(19748),S=i(92423),b=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,s.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,s.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,s.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,s.gte)(e.ImageWidth,i)&&(0,s.gte)(e.ImageHeight,i)),(()=>!1)):null}async function _(e){if(!(0,s.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function E(e){if(!(0,s.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function x(e){return!(0,r.blank)(await(0,p.readMimeType)(e))}async function T(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,s.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function D(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function k(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,r.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,r.notBlank)(t.Make)&&(0,r.notBlank)(t.Model):null}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,b.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.gte)(i,t)}async function O(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.lte)(i,t)}function I(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,S.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:O}]}function L(e){return[...I(e),{notMissingMimeType:x},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:k},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:E},{notRejectedRating:T},{notExcludedKeyword:D}]}async function A(e,t){return await u.Predicates.whyRejected(e,...t??L(e))??await(0,S.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,n.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=O,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,S.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=L,t.whyRejectFile=A,t.acceptFile=async function(e){return null==await A(e)}},78133:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(76760)),s=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,a.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},43899:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const r=n(i(76760)),s=n(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(r.default.join((0,p.execDir)(),"resources"),r.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const n=r.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44652),r=i(19851),s=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,r.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44652),r=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,a=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,a,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},69428:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=s(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44652),r=i(84542);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},32323:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(57075);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},65238:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(51455)),s=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),S=i(88561),b=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function M(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=M;const _=(0,a.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function E(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function x(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),n=T(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(r===f.Timeout&&(0,g.onTimeout)({soft:!1}),r!==f.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=E,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),M()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?M():E(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){E(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await x(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?x(e):T(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=x,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=T},53265:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const r=i(73024),s=n(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=s.default.resolve(t,...e);if((0,r.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const n=i(22454),r=i(28874),s=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new n.CountingSet;for(const i of(0,s.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>r.Settings.maxDuplicatePathElements.valueOrDefault}},50274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const n=i(50989);t.SidecarExts=(0,n.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(22573),r=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},17217:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const r=n(i(73024)),s=n(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=S(e),n=S(t);if(i!==n)return"inconsistent file type: "+i+" ≠ "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(b(n),b(r));if(null==s||s>1)return"unmatched "+i+": "+n+" ≠ "+r}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const r=n(i(73024)),s=i(22573);function a(e){try{return(0,s.blank)(e)?void 0:r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(28874);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(22573),r=i(56409);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(57075)),s=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:n}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(n,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const r=n(i(73024)),s=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),v=i(19851),w=i(40958),S=i(22573),b=i(42659),P=i(98553),M=i(31586),_=i(68708),E=i(50989),x=i(51926),T=i(85556),D=i(54993),k=i(89788),C=i(23467),F=i(7282),O=i(23560),I=i(77377),L=i(71567),A=i(73568),R=i(25764),N=i(38836),B=i(99331),z=i(12959),j=i(87290),V=i(46296),W=i(98314),H=i(38835),U=i(5012),q=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Z=i(84542),X=i(73428);t.AssetFileSyncStates=(0,E.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,E.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,E.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,E.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const Y={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,_.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,j.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function ne(){return ie().join("README.txt")}t.SyncReportHeaders=(0,E.strEnum)(...(0,_.keys)(new class{constructor(e,t,i,n,r,s,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=n,this.from=r,this.elapsedMs=s,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=ne,t.ensureSyncReportReadme=(0,v.lazy)((()=>(0,X.writeTextfile_)(ne().nativePath,(0,x.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(Y)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=b.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,q.isCsvExt)(e)&&(0,M.gte)(e.mtimeMs(),t)))},t.syncReport=(0,v.lazy)((()=>new re));class re extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,n,"m",d).call(this)),R.EndableRanks.predb),n.add(this),r.set(this,void 0),s.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new k.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,r,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,S.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,U.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,D.toS)(e.path),state:e.state,details:(0,D.toS)(e.details).trim().replace(/\r?\n/g,"; ")},r={ts:t,at:new Date(t).toISOString(),...i,...(0,_.pick)(e,"from","elapsedMs","url")};(0,_.isEmptyObj)(e.meta)||(r.meta=(0,P.stringify)(e.meta)),(0,F.isTest)()&&process.stdout.write((0,P.stringify)(e)+Z.Newline),f(this,n,"m",u).call(this,r)}}maybeSystemData(e){(0,O.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:n}){const r=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const s=await n(),a=s.state??(null!=s.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+H.InternalErrorFlag,{path:e,result:s}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-r,...s,state:a}),s}catch(n){throw this.logger.warn("wrap_() caught error",{error:n}),this.onProgress({path:e,from:i,state:(0,B.ending)()||n instanceof A.AbortError?t.SyncFileStates.canceled:n instanceof T.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(n),elapsedMs:Date.now()-r}),n}}get output(){return f(this,s,"f")??f(this,n,"m",h).call(this)}async flushClose(){return f(this,n,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,s,"f");return m(this,s,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,r,"f")}}t.SyncReport=re,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,n=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,n,"m",c).call(this,i):(f(this,n,"m",c).call(this,{...i,details:(0,w.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const n=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(n+Z.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,r,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,z.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,r,"f").nativePath),this.logger.info("Opening new report: "+f(this,r,"f")),(0,F.isTest)()&&(0,L.stdoutWrite)({syncReport:f(this,r,"f").nativePath},!1),m(this,s,(0,g.createWriteStream)(f(this,r,"f").nativePath),"f"),f(this,s,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Z.Newline),f(this,s,"f")}},89966:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=n(i(48161)),s=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44652)),s=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},84258:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=s(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const n of(0,l.toA)(e))try{null!=n&&await a.unlink((0,c.toNativePath_)(n))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+n,{error:e})}}},5545:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(76760)),s=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},70257:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(30976),r=i(45255),s=i(17217);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,n.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,s.basename)(e)??"")}},58722:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(57075),r=i(22911);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},73428:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44652)),s=n(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(73024)),s=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,o.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,o.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,a.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},18454:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p,g,y,v,w,S,b,P,M=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},_=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const E=i(19851),x=i(40958),T=i(76790),D=i(22573),k=i(41400),C=i(50357),F=i(26905),O=i(50268),I=i(55835),L=i(68708),A=i(30976),R=i(51926),N=i(13538),B=i(42279),z=i(59455),j=i(54993),V=i(48884),W=i(89788),H=i(22454),U=i(50213),q=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Z=i(77740),X=i(98314),Y=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),ne=i(33866),re=i(21525),se=i(82638),ae=(0,E.lazy)((()=>(0,U.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{M(this,r,"f",l).push(e+": failed: "+(0,X.errorToS)(t)),this.onResultChange()})),M(this,r,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return M(this,r,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){M(this,r,"f",l).push((0,R.isString)(e)?e:(0,X.errorToS)(e)),this.onResultChange()}static lastErrors(){return M(this,r,"f",l).toA()}static addLoadingMsg(e){M(this,r,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,x.compact)((0,z.toA)(e)).map(j.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:M(this,r,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[M(this,r,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=M(this,r,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>M(this,r,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?ne.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,r.reset()}static findById(e){return M(this,r,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,O.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=M(this,r,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=r.summary();if(e.pendingCount>0){const t=await Promise.all(r.testResultsCritical());e=r.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){r.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,F.shortStack)());else{this.onResultChange(),M(this,r,"f",l).clear(),M(this,r,"f",d).clear(),M(this,r,"f",h).clear(),M(this,r,"f",c).clear(),this.summary.clear(),_(this,r,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new r(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return M(this,r,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,s,o,l,u,c,d,h,f,m,b,P=ee.commandTimeoutMs){n.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=s,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=b,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),w.set(this,(0,E.lazy)((async()=>{await M(this,p,"f").prior(),(0,C.eql)(M(this,g,"f"),M(this,n,"m",v).call(this))||(this.onReset?.(),await this.refresh(),M(this,w,"f").unset())}))),this.refresh=(0,E.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await M(this,p,"f").prior();const e=M(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,U.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[O.HealthCheckSections.ordinal(this.section),l??999,this.id],_(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>M(r,r,"f",a).enqueue({name:this.id,l:()=>M(this,n,"m",S).call(this,o)}),ttlMs:b}),"f"),this.isCritical&&M(this,p,"f").watchLater({onChange:r.onCriticalResult,onError:r.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>M(this,w,"f").call(this)))}isStale(){return M(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return M(this,p,"f").settledCount()}reset(){return M(this,p,"f").unset(),this.onReset?.(),_(this,g,{starting:!0},"f"),this}setTTL(e){M(this,p,"f").setTTL(e)}result(){return M(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return M(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return M(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??M(this,n,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,x.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),n={};return(0,x.isNotEmpty)(i)&&(n.links=(0,x.uniqBy)(i)),(0,x.isNotEmpty)(t)&&(n.buttons=(0,x.uniqBy)(t)),n}t.HealthCheck=oe,r=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,w=new WeakMap,n=new WeakSet,o=function(){return(0,x.filterInPlace)(M(this,r,"f",s),(e=>!e.isPending)),M(this,r,"f",s)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,se.summarizeHealthChecksSync)({errors:M(this,r,"f",l),skipPending:M(this,r,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&_(this,r,!0,"f",u),i.state!==M(this,r,"f",c).last?.state&&M(this,r,"f",c).push({state:i.state,ts:Date.now()}),i},v=function(){return(0,L.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},S=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,F.shortStack)()}),_(this,g,M(this,n,"m",v).call(this),"f");try{if((0,Z.getDevEnvFlag)("PS_SLOMO")&&await(0,k.delay)((0,A.randomInt)(.3*i,.7*i)),this.isSkipped())return M(this,n,"m",b).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const r=await(0,N.thenOrTimeoutError)(e(),i);return M(this,n,"m",b).call(this,{test:r,elapsedMs:Date.now()-t})}catch(e){return M(this,n,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},b=function({test:e,src:t="#toResult",elapsedMs:i}){var n,s;const a=r.normalizeMsg(e.msg),o=e.level??((0,j.toS)(a).toLowerCase().includes("error")?"error":(0,j.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,x.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(_(this,y,(s=M(this,y,"f"),n=s++,s),"f"),n),(0,$.ending)()?u:this.logger.tap({level:re.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const r=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,D.toNotBlank)((0,X.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,Y.isFatalError)(e)&&r.toLowerCase().includes("warn")?"warn":"error"),M(this,n,"m",b).call(this,{test:{msg:r,level:t},src:"#toErrorResult",elapsedMs:i})},s={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new H.CountingSet},f={value:[]},oe.all=(0,E.lazy)((()=>Object.freeze((0,T.sortBy)(M(r,r,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,q.debounce)((()=>{ae().info("onCriticalResult()",r.summary.refresh())}),250),oe.summary=(0,E.lazy)((()=>M(r,r,"m",m).call(r))),oe.resetDebounced=(0,q.debounce)((()=>r.reset()),50)},33866:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(50989);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const n=i(82950),r=i(50268),s=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===r.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===r.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,n.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},42495:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const n=i(40958),r=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,n.compact)([(0,r.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},89035:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const r=n(i(48161)),s=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:n}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(n,2)])]}}function g(){return r.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},82638:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const n=i(40958),r=i(42659),s=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:n}){const r=new Map;for(const e of t??[])r.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),n))r.set(t.id,t);return[...r.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function S(e){const t=(0,n.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),s=i.length,a=i.map((e=>e.id)),c=t.length-s,d=0===s,h=(0,n.uniq)((0,n.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const r=t.filter((e=>e.level===i));if((0,n.isNotEmpty)(r)){const e=t.filter((e=>!r.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+r.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:s,settledCount:c,linkIds:r.map((e=>e.id)),ts:Date.now(),msg:(0,n.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...r,...e].map((e=>e.msg[0])))])},meta:{checks:r.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,r.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},95242:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),v=i(57159),w=i(83278),S=i(95696),b=i(62105),P=i(84258),M=i(38156),_=i(69589),E=i(28874),x=i(47783),T=i(29990),D=i(16047),k=i(42725),C=i(4192),F=i(32876),O=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,x.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class L{constructor(e,t,i){n.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,_.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(n=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,b.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await s(this,n,"m",r).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),n=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:n,best:t.uri}),null==i||null==n)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:r,width:s,height:a,sha:l,mimetype:u}=t;if(null==r||null==s||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,T.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:r,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:n,filesize:i,width:s,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(k.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const n=i.fitSizes.split(","),r=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,T.equivalentFitSizes)(n,r)){const s=(0,T.fitSizes)(e,e.mimetype),a=(0,o.diff)(n,r);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=s.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:s});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=L,r=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),n=await this.priorIfValid_(t,i);if(null!=n)return n;const r=new M.PushProgressObserver({path:e.nativePath,op:"Building previews"},k.ImageSize.sq().length+k.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const s=await this.ap.existingFiles(),a=await(0,O.sharpReadable_)({src:e,minDim:k.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,O.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,D.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,T.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=k.ImageSize.largestSq(),S=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,b=(0,h.pick)(t,"width","height");{let e=o.clone(),t=b;for(const[i,n]of l){const s=Date.now(),a=t,o=this.ap.fileForWidth(n.reducer.name,i.width).wip();e=n.resize(i,e),t=i,n.name===S&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&n.reducer===F.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await n.toJpeg({path:o.nativePath,sh:e,outputSize:i}),r.onProgress(),this.logger.debug("resize("+n.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-s)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:b,bestFitNameForSq:S}),g=o,p=b):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:S});let e=!1;for(const t of k.ImageSize.sq()){const i=Date.now(),n=p,s=t.outputSize(p??b);if(null==s){this.logger.debug("skipping square output for "+t.max);continue}e||(s.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:s});const a=this.ap.fileForWidth(t.reducer.name,s.width).wip();t.resize(s,g),p=s,await t.toJpeg({path:a.nativePath,sh:g,outputSize:s}),r.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(n)+" -> "+(0,u.fmtDim)(s)+" in "+(Date.now()-i)+" ms")}}try{await(0,C.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(s.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const n=i(75761),r=i(33374),s=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,n){return`Download ${t} ${e.ext} ${i} (${(0,r.fmtDim)(n)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),n=(0,o.toInt)(i[0]),r=s.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(n)?{file:t,assetId:n,reducer:r,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:n,reducer:r,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,r.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,r.fmtDim)(o)} ${t.file.ext})`,href:(0,n.assetImgLink)({assetId:i,reducer:s.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),v=i(70417),w=i(35721);t.AssetPreviews=class{constructor(e,t){n.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),r=(0,p.splitEvery)(i,3);this.basename=r.pop()+"-",this.parent=e.join(...r)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:s(this,n,"m",r).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",n=t?.[i];if(!(0,o.isEmpty)(n))return n;const r=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=r,await this.writeInfo(t)),r}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},n=new WeakSet,r=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(50989);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},33106:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const r=n(i(9288)),s=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(32);for(let e=0;e<32;e++){t[e]=new Array(32);for(let i=0;i<32;i++)t[e][i]=Math.cos((2*e+1)/64*i*Math.PI)}return t}();function c(e){const t=new Array(o);for(let i=0;ir?1:0);return s}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,s.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const n=i(40958),r=i(33374),s=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,n.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,n=Math.round(Math.sqrt(t*i));return{width:n,height:Math.round(n/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const n=u(e,i);return null==n?[]:a.Rotations.filter((e=>u(c(t,e),i)===n))}},89782:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const n=i(19851),r=i(31586),s=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,n.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const n=i(40958),r=i(33374),s=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),n=[];let l=(0,s.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,r.dmegapixels)(a)-(0,r.dmegapixels)(l)>2.5)&&(l=a,n.push([a,s])))}return n},t.equivalentFitSizes=function(e,t){return(0,n.includesAll)((0,n.compactBlanks)(e).map(l),(0,n.compactBlanks)(t).map(l))}},277:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const n=i(22573),r=i(41400),s=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,n.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,n.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,n.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,n.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,n.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const n=i(19851),r=i(22573),s=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,n.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,n.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const n=i(22573),r=i(54993),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,n.blank)(e)&&s.test((0,r.toS)(e))}},13940:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(51455),r=i(19851),s=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const a=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const r=n(i(9288)),s=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),v=i(88561),w=i(95696),S=i(17217),b=i(50213),P=i(23624),M=i(28874),_=i(12089),E=i(16170),x=i(1078),T=i(33106),D=i(86580),k=i(78011),C=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,s.lazy)((()=>(0,b.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,S.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const O=(0,s.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=w.PosixFile.for(e),i=await(0,x.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const n=(0,D.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),s=await(0,C.sharpReadable_)({src:t,minDim:n});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const n=(0,b.mkLogger)("ImageHash("+e+")");if(null==t)return n.throw("Cannot build readable stream");const s=(0,D.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,E.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:r.default.fit.outside,...s,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,r.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,r.default)(o,{raw:{...l,channels:3}}),v=await(p?k.meanDiffHash:k.meanDiffHashCIELAB)(y()),w=await(p?T.dctHash:T.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,E.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:s,sizeInfo:i})))}function L(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:O,impl:I}),t._imageHash_=I,t.isImageHash=L,t.toImageHash=function(e){if(null!=e){if(L(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(L(t))return t}}},t.HashDim=8},42725:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return s(this,n,"f",r).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return s(this,n,"f",r).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...s(this,n,"f",r)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},s(n,n,"f",r).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,n=m,r={value:[]},m.UHD8k=new n("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new n("uhd5k",5120,2880,h.Fit,!1),m.UHD=new n("uhd4k",4096,2160,h.Fit),m.QHD=new n("qhd",3120,1440,h.Fit),m.FHD=new n("fhd",1920,1080,h.Fit),m.HD=new n("hd",1280,720,h.Fit),m.WVGA=new n("wvga",720,480,h.Fit),m.QVGA=new n("qvga",320,240,h.Fit),m.QQVGA=new n("qqvga",160,120,h.Fit),m.S480=new n("s480",480,480,h.Square),m.S240=new n("s240",240,240,h.Square),m.S120=new n("s120",120,120,h.Square),m.S60=new n("s60",60,60,h.Square)},4192:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const n=i(19851),r=i(40958),s=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,r.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,s.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),n=i?.capturedAt;null!=n&&(delete i.capturedAt,(0,s.assignFields)(i,n.asExifTag()));const r=i?.exposureSettings;null!=r&&(delete i.exposureSettings,i.FocalLength=r.focalLength,i.FNumber=r.aperture,i.ExposureTime=r.shutterSpeed,i.ISO=r.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,s.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},78011:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const r=n(i(9288)),s=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,n)=>t>=(0===n?e[i]:n%i==0?e[n-i]:e[n-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer(),n=(0,o.rgb2labArray)(i);return{meanHash:(0,s.flatten)(n.map(c)),diffHash:(0,s.flatten)(n.map(d))}}},52121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const n=i(19851),r=i(78923),s=i(95696),a=i(50213),o=i(28874),l=i(12089),u=i(16170),c=i(13940),d=i(4192),h=i(5733),f=i(50961),m=(0,n.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=s.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,r.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},48604:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const n=i(19851),r=i(55835),s=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,n.lazy)((()=>((0,s.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,r.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const n=i(40958),r=i(33374),s=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const n=Math.abs(e-t);return n>i?void 0:n}))??e))}function c(e,i,n=t.RatioEpsilon){return(0,a.lt)((0,s.absdiff)(u(e),u(i)),n)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const n=Math.abs(t.i-e);return n[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},34943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const n=i(19851),r=i(31586),s=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,n.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,n.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,n,s,a]=e.split("\t"),o=(0,r.toGt0)(s),l=(0,r.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:n,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const n=i(19851),r=i(33374),s=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,n.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,n){const r=(0,d.lteBoth)(e,n)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:r,meta:{max:e,input:(0,l.pick)(n,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,r.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,s.fitInside)(i,e);t().trace(`reduce(): input ${(0,r.fmtDim)(i)} is too small for ${(0,r.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=n(i(9288)),s=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,s.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,s.lazy)((()=>{r.default.simd(l.Settings.enableSIMD.valueOrDefault),r.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),r.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(50989);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const r=i(77988),s=n(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),v=i(56519),w=i(56038),S=i(57159),b=i(95696),P=i(17217),M=i(28874),_=i(47783),E=i(16170),x=i(95141),T=i(54979),D=i(1078),k=i(63870),C=i(86580),F=i(277),O=i(16047),I=i(13940),L=i(5733),A=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await j(e,t))?.nativePath}async function z(e,t,i,n,a){const o=t?.[i];if(!(o instanceof r.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,k.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=z,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,s.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const n=N().addParameterContext(e.nativePath);(0,L.setupSharp)();const s=await(0,T.readMimeType)(e);if((0,u.blank)(s))return n.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,D.extractSizeInfoFromFile)(e);if(null==a)return void n.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,E.isVideoMimeType)(s),b=(0,E.isLibrawMimeType)(s),P=a.dimensions,k=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==k?.width||null==k?.height)return n.throw(e+" is not supported (missing dimensions)",{dim:k,doNotSend:!0,mimetype:s,isRaw:b,isVideo:g});const I=(0,C.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),j=(0,E.isSharpMimeType)(s)&&null==t,V=(0,x.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||j||V)n.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:j,isMirrorOrientation:V});else{const i=!1,s=await(0,_.readRawTags)(e,i);if(null==s)n.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=k.width*k.height*.2,u=k.width*k.height*.05,d=(0,l.sortBy)(i.filter((e=>s[e]instanceof r.BinaryField)),(e=>{const t=s[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){n.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>z(e,s,t,k,I)))}}}(0,E.isSharpMimeType)(s)&&f("sharp",(async()=>({file:e}))),(0,O.isHeifMimeType)(s)&&await(0,F.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,F.heif2img)(e),(e=>({file:e}))))),b&&f("raw2tiff",(()=>(0,v.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,A.isVideoSupported)())try{return await(0,v.thenMap)((0,A.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new S.WrappedError("Failed to extract video frame for "+e,t)}else n.warn("video file, but video support is missing",{src:e.nativePath,mimetype:s,minDim:t})}));const W=[];for(const i of d)try{const r=await(0,w.time)("img.read."+i.desc,i);if(null!=r)return n.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:r.file?.nativePath}),{desc:i.desc,rot:m,mimetype:s,...r};n.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){n.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new S.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=j},181:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const r=n(i(9288)),s=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),v=i(54979),w=i(63870),S=i(5733),b=i(50961),P=i(66106),M=i(51210),_=(0,s.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),n=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(n)&&_().throw(n,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const E=(0,s.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return E().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:E,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,b.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,r.default)(i.file.nativePath,{failOn:t});if((0,S.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,r.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const n=i(19851),r=i(40958),s=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const n=i(19851),r=i(40958),s=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),v=i(56038),w=i(31562),S=i(98314),b=i(34102),P=i(88561),M=i(95696),_=i(17217),E=i(74128),x=i(31843),T=i(70417),D=i(33847),k=i(28874),C=i(94678),F=i(43207),O=i(47783),I=i(16170),L=i(95141),A=i(1078),R=i(63870),N=i(89782),B=i(13940),z=i(34592),j=(0,n.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,z.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,n.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return j().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,x.lerp2d)(e,{x:76800,y:k.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:k.Settings.transcodeBitrateUHD.valueOrDefault}),2);const H=(0,n.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?M.PosixFile.for(await(0,t._extractVideoFrame_)((0,_.toNativePath_)(e))):void 0}async function q(e,t){const i=V("extractVideoFrame",e),n=M.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,z.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,B.cachedImageFile_)(n,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const o=await n.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,O.readRawTags)(n,!1);if(null==l)return i.throw("no tags");const u=(0,L.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,A.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),h=null==d?void 0:await(0,N.dimensions)(r);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:h}),r.nativePath;const f=(0,F.extractDurationSec)(l),m=Math.min(f??0,k.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await r.applyIfEmpty_({fn_:async e=>{const t={src:n,dest:e,startAtSec:m,...c};await(0,z.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,O.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),r.nativePath}async function G(){return k.Settings.transcodeVideos.valueOrDefault&&await(0,z.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,O.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const n=i.MIMEType;if(!(0,I.isVideoMimeType)(n))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:n}});const s=(0,F.extractDurationSec)(i);if(!(0,c.gt)(s,k.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const a=(0,r.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeMimeTypes.values,n);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:n,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:H,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,n){if(!await G())return;const s=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,O.readTags)(e),h=(0,A.extractSizeInfoFromTags)(d),m=(0,F.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===n?.force)await i.unlink();else if(await async function(e,t){const i=await(0,O.readRawTags)(t),n=await(0,O.readRawTags)(e),r=(0,F.extractDurationSec)(n),s=(0,F.extractDurationSec)(i);return j().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,s,1.5),meta:{srcDurationSec:r,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const n=V("extractMaxBitrate",e),r=k.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,r))return n.throw("invalid width: "+s,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,r))return n.throw("invalid height: "+a,{ignorable:!0});const o=(0,C.extractBitrateKbps)(i)??k.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:s,height:a,videoBitrateKbps:l};return n.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,v.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:n.halt,...g},m=k.Settings.transcodeMaxDim.valueOrDefault,p=(0,T.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,z.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,r.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,E.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-s})}catch(t){throw(0,E.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,S.errorToS)(t),elapsedMs:Date.now()-s}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await U(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,z.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const n=i(40958),r=i(22573),s=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),v=i(84258),w=i(28874),S=i(76280),b=i(63870),P=i(19769),M=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function _(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:w.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=_;const E=/ffmpeg version n?(?\S+)/i,x=(0,u.lazy)((async()=>{const e=await _();if(null==e)return void M().info("failed to find ffmpeg in $PATH",{ffmpegPath:w.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,b.commandTimeoutMs)(),ignoreStderr:!0}),i=E.exec(t.result)?.[1];return M().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function T(){x.unset(),t.ffmpegVersionDescription.unset()}function D(e){const t=e?.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function k(e){const t=[...w.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(w.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),n=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+n),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=w.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(x(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",T),(0,g.ee)().on("clearToolCache",T)})),t.ffmpegVersion_=async function(){return await x.prior()??x.refresh()},t.isFFmpegSupported=async function(){return null!=await x()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,n.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=k,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,n.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...k(t),...F(t),...D(t),"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){M().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,v.unlink)(t.dest,"debug");const n=(0,p.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(n))return M().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return M().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await _(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const n=i(19851),r=i(42659),s=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,n.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const n=await(0,c.jpegtranNativePath_)();if(!(0,s.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(n,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:r.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:r.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const n=i(19851),r=i(40958),s=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),v=i(89782),w=i(13940),S=i(42725),b=i(19769),P=(0,n.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,w.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>T(e,t)})};const M=["-T"],_=["-Z","-"],E=["-o","1"],x=["-t","0","-j"];async function T(e,t){const i=await(0,v.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const n=S.ImageSize.largestFit().outputSize(i),u=[];null!=n&&4*(0,s.dmegapixels)(n)<(0,s.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[...M,..._,...E,...u,...x,...p.Settings.dcrawEmuArgs.values,e.nativePath],w={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:w});const T=(0,c.execFile)(g,y,void 0,w),D=[];function k(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,b.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const n=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});D.push(n)}}if(T.on("error",k),T.stderr.on("data",k),await t.writeStream_(T.stdout),(0,r.isNotEmpty)(D))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:D,path:e.nativePath});(0,c.endProcess)(T)}t.dcraw_emu_=T},36192:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const n=i(19851),r=i(84777),s=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,n.lazy)((async()=>a.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},49794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const n=i(57975),r=i(19851),s=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,n.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:n})}}},32105:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(19851),r=i(23560),s=i(66184),a=i(72210);class o{log(e,t,i,n){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,n.lazy)((()=>new o))},14593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(57975),r=i(22573),s=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,r.toNotBlank)(e)??(0,s.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[n.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const n=i(50213),r=i(43705);t.currentFileLogger=function(){return(0,n.rootLoggers)().find((e=>e instanceof r.LogWriter))}},28981:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(19851),r=i(51879);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},31256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,n.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}}},51576:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),S=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),n.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,n,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const a=this.socket;null==a?r(this,n,"f").call(this):a.write(this.logFormatter.format(e,t,i,s)+b)}catch(n){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:n})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}n=new WeakMap},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const n=i(76760),r=i(42659),s=i(28874);t.datedLogDir=function(e,t){return(0,n.join)(e??s.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},4904:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(76790),r=i(31586),s=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(19851),r=i(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){n.add(this),this.setting=e,this.silent=!1,r.set(this,[]),s.set(this,(0,l.lazy)((()=>{o(this,r,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,r,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,s,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,n,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,n,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap,s=new WeakMap,n=new WeakSet,a=function(e){if(null==e||0===o(this,r,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,r,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(31586),r=i(50989),s=i(28874);t.LogLevels=(0,r.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,n.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const n=i(40958),r=i(68708),s=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,n=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,n).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-n).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(o));return(0,n.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},24068:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const n=i(73024),r=i(76760),s=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),S=i(38836),b=i(99331),P=i(42638),M=i(76596),_=i(98314),E=i(89968),x=i(29882),T=i(28874),D=i(28981),k=i(20839),C=i(21727),F=i(66184),O=i(57902),I=i(72210),L=i(98192);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class R extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,T.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,x.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(O.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,n.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,_.errorToS)(t))))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,x.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,_.errorToS)(e))))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const n=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(n,i))return;await(0,f.thenMap)((0,L.readLogEntries)(e,{start:n,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(92322),r=i(82328),s=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),S=i(23560),b=i(81168),P=i(78406),M=i(25764),_=i(20197),E=i(14977),x=i(36868),T=i(28874),D=i(32105),k=i(20839),C=i(21727),F=i(66184),O=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,n){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger,unref:!0,onEnd:()=>c(this,r,"f").call(this)}),n.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,n,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:F.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,n,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,n);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=n&&(r.meta=(0,O.prepMeta)(n)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,r=new WeakMap,n=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,n,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,n,"m",a).call(this,e,t),c(this,n,"m",u).call(this))},l=async function(){await c(this,n,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,n,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,x.endStream)(e.stream),T.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,n,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(57975),r=i(40958),s=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},98192:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const n=i(22573),r=i(84542),s=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,n.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),n=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,r.splitLines)(o)){const t=l(e);null!=t&&n.push({...t,from:i})}return n},t.chunkToLogEntry=l},22662:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const n=i(19851),r=i(76790),s=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,n.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,n.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const n=i(76760),r=i(41400),s=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),S=i(24068),b=i(43705),P=i(51879);function M(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),_();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,n.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new b.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,s.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&S.LogTail.instance()}function _(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=M,t.setupLogFormatter=_,(0,r.later)((()=>{h.Settings.logStdout.watchLater(M),h.Settings.logDir.watchLater(M),h.Settings.tailLogs.watchLater(M),h.Settings.logColor.watchLater(_),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},82647:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p69(){return s(this,n,"m",r).call(this,.5)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,r=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(40958),r=i(55835),s=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;ea?(s+=1,i[t]=a):n[t]=a}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},44983:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const n=i(76790),r=i(93973);t.kmeans=function(e,t,i){const s=r(e,t,i);return{...s,centroids:(0,n.sortBy)(s.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(76790);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,a]=(0,n.sortBy)(i,(e=>e.x)),o=a.x-s.x,l=(e-s.x)/o;return r(s.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const n=i(40958),r=i(31586),s=i(48884),a=i(82647),o=i(70417);function l(e,t,i,n){const r=Math.floor(Math.max(0,t.row)),s=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=r;t(0,r.mapFinite)(e[t],(e=>s+=e*e)))),Math.sqrt(s)}function c(e,t,i,n){const s=new a.Average;return l(t,i,n,(t=>(0,r.mapFinite)(e[t],(e=>s.push(e))))),s.stdDev}function d(e,t,i,n){const s=[];return l(t,i,n,(t=>(0,r.mapFinite)(e[t],(e=>s.push(e))))),(0,o.mode)(s)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const r=Math.max(0,t.row),s=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,n.range)(r,s,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,n=t.row,r=[u(e,t,{col:i/2,row:0},{col:i,row:n/2}),u(e,t,{col:0,row:0},{col:i/2,row:n/2}),u(e,t,{col:0,row:n/2},{col:i/2,row:n}),u(e,t,{col:i/2,row:n/2},{col:i,row:n})];return(0,s.leastIndex)(r)},t.leastVariantQuarter=function(e,t){const i=t.col,n=t.row;return(0,s.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:n/2}),c(e,t,{col:0,row:0},{col:i/2,row:n/2}),c(e,t,{col:0,row:n/2},{col:i/2,row:n}),c(e,t,{col:i/2,row:n/2},{col:i,row:n})])},t.greatestHalf=function(e,t){const i=t.col,n=t.row,r=[d(e,t,{col:0,row:0},{col:i,row:n/2}),d(e,t,{col:0,row:0},{col:i/2,row:n}),d(e,t,{col:0,row:n/2},{col:i,row:n}),d(e,t,{col:i/2,row:0},{col:i,row:n})];return(0,s.greatestIndex)(r)},t.submatrixCollect=function(e,t,i){const n=[];return l(e,t,i,(e=>n.push(e))),n},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,s.concat)(...(0,n.stepRange)(0,t.row,u,(i=>(0,n.stepRange)(0,t.col,o,(n=>(c.clear(),l(t,{col:n,row:i},{col:n+o,row:i+u},(t=>(0,r.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},55222:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(77598),r=i(22573),s=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const n=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,n.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const n=i(31586),r=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,n.toInt)(e)]??(0,r.toS)(e)}},17921:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(77598),r=i(65713);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),a(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+a*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const n=i(38522),r=i(22573),s=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,n.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,n.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,r.mapNotBlank)(e,(e=>(0,r.mapNotBlank)(t,(t=>(0,s.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},49076:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(48161)),s=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},96128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(40610),r=i(19851),s=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),S=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==S.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=b.exec(e)}function M(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=M,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=M(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const _=(0,r.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=M(e)?n.promises.reverse(e):n.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(22573),r=i(42659),s=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},78330:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const n=i(40958),r=i(22573),s=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,s.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,n.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(73024),r=i(38639),s=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,s.lazy)((()=>o.isLinux&&((0,r.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(76760),r=i(19851),s=i(54993);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const n=i(45599),r=i(50213),s=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,n.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,n.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(48161)),s=n(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,o.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(s.default.env.APPIMAGE)||(0,a.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(73024)),s=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,s.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,s.lazy)((()=>{try{return a.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const n=i(22573),r=i(51926),s=i(83556);t.negateFilterName=function(e){if((0,n.blank)(e))return;const t=/\s/.test(e)?e:(0,s.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,r.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const n=i(19851),r=i(40958),s=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,n.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,s.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],n=[],r=[];for(const o of t)for(const[t,l]of(0,s.entries)(o)){const s=await l(e);!0===s?i.push(t):!1===s||(0,a.isString)(s)?n.push(t):r.push(t)}return{accepted:i,rejected:n,notApplicable:r}}static async whyRejected(e,...t){for(const i of t)for(const[t,n]of(0,s.entries)(i))try{const i=await n(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:n}){const{accepted:s,rejected:a}=await c.explain(e,...n);return t.tap({msg:i,result:(0,r.isEmpty)(a),meta:{a:e,accepted:s,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const n=i(68708),r=i(94137);class s{static firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))if(!1===r(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))if(!0===r(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i)){const i=r(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==s.firstFalse(e,...t)}static whyRejected(e,...t){return(0,r.negateFilterName)(s.firstFalse(e,...t))}}t.SyncPredicates=s},45643:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(58587),r=i(59455),s=i(31562);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),S=i(54993),b=i(54557),P=i(19851),M=i(50213),_=i(88158),E=i(409),x=i(78406),T=i(25764),D=i(99331),k=i(56519),C=i(46292),F=i(8769),O=i(83278),I=i(32144),L=i(29882),A=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,M.mkLogger)("proc.Pids"))),z=10*p.secondMs;function j(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,L.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,E.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??A.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,f.isEmpty)(r))return B().info("killOldProcs(): no pidfiles"),[];const s=[],a=[],o=await(0,N.pidInfos)(r);if(null!=o){for(const r of n){const n=await r.readJson();if(null==n){B().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!j(n,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,y.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:n}),a.push(W(l,i,!1)),s.push({...n,...u}))}return a.length>0&&await Promise.allSettled(a),s}(0,F.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,r,"f").delete(l),o(this,r,"f").getOrSet(l,(async()=>{const i=o(this,n,"m",s).call(this,e.pid),r=(0,v.opt)((0,_.Try)((()=>(0,L.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:r,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,r,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,n,"m",s).call(this,e);return(0,k.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new x.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:T.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=H,r=new WeakMap,a=new WeakMap,n=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},H.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new H(O.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return H.instance()?.addPid_(e,t)}},58261:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const r=i(31421),s=i(48161),a=n(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),S=i(56519),b=i(84777),P=i(8103),M=i(45879),_=i(43334),E=i(24399),x=i(45643),T=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function k(e){if(_.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,M.readFileMaybe)("/proc/"+i+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,x.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:N)).filter((e=>D(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=D,t.pidInfo=async function(e){return(0,S.thenMap)(k([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,x.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=k;const C="Get-Process",F="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(E.PowerShell.instance().ended)return R(e);const t=[C,"-Id",O(e),"-ErrorAction SilentlyContinue",F].join(" ");return(0,S.thenMap)(E.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const L={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,L),n=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===a.default.pid))||n.push({pid:a.default.pid,start:new Date(v.StartTs),cmd:"node "+a.default.title}),n}async function N(e){return t=(await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...L,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(_.isLinux)return(0,c.toGt0)((0,r.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){T().warn("clk_tck failed",{error:e})}return 100})),z=(0,g.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),j=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=j.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),n=t?.comm,r=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(n)&&(0,c.gt0)(r)?{pid:i,cmd:n,start:new Date(z()+r/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(40958),r=i(22573),s=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(19851),r=i(42659),s=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new o.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new o.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(98553),r=i(31586),s=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const n=i(31586),r=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,n.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,r.emitProgressEvt)({...this.context,pct:(0,n.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(58587),r=i(19851),s=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),S=i(31562),b=i(84777),P=i(34102),M=i(43334),_=i(28874),E=i(63870),x="{ready}",T=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${x}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:x,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,T),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(50989);t.AggregateTypes=(0,n.strEnum)("union","intersection")},71988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(50989);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(22573),r=i(38639),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(22573),r=i(31586),s=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(22573),r=i(31586),s=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(50989);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const n=i(36507),r=i(22573),s=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,s.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,r.blank)(t)||(0,n.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,r.blank)(t)?void 0:(0,n.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(70488),r=i(91655),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=a;class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(22573),r=i(31586),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const n=i(38639),r=i(68708),s=i(50989),a=i(76740),o=i(28874),l=(0,s.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,r.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,r.pick)(e??{},"retries","halt","path"),...(0,r.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,n.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(22573),r=i(31586),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=a},4175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const n=i(19851),r=i(22573),s=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,n.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){M(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&_()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,r.blank)(m.Settings.assetPathnameFormat.value)&&(0,r.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const S=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],b={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function M(e){for(const t of S)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:b;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function _(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=M,t.disableExternalNetworkRequests=_},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(22573),r=i(53265),s=i(87652);class a extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(22573),r=i(31586),s=i(83179);class a extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(22573),r=i(31586),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(83179);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},28283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(51926),r=i(83556);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),S=i(44198),b=i(96706),P=i(34102),M=i(28283),_=i(81075),E=i(98778),x=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){n.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,n,"m",r).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?s(this,n,"m",r).call(this,e??t)+": "+i:null==this.fromEnv(e)?s(this,n,"m",r).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,M.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(M.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return _.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,S.env)(),n=t??this.value;return null!=n&&(i[this.key]=this.toEnv(n)),null==e&&b.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,S.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&b.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],x.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],x.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+n],x.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,E.wrapTomlToLines)({lines:e,wrap:x.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,E.wrapTomlToLines)({lines:e,wrap:x.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,E.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},n=new WeakSet,r=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(50989);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(58587),r=i(51168),s=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),S=i(7282),b=i(12801),P=i(4328),M=i(70488),_=i(84248),E=i(5531),x=i(99315),T=i(34365),D=i(34580),k=i(96706),C=i(50274),F=i(33866),O=i(52086),I=i(48584),L=i(45969),A=i(43334),R=i(24540),N=i(70379),B=i(71300),z=i(33209),j=i(48987),V=i(68268),W=i(61208),H=i(99023),U=i(30577),q=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Z=i(71988),X=i(38483),Y=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),ne=i(55948),re=i(57039),se=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new X.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new X.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new X.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new re.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new re.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new re.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new X.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new re.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new re.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>q.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:q.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>q.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new re.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new re.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new X.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new X.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,L.isDocker)()}),cspReportOnly:new X.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new X.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new X.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),minDelayBetweenSpawnMs:new re.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,M.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new re.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new re.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new re.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new re.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new re.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new X.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:E.CheckpointTypes,defaultValue:E.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:x.RepairModes,defaultValue:x.RepairModes.dump}),maxBusyDbMs:new re.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new re.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new X.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new X.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,L.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:F.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new X.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new X.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new X.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:U.UpdateChannels}),autoUpdateCheck:new X.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new X.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new X.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new X.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new X.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new X.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new X.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new X.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":r.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new X.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new X.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ne.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new X.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new X.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:O.CropStrategies.attention,strEnum:O.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new X.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new X.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Z.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new X.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>z.DefaultIncludedPreviewTags}),disableAllFilters:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new X.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>j.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new re.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new X.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:H.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,L.isDocker)()}),tagDisplayNameFSLabels:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new X.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new X.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function be(e){const i=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,L.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,a.lazy)((()=>be((0,k.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const Me=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Me().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(19851),r=i(31586),s=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,n.lazy)((()=>{w.Settings.configDir.opts.defaultValue=o.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,r.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),S=i(81168),b=i(83556),P=i(87290),M=i(98314),_=i(34102),E=i(83278),x=i(95696),T=i(60865),D=i(4175),k=i(83179),C=i(81075),F=i(28874),O=i(41692),I=i(84438),L=i(32707),A=i(6707),R=i(98778),N=i(55018),B=i(10357),z=(0,n.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function j(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return Y(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,A.readTomlFile_)((0,L.systemSettingsFile)()))?.[F.Settings.libraryDir.name])}catch{return}}function H(e){return(0,A.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function U(){return H((0,L.systemSettingsFile)())}function q(e){return H(j(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=j(e);return z().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:F.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void z().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const n=await e.clear().isNonEmpty(),r=n?e.wip():e;if(await async function(e,i){const n=[(0,g.padding)("#",80)];n.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),n.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),n.push("","");let r="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,n.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),n.push(...e.toTomlLines()),n.push("","")}await e.writeText_("\n"+n.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(r,i),z().info("writeToml(): wrote settings",{dest:r,file:e,nonDefaults:(0,k.settingsToObj)(i),wip:n}),n){const t=await(0,A.readTomlFile_)(r),i=await(0,A.readTomlFile_)(e);(0,u.eql)(t,i)?(z().info("Equivalent contents",{dest:r,file:e,a:t,b:i}),await r.unlink()):(z().info("Archiving prior, different contents",{dest:r,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await r.unwip_())}}async function K(e=(0,L.systemSettingsFile)()){const t=x.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,F.persistedSystemSettings)()),t}function Z(e){return Y(j(e))}async function X(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,F.Settings.libraryDir.value));const i=j(e);return z().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,F.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Y(e){if(null==e)return[];const t=z().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,r.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,M.errorToS)(e)),[]}}async function Q(e){const t=z().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const n=await(0,A.readTomlFile_)(e);if(null==n)return{settings:[],warnings:["No settings found"]};const s=[],a=(0,r.compact)((0,p.entries)(n).map((([e,t])=>{if("version"===e)return;const i=(0,F.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,F.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;s.push(e)}})));return t.info("loaded",{settings:(0,k.settingsToObj)(a),warnings:(0,r.toNotEmpty)(s)}),await(0,D.handleDeprecatedSettings)(),(0,D.handleMetaSettings)(a),{settings:a,warnings:s}}t.librarySettingsFile=j,t.readSettings=(0,n.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return F.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await U()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await q()&&await X()},t.libraryHasSettings=(0,n.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{z().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",G),(0,_.ee)().on("settingsChanged",G),F.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,n.lazy)((()=>(0,T.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(x.PosixFile.for(e),(0,F.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=X,t._readSettings=Y,t.importFileSettings_=Q;const ee=(0,n.lazy)((()=>new Set([F.Settings.noNetwork,F.Settings.httpPort,F.Settings.license,F.Settings.logStdout,F.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(F.Settings))ee().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),F.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(x.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(x.PosixFile.forMaybe(j())?.unlink("trace")),(0,_.ee)().emit("clearCache"),O.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${(0,T.baseVersion)()}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let n="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,r.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,r.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(76760),r=i(40958),s=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}toNotEmpty(){return(0,r.toNotEmpty)((0,r.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(83179);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},72564:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(40958),r=i(98553),s=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,a.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(22573),r=i(81168),s=i(83179);class a extends s.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(76760),r=i(55835),s=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(50989);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},6707:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(90858),r=i(44652),s=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(22573),r=i(96249),s=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,o.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const n=i(98553);t.valueToS=function(e){return(0,n.stringify)(e,void 0,2)}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const n=i(54993),r=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,n.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(4001),r=i(81168);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const n=i(77988),r=i(19851),s=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),v=i(81168),w=i(76596),S=i(79842),b=i(66649),P=i(21330),M=i(98725),_=i(928),E=i(54261),x=i(89724),T=i(17415),D=i(88600),k=i(51275),C=i(29882),F=i(17217),O=i(68284),I=i(57902),L=i(28874),A=i(65162),R=i(71300),N=i(14036),B=i(61424),z=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,S.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class H{static fromAssetFile(e){return(0,d.map)((0,x.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>H.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof H?e:W(e)?new H(e):void 0}constructor(e){var t;this.nativePath=(0,F.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,x.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,S.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(L.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,O.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:H.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,M.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,T.fmtOffsetMinutes)});return null==t?void 0:new H({...e,date:t})}spread(e){return new H({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,T.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,x.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,w.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,E.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,_.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,n.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,T.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?L.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,S.datedToStartDateTime)(this.date)??(0,S.datedToDateTime)(this.date);if(null!=i)return{start:(0,x.datedToLocal)(i.minus(t)),end:(0,x.datedToLocal)(i.plus(t))};z().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:L.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),n=Math.max(t,e.fuzzyPrecisionMs());return z().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,S.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:n}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:n}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>H.for(e))));for(const n of t){let t=e[n],r=n;if((0,D.isValidDate)(t)){if((0,T.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||R.OverrideUTCZoneTags.includes(r))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,v.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,x.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,S.datedToPrecisionMs)(t),rawValue:e[n]?.rawValue})}}const n=(0,p.leastBy)(i,(e=>(0,S.datedToStartTs)(e.date)));if(null==n)return;const r=i.filter((e=>(0,u.eql)(e.date,n.date)||e.precisionMs<=n.precisionMs&&(0,S.datedOverlap)({a:e.date,b:n.date,aPrecisionMs:e.precisionMs,bPrecisionMs:n.precisionMs}))),a=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return z().debug("capturedAtFromTags()",{least:n,overlapsWithLeast:r,earliest:a}),a}function q(e,t){if(L.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)])){const e=(0,M.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,S.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(L.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,M.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(L.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=H,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const n=await e.mtimeMs();function r(t,i){return W(i)?H.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?H.for({nativePath:e.nativePath,date:i.date,local:(0,x.datedToLocal)(i.date),src:(0,v.uniqPath)([t,i.src]),mtime:n,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!L.Settings.usePathsToInferDates.valueOrDefault||!L.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:L.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=r("tags",U(t,L.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,L.Settings.capturedAtTagsFallback.values))??(s?void 0:r("stat+bname",await(0,B.extractStatBname)(e)))??(s?void 0:r("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(s?void 0:r("bname",q(e,t)))??(s?void 0:r("path",G(e)))??(L.Settings.useStatToInferDates.valueOrDefault?r("stat",await $(e)):void 0);return z().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,L.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(50989);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const n=i(31586),r=i(97352),s=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,n.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(77988),s=n(i(76760)),a=n(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),v=i(12168),w=i(56038),S=i(4867),b=i(36557),P=i(98247),M=i(21330),_=i(98725),E=i(23467),x=i(88561),T=i(95696),D=i(17217),k=i(16287),C=i(50213),F=i(17921),O=i(7282),I=i(88158),L=i(23560),A=i(28874),R=i(12089),N=i(45255),B=i(81168),z=i(63870),j=i(15674),V=i(28544),W=i(43207),H=i(72180),U=i(75767),q=i(12788),G=i(80495),$=i(14036),J=i(67083),K=i(3432),Z=i(28630),X=i(15912),Y=i(30748),Q=i(16170),ee=i(95141),te=i(7330),ie=i(54979),ne=i(1078),re=i(61424),se=i(8791),ae=(0,o.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let oe=!1;t.addInstanceIdsToTags=function(e){oe=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ce()};const le=(0,o.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,b.batchClusterOptions)((0,O.isTest)()?8:(0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,j.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function ue(){const e=le();return e.ended?le.refresh():e}function ce(e=!1){return(0,d.map)(le.clear(),(t=>t.end(e)))}t.exiftool=ue,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeoutError)({p:ue().version(),timeoutMs:N.ShortCommandTimeoutMs})},t.exiftoolVersionMaybe=function(){return(0,d.map)(le.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,z.commandTimeoutMs)()})))},t.shutdownExiftool=ce,t.extractBinaryTag=function(e,t,i){return ue().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new x.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new x.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),ie.mimetypeCache.prior()?.clear()};async function de(e){return(0,f.omit)(await ge(e,!1),...t.IgnoredSidecarFields)}function he(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function fe(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function me(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function pe(e,t,i){if((0,B.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return ae().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const n=i??await(0,ie.readMimeType)(e),r=await e.sidecar(),s=(0,Q.isImageMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Q.isVideoMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=s||a||o;return ae().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:n,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function ge(e,i=!0){const n=T.PosixFile.for(e);if(n.isSidecar()&&(i=!1),!await n.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(n.nativePath),void ae().debug("readRawTags("+n+"): invalid file, returning null.");const r=await(0,t._readRawTags)(n.nativePath);if(null==r||!i)return r;ae().trace("readRawTags()",{pf:n,pickedFileTags:(0,f.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await n.jsonSidecars())s.push([e,(0,Z.readJsonSidecar)(e,r.tz)]);for(const e of await n.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Q.normalizeMimetype),...r},o=[];for(const[e,i]of s){if(null==i)continue;const n=await i;if(null==n)continue;const r=(0,f.omit)(n,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(r))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(n.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(r))),(0,f.assignFields)(a,r),ae().debug("readRawTags() sidecar had values",{sidecar:e.base})):ae().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,J.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,ee.orientationToRotation)(a.Rotation),ae().debug("readRawTags() final",{pf:n,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...A.Settings.capturedAtTags.values)}),a}async function ye(e,t){return null==t?void 0:(0,w.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,n=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Q.normalizeMimetype);if((0,u.blank)(n))return void ae().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(ae().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const o=!await(0,re.canInferForDir)(e.parent()),l=await(0,K.maybeInferTimezone)(e,s,o);if(ae().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=s.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values])if(!(0,H.isUtcTagName)(t)){const i=s[t];i instanceof r.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l)}const c=o?(0,Y.extractMakeAndModel)(s):await(0,re.inferMakeAndModel)(e,s);c.Make!==(0,Y.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,Y.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,q.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,X.extractLensMakeModel)(s),h=await(0,V.extractCapturedAt)(e,s,o);if(null==h)return void ae().info("No capturedAt for "+e);!o&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,G.extractExposureSettings)(s),g=await(0,ne.extractSizeInfoFromFile)(e,s);if(null==g)return void ae().info("No size info for "+i);const y={...c,mimetype:n,capturedAt:h,exposureSettings:m,...(0,se.extractTitleDescription)(s),...d,cameraId:(0,U.cameraIdFromTags)(s),imageId:(0,U.imageIdFromTags)(s),lensId:(0,U.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,W.extractDurationSec)(s),tz:s.tz,rating:(0,te.extractRating)(s)};(0,O.isTest)()&&(y.__parsedBy__=a.default.pid);const v={...s,...y};return ae().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void ae().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(de(e),de(t))},t.readTags=he,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=T.PosixFile.for(e);return ye(t,await ge(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await he(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await ue().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void ae().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,ee.extractRotation)(await ge(e,!0))},t.moveOriginal=fe,t.overwriteTags_=async function(e,t){try{await(0,w.time)("exiftool.overwriteTags:"+e,(async()=>{await ue().write(e.nativePath,t,await me(e)),e.clearThisAndParent()}))}catch(i){ae().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await ue().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=me,t.writeTagDest=pe,t.writeTags_=function(e,t,i){return(0,w.time)("exiftool.writeTags:"+e,(async()=>{const n=new h.MultiMap;for(const[r,s]of(0,f.entries)(t)){const t=await pe(e,r,i);n.add(t.nativePath,[r,s])}for(const[t,i]of n.entriesArray()){const n=T.PosixFile.for(t),r=(0,f.fromEntries)(i);ae().info("writeTags()",{src:e,dest:t,t:r}),await ue().write(n.nativePath,r,await me(n)),A.Settings.overwriteOriginal.valueOrDefault||await fe(n),n.clearThisAndParent()}}))},t.readRawTags=ge,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return ae().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);ae().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...A.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,$.isVideoExt)(s.default.extname(e))?[]:["-fast"]],n=await(0,w.time)("exiftool.read()",(()=>ue().read(e,i).catch((t=>{ae().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==n)return;ae().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)}),n.MIMEType=(0,u.mapNotBlank)(n.MIMEType,Q.normalizeMimetype),n.GPSDateTime??(n.GPSDateTime=(0,P.concatDateTime)(n.GPSDateStamp,n.GPSTimeStamp));for(const e of(0,f.keys)(n)){const t=n[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete n[e])}const r=(0,l.compactBlanks)([n.Error,...n.errors??[],n.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(n.problems=r),oe&&(n.__instance=(0,F.safeUUID)()),n}}),t.parseTags=ye},75767:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,n=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[a])||(0,s.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,h.toS)(r)))continue;const o=e[a],u=b(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}n.push([a,(0,l.gt0)(o)?o:u])}var r;return S(n)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:n,parser:r}){const s=r(e[i]),a=r(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==a||(0,l.approximates)(s,a,o)?void 0:"Different "+n+": "+e[i]+" ≠ "+t[i]}function x(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,n.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const n of t)e.set(n,i)}return e})),t.Tag2Synonyms=(0,n.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const n=_(e),s=_(i);if(null==n||null==s||e===i)return;const a=(0,f.intersection)((0,u.keys)(n),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=n[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,r.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:n[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return x({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=x,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const n=i(22573),r=i(54993),s=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,n.blank)(e)||s.test((0,r.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const n=i(19851),r=i(22573),s=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,n.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(50989);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(19851),r=i(40958),s=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,o.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,o.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const n=i(22573),r=i(45599),s=i(68708),a=i(50213),o=(0,r.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,s.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:r}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,n.blank)(e[i])&&!(0,n.blank)(t[r])&&(t[i]=t[r]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,s.pick)(e,"Directory","FileName"));for(const t of(0,s.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const n=i(77988),r=i(19851),s=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),v=i(50213),w=i(81168),S=i(66649),b=i(17415),P=i(29882),M=i(95696),_=i(17217),E=i(28874),x=i(47783);function T(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:n.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=T,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function O(e){if(null==e)return;const t={};for(const[i,n]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=n);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,n){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),a=await(0,x._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...n??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:n,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:n});const h=M.PosixFile.for(e);return await(0,x.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,s.isEmpty)(r))return{};const l=(0,a.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>n.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const n=F(e);(0,o.blank)(n.nativePath)||(0,P.eqlNameWithoutExt)(n.nativePath,i)?u[t]=n:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=O,t.ensureInferredHistoryRecords=async function(e,i,n){const r=T(t.Actions.infer,n),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?O(n):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:s}),I(i,r,s)},t.ensureHistoryRecords=I},3432:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=n(i(53705)),s=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),w=i(14245),S=i(61424),b=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,w.omitInvalidGeolocationTags)(t);{const e=M(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=_(e,t);if(null!=i)return i}if(!i){const t=await(0,S.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function M(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return b().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i);return b().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return b().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function _(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const n of g.Settings.capturedAtTags.values){const r=(0,u.toDated)(t[n]);if(null==r||(0,f.isValidDate)(r))continue;const s=Math.round(15*i.diff(r,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(s),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return b().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+n+")"},meta:{dt:(0,c.datedToISO)(r),rawTzoffsetMinutes:s,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return b().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=M,t.inferTzOffsetMinutesFromFilename=_},28630:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const n=i(77988),r=i(40958),s=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),s=n.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??n.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(50989);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},97573:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const n=i(77988),r=i(66150),s=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,s.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function S(e){return null==e||e instanceof n.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(S)):w(e))}function b(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(b).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=S;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new r.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(b))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function E(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,E);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,E).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=E,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const n=M(e.Categories);null!=n&&t.push(...n)}for(const n of i){const i=(0,c.pluckDeep)(e,n)?.value;(0,o.blank)(i)||(_(i)?t.push(...E(i)):t.push(...Array.isArray(i)?i:S(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,n.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),n=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&n.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&n.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&n.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,r.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&n.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&n.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of n){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,b)}return(0,c.greatestBy)(n,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const n=i(19851),r=i(22573),s=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const n=e.replace(t,i);return n===e?e:h(n,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,n.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const n=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=n)return n[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},16170:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const n=i(22573),r=i(54993),s=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,n.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,n.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(50989);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(50989);t.NameTagOrders=(0,n.strEnum)("western","eastern")},95141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const n=i(21605),r=i(54993),s=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,n.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,n.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,n.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,n.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const n=i(55835),r=i(31586),s=i(28874);function a(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,n.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const n=i(19851),r=i(22573),s=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,n.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(16928),r=i(40958),s=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,n.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,r.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,r.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const n=(0,a.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function r(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=r(e.slice(n.length)),l=r(i.slice(n.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const n=i(19851),r=i(22573),s=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),v=(0,n.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,n.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const n=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,n,await(0,h.rawInfo)(e));const s=b(i,n);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const n=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==n)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:n}});const r=(0,a.maybeDimSwap)(n,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:n,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},61424:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const n=i(77988),r=i(51168),s=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),v=i(79842),w=i(21330),S=i(98725),b=i(51275),P=i(35280),M=i(19748),_=i(88561),E=i(95696),x=i(65238),T=i(17217),D=i(57902),k=i(28874),C=i(80496),F=i(65162),O=i(28544),I=i(47783),L=i(88840),A=i(30748),R=i(16170),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function z(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,x.isSlowDir)(e.nativePath)&&!await(0,x.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function j(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of n){const n=(0,A.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(n.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:n});else if((0,f.definedAndNotEql)(n.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:n});else if(null!=n.Make&&null!=n.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:n,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await z(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await j(t?.younger),n=await j(t?.older);return null==i||null==n?void 0:{before:i,after:n,index:i.index,slots:i.index+n.index+1}}))}t.beforeAfterCapturedAt=W;const H=(0,M.extFilter)(L.ExtTypes.AssetFile);function U(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7,i=!0){if(!await z(e.parent()))return;const n=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(H(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==n)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,o.sortBy)(n,(e=>(0,F.bname)(e))),s=(0,T.findFileIndex)(e,r);if(s<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),q(e,t,!1)):void 0;const l=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[r.slice(s-2*t,s),r.slice(s+1,s+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await z(e.parent()))return;const t=U(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==n.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const n=await e.stat();if(null!=n){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:n[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:n}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:n}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const n=i[e];if(null!=n&&!0===(0,v.datedOverlap)({a:t,b:n}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(n)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const n=i(40958),r=i(76790),s=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,n.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?f((0,n.last)(e)):(0,n.last)(g(e))}function w(e,t){if((0,n.isEmpty)(e)||(0,n.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,n.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,n.uniqBy)((0,l.toA)(e),(e=>(0,n.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,n.compact)(t).map((e=>y(e))));return(0,n.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,r.sortBy)(e.filter(n.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,r.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const n=i(40958),r=i(22573),s=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,n.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const n of i){const i=(0,a.toS)(e[n]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(76760),r=i(57975),s=i(90595),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=r??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),a="psfile"===n&&s.startsWith("//")?s.slice(1):s,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(n,r,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return x(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?x(this,!0):(null==this._formatted&&(this._formatted=x(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function x(e,t){const i=t?_:M;let n="";const{scheme:r,query:s,fragment:o}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,a.mapNotBlank)(s,(e=>n+="?"+e)),o&&(n+="#",n+=t?o:M(o,!1)),n}function T(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+T(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>T(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(19851),r=i(40958),s=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(76760),r=i(22573),s=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(40958),r=i(22573),s=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},12228:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=s(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,o.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?a.join(t,...r):void 0}},85087:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(22573),r=i(42659),s=i(9103),a=i(37628);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},60865:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(37805),r=i(30577);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},76280:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const n=i(38064),r=i(22573),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof n.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,n.satisfies)(e,t,i))return!0;const s=a(e);return null!=s&&(0,n.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof n.SemVer?e:(0,n.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(50989);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(40958),r=i(9595),s=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},1485:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(19851),r=i(22573),s=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),S=i(24541),b=i(60224),P=i(63870),M=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function x(e){return(0,l.map)(E(e),(e=>e+":\\"))}function T(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=x,t.getPsDriveCommand=T,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function O(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=x(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function I(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(x)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(T(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,o.flatten)(t).map(D)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,r.compact)((0,o.flatten)(n).map(O)),l=(0,r.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=O,t.volumeInfoWin=I},68884:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),S=i(16287),b=i(45969),P=i(43334),M=i(69108),_=i(98770),E=i(44224),x=i(63870);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,x.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const T=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?T().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):T().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(T().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,x.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void T().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await D(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))},timeoutMs:(0,x.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,x.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void T().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(19851),r=i(5233),s=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),S=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),o={...r,...s},u=n?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),n=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(57272),r=i(19851),s=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),S=i(8769),b=i(34102),P=i(17217),M=i(16287),_=i(43334),E=i(28874),x=i(8540),T=i(68884),D=i(44224),k=i(24541),C=i(69375),F=i(63870),O=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,F.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function A(){I()}t.localMountpointSetup=(0,n.lazy)((async()=>{E.Settings.libraryDir.watchLater(I),E.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&E.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,F.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux){const i=(0,D.maybeWatchProcMounts)();await(0,T.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,F.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,F.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?k.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return O().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,F.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(O().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,P.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,o.later)((()=>{(0,b.ee)().on("clearCache",(()=>{T.gioVolumes.unset(),I()})),E.Settings.mountpointsTtlMs.watch(L)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>A(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:T.GioCommand,args:T.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(T.gioVolumes.unset(),A()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,n.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,F.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>A(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(19851),r=i(40958),s=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),S=i(68884),b=i(59107),P=i(69375),M=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await T()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,S.isGioSupported)())try{await(0,c.thenMap)((0,S.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){M().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function E(e){return!v.Settings.excludedFilesystemTypes.has(e)}function x(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function T(e=_,t=E,i=x){if(y.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return M().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return M().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void M().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=E,t.readProcMounts=T,t.maybeWatchProcMounts=(0,n.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(_)?new h.FileWatcher(_,{recursive:!1,persistent:!1},(()=>{M().info("detected change in "+_),(0,d.setUnrefTimeout)((()=>b.mountpoints.refresh()),s.secondMs)})):void 0))},24541:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(19851),r=i(42659),s=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(19851),r=i(22573),s=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(22573),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(40958),r=i(22573),s=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await E()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,o.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,u.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,a.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,h.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(42659),r=i(12168),s=i(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},86848:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(76760),r=i(19851),s=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),S=i(28874),b=i(59107),P=i(63870),M=i(68995),_=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),E=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function x(e){return(0,a.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,n.basename)(e.mountpoint)}function T(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=T(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function k(e){if(S.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of S.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),n=await D(i).catch((e=>_().info("Failed to read "+i,{error:e})));if(null!=n)return _().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}const t=(0,n.join)(e.mountpoint,(0,M.volumeUuidSubpath)());if("/"===e.mountpoint)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(S.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(S.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,M.writeVolumeUuid)(e);if(!(0,s.blank)(t))return _().tap({msg:"readVolumeUUID(): wrote new "+(0,M.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return _().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>E.clear())),b.mountpoints.watchLater((()=>E.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(x(e))return;if((0,a.isFalse)(e.ok))return;const t=await E().getOrSetAsync(e.mountpoint,(async()=>k(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>_().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=x,t.toVolumeUUID=T,t.readUuidFile_=D,t.readVolumeUUID=k},7014:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(48161)),s=n(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),S=i(50213),b=i(7282),P=i(23560),M=i(28850),_=i(45255),E=i(81168),x=i(56519),T=i(4867),D=i(49776),k=i(9595),C=i(77740),F=i(44198),O=i(96706),I=i(8769),L=i(57159),A=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),z=i(17217),j=i(16287),V=i(49076),W=i(96128),H=i(45969),U=i(43334),q=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Z=i(27461),X=i(66840),Y=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),ne=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),re=r.default.platform(),se=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,se),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){ne().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),se.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,H.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:n,os:re}))),s=new Map;for(const e of r)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))s.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){ne().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));ne().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,Y.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,q.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==q.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return ne().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function me(e,i){const n=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(n))return;const r=await(0,A.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return ne().trace("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return ne().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function pe(e,t,i){const n=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,W.friendlyname)(e);return(0,x.asyncFind)(n,(async e=>(0,E.equalsIgnoreCase)(s,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,b.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,v.toA)(await(0,Y.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,o.isNotEmpty)(i)?i:e.filter((e=>re===e?.os));return ne().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,T.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return ne().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,T.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return ne().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if((0,b.isTest)()){const e=(0,p.toInt)((0,F.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(ne().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void ne().throw("PS_FAIL_VOLUMES")}const e=await(0,T.thenOrTimeoutError)({p:U.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void ne().warn("df failed");const t=q.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,j.isReadableDirectory)(e.mountpoint))return e;ne().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){ne().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,T.thenOrTimeoutError)({p:U.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(U.isWin?t:U.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return ne().debug("_volumes(): final result",{sorted:n}),n.forEach(ue),await he(n),Object.freeze(n)}}),t.rootPath=(0,a.lazy)((()=>U.isWin?(0,g.opt)((0,O.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(ne().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(76760),r=i(19851),s=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(50989);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},65713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(76760),r=i(19851),s=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(22573),r=i(96249),s=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(48161)),s=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*a.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(48161)),s=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},15674:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(19851),r=i(42659),s=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,n.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),r.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,n.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,n=w();if(1!==n){const e=t;t*=n,g().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,v());return t=(0,a.clamp)(1,r,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(58587),r=i(87997),s=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},91863:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(i(1708)),s=i(98553),a=i(5670),o=i(59880),l=i(19913),u=i(71567),c=i(80061),d=i(17181),h=i(41944),f=i(28874),m=i(7014),p=i(16848);!async function(){r.default.argv.includes("--help")&&(console.log((0,c.cliWrapWithFooter)("This is PhotoStructure's background worker, and is for internal use only")),r.default.exit(0)),(r.default.argv.includes("--version")||r.default.argv.includes("-V"))&&(console.log((0,c.cliWrapVersion)()),r.default.exit(0)),(0,l.setServiceName)(a.ServiceNames.worker),(0,o.setShortProcessNames)(f.Settings.shortProcessNames.valueOrDefault),(0,o.setProcessTitle)(),(0,d.setupLogger)(),r.default.argv.includes("--volumes")&&(console.log((0,s.stringify)(await(0,m.volumes)())),r.default.exit(0)),h.onProgressEvt.setShim((async e=>{(0,u.stdoutWrite)(e,void 0)})),(0,p.handleWorkRequests)()}()},24817:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequest_=t.isWorkRequest=t.mkWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=t.AllWorkerFunctionCandidates=void 0;const n=i(98553),r=i(31586),s=i(68708),a=i(50989),o=i(32639),l=i(13991),u=i(50597),c=i(48368),d=i(52121),h=i(48604),f=i(181),m=i(66106),p=i(47783),g=i(83966);t.AllWorkerFunctionCandidates={_extractVideoFrame_:m._extractVideoFrame_,_readRawTags:p._readRawTags,_readTags:p._readTags,assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkerFunctions={assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkRequestMethods=(0,a.strEnum)(...(0,s.keys)(t.WorkerFunctions));let y=0;t.mkWorkRequest=function(e,t){return{id:++y,fn:e,args:t}},t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,r.isNumber)(e.id)},t.handleWorkRequest_=async function(e){const i=t.WorkerFunctions[e?.fn];if((0,o.isFunction)(i))return i(e?.args);throw new Error("invalid method "+(0,n.stringify)(e))}},16848:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequests=void 0;const r=n(i(1708)),s=i(19851),a=i(50213),o=i(71567),l=i(33456),u=i(22573),c=i(26905),d=i(67478),h=i(54993),f=i(45608),m=i(55534),p=i(8769),g=i(57159),y=i(24817),v=(0,s.lazy)((()=>(0,a.mkLogger)("worker.Worker")));async function w(e){if(e=(0,h.toS)(e),(0,u.blank)(e))return;if(e.trim()===m.ServiceExitCommand)return(0,f.exit)({reason:e+" from stdin",status:0});const t=(0,d.parseJSON)(e);v().trace("onData",{request:t});try{const e=await(0,y.handleWorkRequest_)(t);(0,o.stdoutWrite)({id:t.id,response:e},!0)}catch(e){const i=(0,c.errorToJson)(e);v().warn("failed to process request",{request:t,error:i}),(0,o.stdoutWrite)({id:t.id,error:i},!1)}}t.handleWorkRequests=function(){!0!==r.default.stdin?.readable?(0,f.exit)({reason:"process.stdin is not readable",status:13}):(function(){for(const e of["SIGINT","SIGTERM"])r.default.on(e,(e=>(0,f.exit)({reason:e,status:0})))}(),function(){for(const e of["uncaughtException","uncaughtException","disconnect"])r.default.on(e,(e=>{const t=new g.WrappedError("uncaughtException",{cause:e});return(0,p.onError)(t)?(0,f.exit)({error:t,status:(0,c.errorErrno)(t)??1}):void 0}))}(),(0,f.exitOnStdStream)(),r.default.stdin.pipe(new l.LineReader).on("data",w),v().info("Child process mode: listening on stdin..."))}},83966:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const r=n(i(1708)),s=i(41400),a=i(31586),o=i(7282),l=i(12089),u=i(45608),c=i(57159),d=i(89035);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,s.delay)(e.delay),(0,o.isTest)()&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:r.default.pid,input:e?.input??"(no input)"}}})},40958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(76790),r=i(22573),s=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,o.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(40958),r=i(36783),s=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,o.getOrSet)(i,(0,a.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(32639);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},75761:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const n=i(58939),r=i(40958),s=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const n=(0,c.toS)(e.v);return(0,s.blank)(n)||"1"===n||(i??(i=new URLSearchParams)).append("v",n),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,n.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:r}){return(0,d.assembleFullPath)(`/img/${(0,n.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,r))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,r.compact)([(0,n.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:r,lazyLoad:s,af:l}){if(null==(0,n.id2id)(e))return{src:"/images/clear-64.png"};0===(r=(r??[]).filter(u.gt0)).length&&r.push(320);const d=Math.min(...r),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});s??(s=!0);const S=s&&(0,f.isSafari)((0,h.ua)());S?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=s?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const b=r.map((n=>m(y({assetId:e,params:t,reducer:i,width:n}),n)));return null!=l&&b.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(S?"data-":"")+"srcSet"]=b.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,s.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,n.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:n="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===n?80:"m"===n?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},5233:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(41400),r=i(31586),s=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const n=i(40958),r=i(22573),s=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,r.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,n.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(55835),r=i(42279),s=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!n(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(40958),r=i(22573),s=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),a=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38639),r=i(73872);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function a(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function o(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return a(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r.hasPrior=()=>n,r}},41400:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(42659),r=i(35556),s=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,a.maybeCall)(s,"unref")??s}},33374:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const n=i(31586),r=i(21605),s=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,n.toGt0)(e?.width)??0)*((0,n.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,n.gt0)(e)&&(0,n.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(o(e))},t.pixels=o},50357:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const n=i(12487),r=i(68708),s=i(34666),a=i(32639);function o(e,t){return(0,n.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,r.isObject)(e)||!(0,r.isObject)(t))return!1;for(const i of(0,r.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=d.get(i);if(null!=n)return n(e,t)??null}for(const i of c){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(40958),r=i(22573),s=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(59455);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(40958),r=i(42659),s=i(55835),a=i(31586),o=i(12168),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(40958);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},50268:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const n=i(22573),r=i(38639),s=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,n.blank)(e.id)&&!(0,n.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,n.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&a.RunStates.has(e.state)&&(0,r.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const n=i(50989);t.ReducerNames=(0,n.strEnum)("fit","sq")},73722:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(50989);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,a,o,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let n=0;t.Latch=class{constructor(e=n++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(40958),r=i(50357),s=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,o=await i;if(!(0,r.eql)(s,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},55835:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(42279),r=i(54993);function s(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return o(a(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const n=i(68708);class r extends Error{constructor(e,t){super(e),this.message=e,(0,n.assignFields)(this,t)}}t.MetaError=r},23838:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(40958),r=i(76790),s=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=(0,n.findIndexes)(r,(t=>!e(i,t,r)));if(s.length>0){t=!0;for(const e of s.reverse())r.splice(e,1)}0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const n=i(76790),r=i(22573),s=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,r){return!(null==r||!o(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,r.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return o(e)&&e>0}function S(e){return o(e)&&e>=0}function b(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function M(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function _(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return f(t-n,t+n,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,i){return b(e,(e=>b(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=M,t.toPrecisionMaybe=function(e,t){return d(e,(e=>M(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?P(e/n)*n:P(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=_,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return _(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(40958),r=i(76790),s=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,a]=(0,c.splitFirst)(n,"."),o=b(t,i);null!=o?.value&&r(o.key,(0,s.blank)(a)?o.value:e(o.value,a))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,a]=(0,c.splitFirst)(i,"."),o=b(t,r);if(null==o)return;if((0,s.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,a.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},97790:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},39926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(31586),r=i(54993),s={};function a(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}})},46891:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(22573),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(40958),r=i(54993),s=["number","string","boolean"];function a(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),a=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?o.indexOf(n)-o.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(59455);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},57153:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(50989);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(40958),r=i(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?s(e,t):o(e,t,1,i)[0]}function o(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,a=new Set(n??[]);if(t===e&&0===r&&0===a.size&&1===i)return[e];const o=r-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of o(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let n=e;t.global||(t=new RegExp(t,"g"));let r=null;for(;null!=(r=t.exec(e));)r.index===t.lastIndex&&t.lastIndex++,n=n.slice(0,r.index)+i(r)+n.slice(r.index+r[0].length);return n}},21605:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const n=i(31586);function r(e){if(!(0,n.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,n.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},62220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const n=i(50989);t.RunStates=(0,n.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(50989);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(68708),r=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...s,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,r.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),n=a(t);return null==i||null==n?void 0:i>n?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(40958),r=i(17586),s=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,o.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"…"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const n=i(42659),r=i(68708),s=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,n)=>{let r=!0;const s=setTimeout((()=>{r&&(r=!1,i(a.Timeout))}),t);try{s.unref?.();const t=await e;r&&(r=!1,i(t))}catch(e){r&&(r=!1,n(e))}finally{clearTimeout(s)}}))}async function c(e,t,i=!0){const r=await u(e,t,i);if(r===a.Timeout)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(t)+")");return r}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const n=t-Date.now();return n<=0?a.Timeout:u(e,n,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(n,s)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),n(l))}catch(e){a&&(a=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return c(e,r,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:n=!0}){if(null==e)return(0,s.tot)(i);const r=await u(e,t,n);return r===a.Timeout?(0,s.tot)(i):r}},42279:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(32639);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(40958),r=i(22573),s=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(22573),r=i(30301),s=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),a=d[n];return(0,s.sigFigs)(e/r,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),a=h[n];return(0,s.sigFigs)(e/r,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const n=i(30301),r=i(54993);t.ua=(0,n.lazy)((()=>(0,r.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,n=/\bSafari\b/,r=/\bFirefox\b/,s=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,r)}t.isChrome=l,t.isSafari=function(e){return o(e,n)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,s)},t.isIphone=function(e){return o(e,a)}},58939:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const n=i(55835),r=i(31586);function s(e){const t=e;return(0,r.isNumber)(e)?e:(0,r.isNumber)(t.id)?t.id:(0,r.isNumber)(t.assetId)?t.assetId:(0,r.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=s,t.idEql=function(e,t){return(0,n.map2Or)(s(e),s(t),((e,t)=>e===t),(()=>!1))}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const n=i(41801),r=i(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(40958),r=i(23541),s=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(o))}},54993:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(98553);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},23227:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),i(91863)},90858:e=>{e.exports=require("@iarna/toml")},53705:e=>{e.exports=require("@photostructure/tz-lookup")},58587:e=>{e.exports=require("batch-cluster")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},66150:e=>{e.exports=require("fast-xml-parser")},68817:e=>{e.exports=require("file-type")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},93973:e=>{e.exports=require("ml-kmeans")},4927:e=>{e.exports=require("papaparse")},83058:e=>{e.exports=require("picomatch")},57272:e=>{e.exports=require("plist")},85949:e=>{e.exports=require("process")},90595:e=>{e.exports=require("punycode")},38064:e=>{e.exports=require("semver")},9288:e=>{e.exports=require("sharp")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},40610:e=>{e.exports=require("node:dns")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},77030:e=>{e.exports=require("node:net")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},53916:e=>{e.exports=require("node:path/posix")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")},16928:e=>{e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=23227);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={37975:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const n=i(1708),r=i(22573),s=i(38639);function a(){return(0,s.toNotBoolean)(n.env.PS_LOG_COLOR)??(!(0,r.blank)(n.env.NO_COLOR)||["dumb","unknown"].includes(n.env.TERM))}t.noColor=a;let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const n=i(19851),r=i(7282),s=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,n.lazy)((()=>t.SimpleAppName+((0,r.isProd)()?"":`-${(0,r.nodeEnv)()}`))),t.AppNameVersion=(0,n.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const n=i(40958),r=i(36783),s=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=n.primitiveValueOfOrElse){const r=new Set(t.map(i));return e.filter((e=>r.has(i(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function w(...e){const t=[],i=Math.max(...e.map((e=>e?.length??0)));for(let n=0;ne?.[n])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return M(e,(e=>e.valueOf()))}function P(e,t){return E(e,t,((e,t)=>(0,h.lt)(e,t)))}function M(e,t){return E(e,t,((e,t)=>(0,h.gt)(e,t)))}function _(e,t){return(0,n.isEmpty)(e)?void 0:e[P(e,t)]}function E(e,t,i){return x(e,t,i).index}function x(e,t,i){if((0,n.isEmpty)(e))return{index:-1,value:void 0};let r,s=-1;for(let n=0;ne.slice(i,i+t)))}async function D(e,t){return(0,n.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,o.eql)(e,t)))))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const n=e[i];if(null!=n&&!0===await t(n))return n}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null!=n){const e=await t(n,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,n.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let n=i;n<=e.length-1;n++)if(t(e[n]))return n},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,n.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i(0,o.eql)(e,t)))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,r.copyArrayTo)((0,n.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],n=[];let r=0;for(const s of e)(t(s,r++)?i:n).push(s);return[i,n]},t.isUniq=function(e){return e.every(((t,i)=>e.indexOf(t)===i))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,n.compact)((0,n.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),i=[];return(0,c.times)(t,(t=>e.map((e=>i.push(e?.[t]))))),i},t.unFlatZip=function(e,t){const i=e.length/t;if(i!==Math.round(i))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const n=(0,c.times)(t,(()=>new Array(i)));for(let r=0;re.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=M,t.leastBy=_,t.least=function(e){return _(e,(e=>e))},t.greatestBy=function(e,t){return(0,n.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=x(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(i(s)));return r},t.collectBatchedAsync=async function(e,t,i){const r=[];for(const s of T((0,n.compact)((0,f.toA)(e)),t))r.push(...(0,n.compact)(await i(s)));return r},t.contextFilter=function(e,t){let i;return e.filter(((e,n)=>(0,d.tap)(t(e,n,i),(t=>{t&&(i=e)}))))},t.clusterSome=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.some((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterEvery=function(e,t){const i=[];for(const n of e){const e=i.find((e=>e.every((e=>t(n,e)))));e?e.push(n):i.push([n])}return i},t.clusterAsync=async function(e,t){const i=[];e:for(const n of e){for(const e of i)if(null!=n&&await D(e,(e=>t(n,e)))){e.push(n);continue e}null!=n&&i.push([n])}return i},t.someAsync=async function(e,t){if(null!=e)for(let i=0;i=0&&!0===(0,u.map)(e[n],(e=>i(e,n))))return n}{const n=t+r;if(ne+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,i){return e.lengthi))),e}},36557:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const o=i(77988),l=a(i(1708)),u=i(19851),c=i(42659),d=i(55835),h=i(31586),f=i(85556),m=i(54993),p=i(50213),g=i(79089),y=i(45255),v=i(25764),w=i(38836),S=i(99331),b=i(95937),P=i(98314),M=i(38835),_=i(70025),E=i(8769),x=i(43334),T=i(95402),D=i(28874),k=i(63870);class C extends w.EndableWrapper{constructor(e,t,i=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,n,"m",r).call(this)),i,"worker"===e?(0,k.commandTimeoutMs)():y.ShortCommandTimeoutMs),n.add(this),this.t=t;const a=t;a.on("childStart",(async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,g.renice)(i.pid).catch((e=>this.onError("renice failed",e))),(0,T.addPid)({pid:i.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),a.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),a.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),a.on("fatalError",(e=>{this.onError("on(fatalError)"+M.FatalErrorFlag,e)})),a.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),a.on("noTaskData",((e,i,n)=>{const r=t.options.streamFlushMillis;r{this.logger.error("observeBatchCluster.endError()",e)})),a.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&T.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof o.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,_.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,E.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=C,n=new WeakSet,r=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(x.isWin?3:1)*c.minuteMs,maxTasksPerProcess:D.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:D.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:D.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,p.mkLogger)(t))),spawnTimeoutMillis:(0,k.commandTimeoutMs)(),taskTimeoutMillis:D.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=i(92460),d=i(31586);class h{constructor(e){if(n.add(this),this.maxLength=e,r.set(this,void 0),s.set(this,0),a.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,r,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,n,"m",o).call(this,e,(e=>u(this,r,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,n,"m",o).call(this,e,(e=>u(this,r,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,a,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,r,"f")[t]))}()}push(...e){var t,i;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,r,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,n,"m",o).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,r,"f")[e]}))}unshift(...e){var t,i;for(const c of e.reverse())u(this,s,"f"){u(this,r,"f")[e]=c,l(this,a,e,"f")}));return u(this,s,"f")}shift(){return u(this,n,"m",o).call(this,0,(e=>{var t,i;return l(this,a,(t=u(this,a,"f"),++t),"f"),l(this,s,(i=u(this,s,"f"),--i),"f"),u(this,r,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,n,"m",o).call(this,u(this,s,"f")-1-e,(e=>{const i=u(this,r,"f")[e];u(this,r,"f")[e]=u(this,r,"f")[t],u(this,r,"f")[t]=i}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const n=i(54993),r=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:i}of r)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every(((t,i)=>e[i]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,n.toS)(e)},t.bufferStartsWith=a},9092:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const n=i(94863);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=r},36638:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const n=i(94863);class r{constructor(e=[],t=n.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=r},40583:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const a=i(40958),o=i(23838),l=s(i(68708)),u=i(59455),c=i(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new o.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const i of(0,a.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let n,r=-1;for(const[i,s]of this.m.entries()){const a=(0,c.diceCoeff)(i,e);if(a>t&&a>r){const e=this.getFirst(s);null!=e&&(n=e,r=a)}}return n}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),i=this.m.get(t);if(null!=i){for(const e of i)delete this.obj[e];this.m.delete(t)}return i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const n=i(76790),r=i(31586),s=i(68708),a=i(54993),o=i(82647),l=i(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.m.delete(e):this.m.set(e,i),i}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new o.Average(0);for(const t of this.keys()){if(!(0,r.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,i]of this.m.entries())e[(0,a.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,n.sortBy)([...this.entries()],(([t,i])=>[-i,(0,r.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new o.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,i]of(0,n.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,n.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let i=0;for(const[n,r]of this.m.entries()){const s=e(n);t.fill(s,i,i+r),i+=r}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const n=i(19851),r=i(72993),s=i(45969),a=i(43334);t.EditionType=(0,n.lazy)((()=>a.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,n.lazy)((()=>r.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const n=i(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),i=t-this.ts;this.ts=t,(0,n.map)(this.listener,(t=>t(e,i))),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}},t.elapsed=function(e){const t=Date.now(),i=e();return{elapsedMs:Date.now()-t,result:i}},t.thenElapsed=async function(e){const t=Date.now(),i=await e;return{elapsedMs:Date.now()-t,result:i}}},23467:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const n=i(50357),r=i(55835),s=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,n.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,n.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,r.map2Or)(await e,await t,n.eql,(()=>!1))},t.eqlPicked=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,n.eql)((0,s.omit)(e,...i),(0,s.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,r.map2Or)(await e,await t,((e,t)=>(0,n.eql)((0,s.pick)(e,...i),(0,s.pick)(t,...i))),(()=>!1))}},19935:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const n=i(31658),r=i(19851),s=i(95696);t.examples=(0,r.lazy)((()=>s.PosixFile.for((0,n.examplesNativePath_)())))},31658:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const n=i(19851),r=i(65843),s=i(29882);t.examplesNativePath_=(0,n.lazy)((()=>{const e=(0,r.ancestorWithChildren)(__dirname,["examples"]);if(null==e)throw new Error("Couldn't find the examples directory");return(0,s.joinNativePath)([e,"examples"])}))},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const n=i(57975),r=i(40958),s=i(55835),a=i(31586),o=i(54993),l=i(77377),u=i(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,a.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,a.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,r.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const i of this.expireListeners)i(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[n.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const i of this.expireListeners)i(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,r.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const i of this.expireListeners)i(e,t)}const i=this.priorCache[e];if(void 0!==i&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,i)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const i=this.currentCache[t]??this.priorCache[t];null!=i&&e(t,i)}}deleteIf(e){for(const t of this.keys()){const i=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=i&&e(t,i)&&this.delete(t)}}get(e){return e=(0,o.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,o.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,o.toS)(e),this.has(e))return this.get(e);const i=t();return this.set(e,i),i}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,a.isNumber)(e.__uid)&&(0,a.isNumber)(e.__start)}},80049:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=i(31586),d=i(85556),h=i(54993),f=i(54557),m=i(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,n.set(this,0),r.set(this,0),s.set(this,0),a.set(this,0),o.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,n,l(this,n,"f")+e.cacheHitsSync,"f"),u(this,r,l(this,r,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,a,l(this,a,"f")+e.rejections,"f"),u(this,o,l(this,o,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,n,"f"),cacheHitsAsync:l(this,r,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,a,"f"),timeouts:l(this,o,"f")}}has(e){return this.cache.has(e)}get_(e){var t,i,a,o;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,r,(i=l(this,r,"f"),++i),"f"),c.promise):(u(this,n,(a=l(this,n,"f"),++a),"f"),c.value)}if(c instanceof Error)throw c;return u(this,n,(o=l(this,n,"f"),++o),"f"),c}get(e){var t,i;const r=this.cache.get(e);return null==r||r instanceof m.Deferred&&r.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,n,(i=l(this,n,"f"),++i),"f"),r instanceof m.Deferred?r.value:r}clear(){this.cache.clear(),u(this,n,0,"f"),u(this,r,0,"f"),u(this,s,0,"f"),u(this,a,0,"f"),u(this,o,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const i=this.get(e);if(null!=i){if(i instanceof Error)throw i;return i}return this.set(e,t())}getOrSetAsync(e,t){const i=(0,h.toS)(e);{const e=this.get_(i);if(null!=e)return e instanceof m.Deferred?e.promise:e}const n=new m.Deferred(this.opts.name).observe(t());return this.cache.set(i,n),(0,c.gt0)(this.opts.timeoutMs)&&n.setTimeout(this.opts.timeoutMs),n.promise.then((e=>{this.set(i,e)}),(e=>{var t,n;this.cache.set(i,e),u(this,a,(t=l(this,a,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,o,(n=l(this,o,"f"),++n),"f")})),n.promise}},n=new WeakMap,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap},54127:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class n{constructor(e){this.maxSize=e,this[i]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(i=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=n},53507:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,n.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};class m{constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const n=(0,a.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,r.range)(0,n).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,o.fromEntries)(e))).filter((e=>(0,o.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),i=[];let n,o=0;for(;null!=(n=t.exec(this.headerRow));){const l=this.headerRow.substring(o,n.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:n.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(n.index,t.lastIndex),d=n.index+((0,c.indexOfNonSpace)(u)??0),h=n.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find((e=>e.text===m));if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:n,left:d,right:h});else{const e=(0,r.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,n.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,r.last)(i);return null!=l&&((0,s.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map((e=>e.length))):l.rightIdx=o),i}}t.Fixed=m},73168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distanceMeters=t.geohashDistanceMeters=t.geoHashToLocation=t.ungeohash_num=t.ungeohash=t.geohashNumeric=t.geohashNumericShort=t.geohash=t.locationToGeohash=t.validLatLon=t.validLon=t.validLat=void 0;const n=i(55835),r=i(20014),s=i(55222),a=i(97352),o=30;function l(e){return 5*Math.floor(e/5)}function u(e){return(0,a.within)(-90,90,e)&&0!==e}function c(e){return(0,a.within)(-180,180,e)&&0!==e}function d(e,t){return u(e)&&c(t)}function h(e,t,i=o){return(0,n.map)(m(e,t,l(i)),(e=>s.GeoRadix.encode(e)))}t.validLat=u,t.validLon=c,t.validLatLon=d,t.locationToGeohash=function(e,t=o){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)};const f=new r.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=o){return d(e,t)?f.zip([t,e],l(i)):void 0}function p(e,t=o){return f.unzip(e,l(t))?.reverse()}function g(e,t=o){const[i,n]=p(e,t);return{lat:i,lon:n}}t.geohashNumeric=m,t.ungeohash=function(e,t=o){return(0,n.map)(s.GeoRadix.decode(e),(e=>p(e,t)))},t.ungeohash_num=p,t.geoHashToLocation=g;function y(e,t){const i=e.lat*Math.PI/180,n=t.lat*Math.PI/180,r=(t.lat-e.lat)*Math.PI/180,s=(t.lon-e.lon)*Math.PI/180,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(i)*Math.cos(n)*Math.sin(s/2)*Math.sin(s/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const n=i(51455),r=i(98553);var s=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const i=(0,r.parseJSON)(e);return null==i?void 0:t(i)},t.readJson_=async function(e){return(0,r.parseJSON)((await(0,n.readFile)(e)).toString())}},19851:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const a=i(57975),o=i(40958),l=i(50357),u=i(31586),c=i(65812),d=i(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),n.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,n,"m",r).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,o.isEmpty)(this.watchers))return;const i=await e,n=await t;if(!(0,l.eql)(i,n))for(const e of this.watchers)e(n);null!=this.ttlMs&&this.ttlMs>0&&void 0!==n&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(56519),d=i(84777),h=i(44198),f=i(6012),m=i(43334),p=i(24399),g=i(63870);t.DefaultLocale="en";const y=(0,n.lazy)((()=>(0,o.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?_():E()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,g.commandTimeoutMs)()}),t.envLocale=(0,n.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=w.exec(e.trim())?.groups;return null==i?void 0:(0,r.compact)([i.lang,i.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(p.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const M={timeoutMs:10*a.secondMs};async function _(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],M))}async function E(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],M)})))}t.localeMac=_,t.localePosix=E,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},57150:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const n=i(48161),r=i(1708),s=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,s.defer)((()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:r.argv,arch:(0,n.arch)(),platform:(0,n.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:g.isElectron,versions:(0,a.pick)(r.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:r.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),((e,t)=>[e,(0,m.isHiddenEnvKey)(e)?"(hidden)":t]))})}))},50213:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const n=i(19851),r=i(32105),s=i(14593);t.rootLoggers=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));const a=(0,n.lazy)((()=>[r.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,a)}},56639:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inverse=t.getLike=t.pickKeys=t.filterInPlace=t.filter=t.toObj=t.toMapAsync=t.toMap=t.compactMap=t.flatMap=t.hasAll=void 0;const n=i(40958),r=i(55835),s=i(59455),a=i(48884);function o(e){const t=(0,n.compact)(e).filter((([e,t])=>null!=e&&null!=t));return new Map(t)}function l(e,t){return new Map([...e.entries()].filter((([e,i])=>t(e,i))))}t.hasAll=function(e,t){return t.every((t=>e.has(t)))},t.flatMap=function(e,t){return new Map((0,a.concat)(...e.map((e=>t(e)))))},t.compactMap=o,t.toMap=function(e,t){return o((0,n.compact)(e).map(t))},t.toMapAsync=async function(e,t){return null==e?new Map:o(await Promise.all((0,n.compact)((0,s.toA)(e)).map((e=>t(e)))))},t.toObj=function(e){const t={};for(const[i,n]of e)t[i]=n;return t},t.filter=l,t.filterInPlace=function(e,t){[...e.entries()].forEach((([i,n])=>t(i,n)||e.delete(i)))},t.pickKeys=function(e,t){return l(e,(e=>t.indexOf(e)>=0))},t.getLike=function(e,t){return(0,r.map)([...e.entries()].find((([e])=>t(e))),(([,e])=>e))},t.inverse=function(e){return new Map([...e.entries()].map((([e,t])=>[t,e])))}},9103:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const n=i(98553),r=i(54557);t.memoize=function(e,t){let i=0;const s=new r.FifoCache(t.maxSize,t.ttlMs),a=t=>{if(null!=t)return i++,s.getOrSet((0,n.stringify)(t),(()=>e(t)))};return a.clear=e=>null==e?s.clear():s.delete((0,n.stringify)(e)),a.size=()=>s.size,a.callCount=()=>i,a}},31578:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageRssMb=t.memoryUsageRssBytes=t.memoryUsageMb=t.memoryUsageBytes=void 0;const n=i(1708),r=i(31586),s=i(12168),a=i(70417);function o(){const e=(0,n.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,n.memoryUsage)().rss}t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,r.sigFigs)(o()/s.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,r.sigFigs)(l()/s.MB,2)}},7282:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const r=n(i(1708)),s=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)((()=>r.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(r.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return r.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(r.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){r.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const n=i(40958),r=i(22573),s=i(96249),a=i(55835),o=i(31586),l=i(39926),u=i(54993),c=i(20014);var d=i(31586);function h(e,t){return(0,o.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(o.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,o.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,i){return(0,a.orElse)(h(e,t),i)},t.mapGte0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,o.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,o.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const n=(0,o.toInt)(e),r=(0,o.toInt)(t);return null!=n&&n>0&&null!=r&&r>0?i(n,r):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,o.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,a.map)(f.exec(t),(e=>(0,o.toFloat)(t.substr(e.index))))}function p(e){return(0,o.toInt)(m(e))}function g(e,t){if(null==e||null==t)return;const i=[e,t].map((e=>e.toString(2))),n=Math.max(...i.map((e=>e.length)));return i.map((e=>(0,l.leftPad)(e,n,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let i=0;for(let n=0;ne/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}},t.hammingDistanceBigInt=function(e,t){return(0,a.map)(g(e,t),(([e,t])=>(0,n.count)([...e],((e,i)=>e!==t.charAt(i)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,a.map)(g(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,n.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,i){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let n=0;const r=i*e.length;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const n=i(40958),r=i(42659),s=i(96249),a=i(55835),o=i(31586),l=i(68708),u=i(34666),c=i(41583),d=i(48884),h=i(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,r.isDate)(e[t]))).map((t=>[t,e[t]]))}function p(e,t){const i={};for(const[n,r]of(0,l.entries)(e)){const e=t(n,r);null!=e&&(i[n]=e)}return i}t.definedThunks=function(...e){return e.every((e=>(0,a.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(a.defined)},t.firstDefinedField=function(e,...t){return(0,a.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(i=>t(i,e[i])?e[i]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,a.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,n.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,n]of m(t))null==e[i]&&(e[i]=n);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,n]of(0,l.entries)(t))null==e[i]&&(e[i]=n);return e},t.pickMap=function(e,t,i){const n={};for(const r of t)n[r]=i(r,e[r]);return n},t.mapEntries=p,t.mapNullEntries=function(e,t,i){const n={};let r=0;for(const s of(0,l.keys)(e))if(n[s]=t(s,e[s]),r++,(0,o.gt)(r,i))break;return n},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const i={};for(const n of(0,h.sortIgnoreCase)((0,l.keys)(t)))i[n]=e(t[n]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...i))):p(t,((t,n)=>i.includes(t)?void 0:e(n,...i)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,n.uniq)((0,s.flatten)(e.map(l.keys))))t[i]=e.map((e=>e?.[i]));return t}},96175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osNameWin=t.osNameMac=t.isAlpine=t.isFedora=t.hasApt=t.isUbuntu=t.isDebian=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0;const n=i(31421),r=i(73024),s=i(48161),a=i(19851),o=i(22573),l=i(42659),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),w=(0,a.lazy)((()=>(0,f.mkLogger)("os")));function S(){return(0,s.platform)()+" "+(0,s.release)()}t.osArch=(0,a.lazy)((()=>`${function(){switch((0,s.platform)()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return F();default:return S()}}()} on ${(0,s.arch)()}`)),t.osFullName=(0,a.lazy)((()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":"")));const b=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function _(){return"fedora"===(0,t.osDistributionLinux)()}function E(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,a.lazy)((()=>{if(g.isLinux)for(const e of b)try{const t=(0,r.readFileSync)(e).toString();if((0,o.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){w().warn("failed to read os-release file",{filename:e,error:t})}})),t.osNameLinux=(0,a.lazy)((()=>{const e=(0,t.osReleaseTokens)();return(0,o.notBlank)(e?.pretty_name)?e?.pretty_name:(0,u.map2Or)(e?.name,e?.version??e?.version_id,((e,t)=>e+" "+t),S)})),t.osDistributionLinux=(0,a.lazy)((()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0)),t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=_,t.isAlpine=E;const x={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma"},T={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,n]=function(e){return e.split(".").slice(0,2)}(e),r=t[i];return(0,c.isString)(r)?r:r?.[n]}const k=(0,a.lazy)((()=>(0,n.execSync)("sw_vers -productVersion").toString().trim()));function C(e=k()){try{return(0,o.mapNotBlankOr)(function(e=k()){return D(e,x)}(e),(t=>`macOS ${t} (${e})`),S)}catch(e){return w().warn("osNameMac(): unknown release",e),S()}}function F(e=(0,s.release)()){const t=e.startsWith("10.0.22")?"11":D(e,T);return null!=t?`Windows ${t} (${e})`:(w().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.osNameMac=C,t.osNameWin=F,t.CPUs=(0,a.lazy)((()=>(0,h.uniqCount)((0,v.cpuInfo)().map((e=>e.model))).map((e=>`${e.count} × ${e.t}`)).join(", ")),l.minuteMs),t.whyOsNotSupported=(0,a.lazy)((()=>{if(g.isWin)return/^Windows (?:10|11) /i.test(F())?void 0:"Windows 10 and 11 is supported";if(g.isMac){const e=k();return(0,y.semverSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later is supported"}if(g.isLinux){const e=(0,d.toS)((0,y.debianVersionToSemver)((0,t.osReleaseTokens)()?.version_id));if(P())return(0,y.semverSatisfies)(e,">=11")?void 0:"Debian 11 or later is supported";if(M())return(0,y.semverSatisfies)(e,"20 || 22")?void 0:"Ubuntu 20.x LTS or 22.x LTS is supported";if(_())return(0,y.semverSatisfies)(e,"37 || 38")?void 0:"Fedora 37 or 38 is supported";if(E())return(0,y.semverSatisfies)(e,">=3.15")?void 0:"Alpine >= 3.15 is supported"}return"recent versions of Windows 10/11, macOS, Debian, Ubuntu, and Fedora are supported"}))},12801:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const r=n(i(48161)),s=i(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:r.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:r.default.constants.priority.PRIORITY_NORMAL,BelowNormal:r.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:r.default.constants.priority.PRIORITY_LOW,Low:r.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.setProcessTitle=t.setShortProcessNames=void 0;const n=i(72993),r=i(50213),s=i(23560),a=i(43334);let o=!a.isElectron;t.setShortProcessNames=function(e){o=e},t.setProcessTitle=function(){try{const e=[o?n.SimpleShortAppName:n.SimpleAppName];(0,s.isMainService)()&&a.isElectron||e.push((0,s.serviceName)());const t=e.join(a.isElectron?" ":"-");i(85949).title=t}catch(e){(0,r.mkLogger)("ServiceNames").warn("Failed to set friendly process name",e)}}},409:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const n=i(41400),r=i(56409),s=i(31586),a=i(22911),o=i(73614),l=i(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const p=[];function g(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...n){f=!0,m=Date.now()+(0,s.max_)(t,i);const r=d=new a.Deferred(c);(0,s.gt0)(i)&&r.setTimeout(i);try{r.resolve(await e(...n))}catch(e){r.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,o.setUnrefTimeout)(y,t+1),p.forEach((e=>e.resolve())),p.length=0}return r.promise}const w=(...e)=>{if(g()){if(!0===u)return null;const t=d?.promise;return h=e,(0,n.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new r.Latch;return p.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>g(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const n=i(68708),r=i(54993);function s(e){return e instanceof a?e.source:(0,r.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let r;for(;null!=(r=e.exec(t));)r.index===e.lastIndex?e.lastIndex++:i.push((0,n.pick)(r,"index","groups"));return i},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const n=[];for(const t of e)try{n.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{n.push(s(t))}const r=0===n.length?t.NothingRegExp:n.map((e=>"(?:"+e+")")).join("|");return new RegExp(r,i)};class a{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=a;class o extends a{static from(...e){const t=l(e);return new o("(?:"+t.source+")?",t.flags)}}function l(e,t){let i="",n=t?.includes("g")??!1,o=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof a||t instanceof RegExp?(i+=t.source,n||(n=t.global),o||(o=t.ignoreCase),l||(l=t.multiline)):i+=s((0,r.toS)(t));return new RegExp(i,t??(n?"g":"")+(o?"i":"")+(l?"m":""))}t.RegExpOptional=o,t.concatRegexp=l},79089:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const r=n(i(48161)),s=n(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),w=i(43334),S=i(24399),b=i(28874),P=(0,a.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>E.prior()?.clear()))));const M=(0,a.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,o.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>M().includes(e.toLowerCase())))};let _=!0;const E=(0,a.lazy)((()=>new g.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||E().has(e))return;E().add(e);const i=(0,p.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=p.PriorityClassToNode[i]),_)try{return r.default.setPriority(e,t),t}catch(i){const n=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:n,error:i}),n)return;_=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const r=n(i(1708)),s=i(19851),a=i(40958),o=i(5670),l=i(54993),u=i(7282),c=i(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===o.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===o.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===o.ServiceNames.sync}function p(){return(0,t.serviceName)()===o.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,a.compactBlanks)([t.serviceName.prior(),(0,l.toS)(r.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return o.ServiceNames.indexOf(e)??o.ServiceNames.length+1},t.MainServices=[o.ServiceNames.main,o.ServiceNames.desktop],t.DbServices=[o.ServiceNames.sync,o.ServiceNames.info,o.ServiceNames.web,o.ServiceNames.list,o.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[o.ServiceNames.sync,o.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===o.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===o.ServiceNames.info},t.isTestService=p,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||p())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||p())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const n=i(59455);function r(e){return e instanceof Set?e:new Set((0,n.toA)(e))}t.asSet=r,t.setEql=function(e,t){return(0,n.toA)(e.keys()).every((e=>t.has(e)))&&(0,n.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=r(t);return new Set([...e].filter((e=>i.has(e))))},t.diff=function(e,t){const i=r(t);return new Set([...e].filter((e=>!i.has(e))))}},19913:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=void 0;const n=i(5670),r=i(57150),s=i(7282),a=i(23560),o=i(17181);t.setServiceName=function(e){(0,a.isMainService)(e)&&(e=n.ServiceNames.main);const t=a.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),a.serviceName.set(e),(0,o.setupLogger)(),(0,r.logStartup)())}},28850:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim0=void 0;const o=i(62344),l=i(56038);t.shim0=function(e){return new u(e.name,e.impl)};class u extends o.ExtensibleFunction{constructor(e,t){super(),this.impl=t,n.set(this,void 0),r.set(this,void 0),s(this,n,e,"f")}_call(){return(0,l.time)(a(this,n,"f")+(null==a(this,r,"f")?"(local)":"(remote)"),null==a(this,r,"f")?this.impl():a(this,r,"f").call(this))}setShim(e){s(this,r,e,"f")}hasShim(){return null!=a(this,r,"f")}clearShim(){s(this,r,void 0,"f")}}n=new WeakMap,r=new WeakMap},12089:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=i(98553),d=i(34666),h=i(54993),f=i(62344),m=i(56038);t.shim1=function(e){return new p(e.name,e.impl,e.cache,e.toKey)};class p extends f.ExtensibleFunction{constructor(e,t,i,a){super(),n.add(this),this.impl=t,this.cache=i,this.toKey=a,r.set(this,void 0),s.set(this,void 0),l(this,r,e,"f")}async _call(e){return null==this.cache?u(this,n,"m",o).call(this,e):this.cache().getOrSetAsync(u(this,n,"m",a).call(this,e),(()=>u(this,n,"m",o).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,n,"m",a).call(this,e))}}r=new WeakMap,s=new WeakMap,n=new WeakSet,a=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},o=function(e){return(0,m.time)(u(this,r,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const n=i(42659);t.ShortCommandTimeoutMs=7*n.secondMs},92322:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=i(76790),a=i(17586);class o{constructor(e,t){this.valueOf=e,this.diff=t,n.set(this,[])}[(n=new WeakMap,Symbol.iterator)](){return r(this,n,"f")[Symbol.iterator]()}get length(){return r(this,n,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,i=r(this,n,"f").length-1;for(;t<=i;){const s=t+Math.floor((i-t)/2),a=this.valueOf(r(this,n,"f")[s]);if(e===a)return{found:!0,index:s};e>a?t=s+1:i=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&r(this,n,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...r(this,n,"f")];const a=t=>t<0||t>r(this,n,"f").length-1?null:(i??this.diff)(r(this,n,"f")[t],e),o=this.findIndex(e);if(null==o)return;let l=o.index-1,u=a(l),c=o.index,d=a(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return r(this,n,"f").shift()}at(e){return(0,a.at)(r(this,n,"f"),e)}toA(){return[...r(this,n,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===r(this,n,"f").length-1){const e=[...r(this,n,"f")];return r(this,n,"f").length=0,e}return r(this,n,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return r(this,n,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},54826:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.quietly=t.consoleError=t.consoleLog=void 0;const n=i(1708),r=i(82328),s=i(84542),a=i(95705),o=i(28874);t.consoleLog=function(e,...t){o.Settings.quiet.valueOrDefault||(0,r.stdoutEnded)()||console.log((0,s.crlf)(e),...t)},t.consoleError=function(e){o.Settings.quiet.valueOrDefault||(0,a.streamEnded)(n.stderr)||n.stderr.write(e)},t.quietly=async function(e){const t=o.Settings.quiet.envValue;try{return o.Settings.quiet.envValue=!0,await e()}finally{o.Settings.quiet.envValue=t}}},82328:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const n=i(1708),r=i(95705);t.stdoutEnded=function(){return(0,r.streamEnded)(n.stdout)}},71567:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const r=n(i(1708)),s=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(95705);function h(e,t){return f({obj:e,ready:t,stream:r.default.stdout})}function f({obj:e,ready:i,stream:n}){if(null==n||(0,d.streamEnded)(n))return;const r=(0,a.stringify)(e,void 0,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);n.write(r+"\n"),(0,o.isWorkerService)()&&null!=i&&(r.includes(u.FailStr)||(0,c.isFatalError)(r)||(0,c.isHealthCheckError)(r)?n.write(u.FailStr+"\n"):n.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||r.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:r.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const n=i(40958),r=i(76790),s=i(22573),a=i(55835),o=i(31586),l=i(39926),u=i(34666),c=i(51926),d=i(59455),h=i(54993),f=i(48884),m=i(68852),p=i(38835);var g=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return g.splitFirst}});var y=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=i(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(0===i.length)throw new Error("rightPad() given empty pad");const n=String(e);return n+(0,l.padding)(i,t-n.length)},t.padReplace=function(e,t,i,n){return(0,c.strslice)(e,0,t)+(0,l.padding)(n,i)+(0,c.strslice)(e,t+i)},t.contains=function(e,t,i){return(0,h.toS)(e).indexOf((0,h.toS)(t),i)>-1},t.countChars=function e(t,i,n=0){if(null==i||0===i.length)return 0;const r=t.indexOf(i,n);return-1===r?0:1+e(t,i,r+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,i){const n=Math.min(Math.ceil(e.length/t),i??e.length)-1;return n<=0?[e]:[...(0,o.times)(n,(i=>e.slice(i*t,(i+1)*t))),e.slice(n*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const n=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,n)+e.substring(n+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:n}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const n=(0,h.toS)(e),r=(0,h.toS)(t);return r.length>0&&(0,c.equalsIgnoreCase)(n.slice(-r.length),r,i)?n.slice(0,-r.length):n},t.gist=function(e,t=80,i=80){const n=(0,h.toS)(e),r=n.length-(t+i);return r<=0?n:n.slice(0,t).trim()+" …(+"+r+" chars)…"+n.slice(-i).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t):i}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,n.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,a.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const i=S(e.cmp[0],t.cmp[0]);return 0!==i?i:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,n.isEmpty)(e)||(0,s.blank)(t))return;for(const i of e)if((0,c.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),n=e.toLowerCase(),r=t.indexOf(n);if(r>=0)return{index:r,match:n}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const M=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return M.reduce(((e,[t,i])=>e.replace(t,i)),e).normalize()}t.dumbquote=_;const E=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e};const x=/^['‘’].*['‘’]$/,T=/^["“”„«»〃].*["“”„«»〃]$/;function D(e,t){const i=k(e,t);return(0,f.flatZip)(i.nonSeparators,i.separators).filter((e=>null!=e&&e.length>0))}function k(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+p.NonRetriableErrorFlag);const i=[],n=[];let r,s=0;for(;null!=(r=t.exec(e));)r.index===t.lastIndex?t.lastIndex++:(t.lastIndex=r[0].length+r.index,i.push(e.substring(s,r.index)),n.push(e.substring(r.index,t.lastIndex)),s=t.lastIndex);return s(0,o.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),x.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const i=(0,n.compactBlanks)(e),r=Math.max(...i.map((e=>e.length)));for(let e=0;e(0,a.map)(i[e],(e=>t+=e))));return t},t.splitKeep=D,t.splitUp=k,t.sortNaturalBy=C,t.sortNatural=function(e){return(0,r.sortBy)(e,(e=>C(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,n.compactBlanks)(e)),i=t.filter(((e,i)=>!P(t[i+1],e)));return(0,r.sortBy)(i,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const i=Math.min(e.length,t.length);for(let n=0;n4===e?.length?(0,o.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const F=/#.*$/gm;t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const n of(0,d.toA)(e))if(null!=n&&!(0,s.blank)(n))for(const e of n.split(t))(0,s.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,s.blank)(t))return e;const n=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),r=e.findIndex((e=>n.test(e))),a=new RegExp("("+(0,m.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(r<0)return e;for(let t=r+1;te.trim()))))}},83556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const n=i(54993);function r(e){return(0,n.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>"_"+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,n.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,i)=>" "+t.toLowerCase()+i)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=r,t.asObjectKey=function(e){return r(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const r=n(i(77598)),s=i(73913),a=i(55222);function o(e,t=s.HashBits){return r.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,n=224){return i.encodeBuffer(o(e,n)).substring(0,t)}t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,n=224){return l(e,t,i,n)}},94863:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const n=i(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,n.toS)(e).toLowerCase().normalize()}},96859:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const n=i(40958),r=i(76790),s=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let n=0,r="";for(let s=0;s=n&&(n=i.get(s,a),r=(0,l.substr)(e,s-n+1,n)));return r}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const n=e.normalize(),r=t.normalize();return e!==n||t!==r?y(n,r):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,i,n)=>i===t.charAt(n)?e:e+1),0)}function v(e,t){const i=e.toUpperCase().normalize(),n=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>i===n?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(i),t=w(n);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,i)=>e+t[i+1]))}function S(e,t){const i=(0,f.intersection)(e,t),r=[];return i.forEach((i=>{const s=Math.min((0,n.count)(e,(e=>e===i)),(0,n.count)(t,(e=>e===i)));(0,a.times)(s,(()=>r.push(i)))})),r}function b(e,t,i){const r=(0,n.commonPrefixLength)(e,t);return i((0,l.strslice)(e,r))-i((0,l.strslice)(t,r))}function P(e){const t=(0,n.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,r.sortBy)(t,(e=>-e.length))[0]}function M(e,t){const[i,n]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(i,n,(e=>(0,a.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=M;const _=/[^\da-z]+/gi;function E(e,t){const[i,n]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(_,"").toLowerCase()));return b(i,n,(e=>c.RadixAlphaNum.decode(e)))}function x(e,t){let i;for(let n=Math.max(e.length,t.length);n>=0;n--){const r=(0,a.mapNumericOr)(e.charCodeAt(n),(e=>e),256),s=(0,a.mapNumericOr)(t.charCodeAt(n),(e=>e),256),o=(0,a.clamp)(-256,256,r-s);i=null==i?o:(i+o)/2}return i}t.radixDiff=E,t.str=function(e,t){return{pref:(0,n.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:E(e,t)}},t.lcdiff=function(e){return(0,n.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=x,t.paddedPositionalDiff=function(e,t,i=8){return x((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))}},84885:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const n=i(98553),r=i(88158);t.stringifySorted=function(e){return(0,n.stringify)((0,r.sortedKeys)(e))}},75387:function(e,t,i){var n,r,s,a,o,l,u,c,d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLMap=void 0;const f=i(76790),m=i(42659),p=i(73614);class g{constructor(e){n.add(this),this[c]="TTLMap",r.set(this,[]),s.set(this,new Map),a.set(this,void 0),o.set(this,void 0),this.ttlMs=e}get ttlMs(){return d(this,a,"f")}set ttlMs(e){h(this,a,e,"f"),null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),h(this,o,(0,p.setUnrefInterval)((()=>d(this,n,"m",u).call(this)),e),"f"),d(this,n,"m",u).call(this)}destroy(){null!=d(this,o,"f")&&clearInterval(d(this,o,"f")),this.ttlMs=-m.dayMs,d(this,n,"m",u).call(this)}clear(){return d(this,s,"f").clear(),this}delete(e){return d(this,s,"f").delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of d(this,s,"f").entries())d(this,n,"m",l).call(this,t,i)&&e(i.v,t,this)}get(e){const t=d(this,s,"f").get(e);return d(this,n,"m",l).call(this,e,t)?(t.ts=Date.now(),t.v):void 0}getOrMaybeSet(e,t){const i=d(this,s,"f").get(e);if(d(this,n,"m",l).call(this,e,i))return i.v;const r=t();return null!=r&&this.set(e,r),r}lastSetOrGetTs(e){return d(this,s,"f").get(e)?.ts}set(e,t){return d(this,s,"f").set(e,{ts:Date.now(),v:t}),this}has(e){return d(this,n,"m",l).call(this,e,d(this,s,"f").get(e))}get size(){return d(this,n,"m",u).call(this),d(this,s,"f").size}keys(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield t)}()}values(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield i.v)}()}valuesByRecency(){return d(this,n,"m",u).call(this),(0,f.sortBy)(d(this,s,"f").values(),(e=>-e.ts))}entries(){const e=this;return function*(){for(const[t,i]of d(e,s,"f").entries())d(e,n,"m",l).call(e,t,i)&&(yield[t,i.v])}()}[(r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,c=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}on(e,t){d(this,r,"f").push(t)}}t.TTLMap=g,l=function(e,t){if(null==t)return!1;if(t.ts+this.ttlMs>Date.now())return!0;d(this,s,"f").delete(e);for(const i of d(this,r,"f"))i(e,t.v);return!1},u=function(){for(const[e,t]of d(this,s,"f").entries())d(this,n,"m",l).call(this,e,t)}},22277:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=i(73614);class u{constructor(e,t=!1){n.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[a]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return o(this,n,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>o(this,n,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||o(this,n,"m",r).call(this,e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)o(this,n,"m",r).call(this,t,i)||e(t,t,this)}has(e){return null!=e&&!o(this,n,"m",r).call(this,e)}values(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,i]of e.delegate)o(e,n,"m",r).call(e,t,i)||(yield[t,t])}()}toA(){return o(this,n,"m",s).call(this),[...this.delegate.keys()]}[(n=new WeakSet,a=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,r=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const i=t<=Date.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i},s=function(){for(const[e,t]of this.delegate)o(this,n,"m",r).call(this,e,t)}},84699:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},94174:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const r=n(i(48161)),s=n(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(38639),c=i(31586),d=i(50213),h=i(45255),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,a.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,a.lazy)((()=>(0,o.uniq)([s.default.geteuid?.(),s.default.getuid?.(),r.default.userInfo().uid]))),t.userid=(0,a.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,a.lazy)((()=>(0,o.uniq)([s.default.getegid?.(),s.default.getgid?.(),r.default.userInfo().gid]))),t.groupid=(0,a.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,a.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,a.lazy)((()=>(0,l.toNotBlank)(r.default.userInfo()?.username))),t.userNameFromWhoami=(0,a.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,a.lazy)((async()=>p.isWin?g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,a.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,a.lazy)((async()=>p.isWin?p.isWin?g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const n=i(42659),r=i(55835),s=i(31586),a=i(97790),o=i(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const i=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,r.allDefined)(i))return;const[a,o,u,c,d,h,f]=i,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(a,o-1,u,c,d,h,f/1e3)-m*n.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,a.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,o.within)(0,Date.now()+n.dayMs,e))).map((e=>new Date(e))).get()}},13991:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkSortableAssetFile_=t.mkAssetFile_=t.assetFileMetadata_=t.assetFileImageHashFields_=t.imageHashToAssetFileImageHashFields=t.assetFileStatFields_=t.assetFileUriFields_=void 0;const n=i(19851),r=i(55835),s=i(31586),a=i(59455),o=i(73168),l=i(50213),u=i(12089),c=i(76490),d=i(95696),h=i(48368),f=i(70417),m=i(28874),p=i(43207),g=i(47783),y=(0,n.lazy)((()=>(0,l.mkLogger)("asset-file.AssetFileFactory")));async function v(e){try{return{nativePath:e.nativePath,uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath}}catch(t){return y().throw("Failed to build URI for "+e,{error:t})}}async function w(e){const t=await e.stat_(),i=await e.sidecareStats();return{mtime:Math.floor((0,f.max)([t.mtimeMs,...(0,a.toA)(i).map((e=>e.mtimeMs))])),fileSize:t.size}}function S(e){return{...e,...c.DominantColor.toModeData(e.dominantColors)}}async function b(e){if(!m.Settings.useImageHashes.valueOrDefault)return;const t=await(0,h.imageHash_)(e.nativePath);return null==t?y().throw("Failed to extract image hash for "+e):S(t)}async function P(e){const[i,n,r,s]=await Promise.all([v(e),w(e),(0,t.assetFileMetadata_)(e),e.sha_()]);return{...i,...n,...r,sha:s}}t.assetFileUriFields_=v,t.assetFileStatFields_=w,t.imageHashToAssetFileImageHashFields=S,t.assetFileImageHashFields_=b,t.assetFileMetadata_=(0,u.shim1)({name:"asset-file.assetFileMetadata",impl:async function(e){try{const t=d.PosixFile.for(e),i=await(0,g.readTags)(t);if(null==i)throw new Error("Failed to read tags");if(null==i.capturedAt)throw new Error("Failed to read capturedAt");const n=i.capturedAt.toAssetFileFields();return null==n?y().throw("Failed to render assetFileFields from capturedAt",{capturedAt:i.capturedAt}):{...n,...i.exposureSettings,...i.dimensions,mimetype:i.mimetype,rotation:i.rotation,make:i.Make,model:i.Model,rating:i.rating,cameraId:i.cameraId,imageId:i.imageId,lensId:i.lensId,geohash:(0,o.geohashNumericShort)(i.GPSLatitude,i.GPSLongitude),durationMs:(0,p.extractDurationMs)(i),fps:(0,r.map)((0,s.toFloat)(i.VideoFrameRate),Math.floor)}}catch(t){return y().throw("_assetFileMetadata_() failed",{nativePath:e,error:t})}}}),t.mkAssetFile_=async function(e){const[t,i]=await Promise.all([P(e),b(e)]);return{...t,...i}},t.mkSortableAssetFile_=P},92434:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bestExistingAssetFile=t.assetFileSortCriteria=t.assetFileSortFields=t.assetFileSortCriteriaPojo=t.sortAssetFiles=t.mtime2sort=t.sortScale=t.dim2sort=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(22573),o=i(42659),l=i(23838),u=i(31586),c=i(68708),d=i(34666),h=i(50989),f=i(89937),m=i(50213),p=i(4001),g=i(29882),y=i(28874),v=i(14036),w=i(45200),S=i(34238),b=(0,n.lazy)((()=>(0,m.mkLogger)("img.AssetFileSorter"))),P=(0,h.strEnum)("file",f.PS_NETWORK_FILESYSTEM_SCHEME,f.PS_LOCAL_FILE_SCHEME,f.PS_LIBRARY_SCHEME);function M(e){return(0,u.map2Numeric)(e?.width,e?.height,((e,t)=>_(e*t)))}function _(e){if((0,u.gt0)(e))return Math.round(Math.pow(e,y.Settings.variantSortCriteriaPower.valueOrDefault))}function E(e){return Math.round(e/(5*o.minuteMs))}t.dim2sort=M,t.sortScale=_,t.mtime2sort=E;const x=["make","model","rating","cameraId","imageId","lensId","geohash"];function T(e){for(const t of(0,l.groupBy)(e,(e=>e.sha)).values())if(t.length>1){const e=Math.max(...(0,r.compact)(t.map((e=>e.mtime))));for(const i of t)i.mtime=e}return(0,s.sortBy)(e,C).reverse()}function D(e){const t=S.URI.parse(e.uri);if((0,a.blank)(t?.scheme)||(0,a.blank)(t?.path))return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=M(e);if(null==i)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const n=P.indexOf(t.scheme);if(null==n)return void b().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const r=e.mtime??0,s=(0,g.parsePosixPath)(t.path),l=[];for(const t of x)(0,a.blank)(e[t])||l.push(t);const u={resolution:i,schemeIdx:n,capturedAtPrecision:-(e.capturedAtPrecisionMs??o.weekMs),metadataCoverage:l.length,metadataFields:l.join(","),isBrowserSupported:(0,v.isSupportedByCurrentBrowserExt)(s.ext),mtime:E(r),isEditOrUpdate:/edit|update/i.test(s.base),isCover:/cover/i.test(s.base),count:Math.abs((0,p.copySuffixCountFromName)(s.name)??0),basename:d.CmpReverseFlag+s.base,parentBasename:d.CmpReverseFlag+(0,g.parentBasename)(e.nativePath??t.path),uri:d.CmpReverseFlag+e.uri};return b().tap({msg:"assetFileSortCriteriaPojo()",result:(0,c.toReqValued)(u)})}function k(){return(0,r.uniq)([...y.Settings.variantSortCriteria.values,"uri"])}function C(e){const t=D(e);if(null==t)return;const i=[];for(const e of k())i.push(t[e]);return i}t.sortAssetFiles=T,t.assetFileSortCriteriaPojo=D,t.assetFileSortFields=k,t.assetFileSortCriteria=C,t.bestExistingAssetFile=async function(e){for(const t of T(e))if(await(0,w.uriExists)(t.uri,t.nativePath))return b().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map((e=>e.uri))}});return b().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e.map((e=>e.uri))}})}},54296:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getAssetFileNativePath=void 0;const n=i(45200);t.getAssetFileNativePath=async function(e){return e.nativePath??(e.nativePath=await(0,n.uri2nativePath)(e.uri,e.mountpoint))}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class i extends Error{}t.AbortError=i},76740:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const o=i(45599),l=i(56409),u=i(73568);t.Abortable=class{constructor(){this._aborted=!1,n.set(this,void 0),r.set(this,(0,o.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,r,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,r,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,r,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),a(this,n,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,n,"f")&&clearTimeout(s(this,n,"f")),a(this,n,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},n=new WeakMap,r=new WeakMap},69591:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;const r=n(i(87997)),s=i(31586);t.debounce=function(e,t){let i,n=[];const a=(0,s.gt0)(t)?(...s)=>{n=s,null!=i&&r.default.clearTimeout(i),i=r.default.setTimeout((()=>{e(...n)}),t)}:e;return a.reset=()=>{null!=i&&r.default.clearTimeout(i),i=void 0},a.force=()=>{a.reset(),e()},a.setTimeoutMs=e=>{a.reset(),t=e},a.timeoutMs=()=>t,a}},22911:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},g=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(i(87997)),w=y(i(57975)),S=i(45599),b=i(26905),P=i(55835),M=i(31586),_=i(68708),E=i(20214),x=i(57153),T=i(85556),D=i(50213),k=i(70025),C=i(95937),F="TIMEOUT",O=(0,S.defer)((()=>(0,D.mkLogger)("async.Deferred")));class I{static async*toAsyncIterable(e,t){const i=[...e].reverse(),n=(0,M.gt0)(t)?new r(F).setTimeout(t):void 0;for(null!=n&&i.push(n);;){for(let n=i.length-1;n>=0;n--){const r=i[n];if(r.isSettled){if(r.name===F)return void O().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});i.splice(n,1),yield r.value}}if(i.every((e=>e.name===F)))break;try{await Promise.race(i)}catch{}}n?.clearTimeout()}static resolve(e,t){return new r(".resolved()",t).resolve(e)}constructor(e,t){var i,m,y;n.add(this),this.name=e,this.startedAt=Date.now(),a.set(this,void 0),o.set(this,x.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(g(i=r,r,(y=p(i,r,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{g(this,u,e,"f"),g(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return p(this,f,"f")??(0,D.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof r&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:p(this,o,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,_.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return p(this,a,"f")}get elapsedMs(){return(p(this,a,"f")??Date.now())-this.startedAt}get[(a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,E.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=p(this,h,"f")&&(v.default.clearTimeout(p(this,h,"f")),g(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,M.gt0)(e)&&(g(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,C.onTimeout)())}),e),"f"),p(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return p(this,o,"f")===x.PromiseStates.pending}get value(){return this.isResolved?p(this,l,"f"):void 0}get error(){return p(this,d,"f")}get isSettled(){return p(this,o,"f")!==x.PromiseStates.pending}get isResolved(){return p(this,o,"f")===x.PromiseStates.resolved}get isRejected(){return p(this,o,"f")===x.PromiseStates.rejected}get settledMs(){return null==p(this,a,"f")?void 0:p(this,a,"f")-this.startedAt}resolve(e){return p(this,n,"m",m).call(this,(()=>{g(this,o,x.PromiseStates.resolved,"f"),g(this,l,e,"f"),p(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,k.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return p(this,n,"m",m).call(this,(()=>{g(this,d,t,"f"),g(this,o,x.PromiseStates.rejected,"f"),p(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=I,r=I,m=function(e){if(p(this,o,"f")===x.PromiseStates.pending){(0,P.map)(p(this,h,"f"),v.default.clearTimeout),e(),g(this,a,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:p(this,l,"f")});return this},s={value:0}},27395:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const n=i(19851),r=i(40958),s=i(42659),a=i(23838),o=i(13538),l=i(50213),u=i(7282),c=i(97352),d=i(77740),h=i(25764),f=i(99331),m=i(73614),p=(0,n.lazy)((()=>(0,l.mkLogger)("async.Endable"))),g=new a.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const i=await e;if(null==i||!0===i?.ended)return;const n=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,i.endTimeoutMs,y);p().trace(i.name+" ending...",{timeoutMs:n});try{await(0,o.thenOrTimeoutError)(i.end(),n,(0,u.isTest)())}catch(e){try{p().warn(i.name+".end() failed",e)}catch{}}}function w(){g.filterInPlace(((e,t)=>!0!==t.ended)),p().debug("vacuumEndables()",g.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),g.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,n.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;p().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const i=g.get(t)??[];(0,r.isNotEmpty)(i)&&(p().debug("endEndables(): ending "+t),await Promise.allSettled(i.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,r.compact)(g.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const i=g.get(t)??[];e[t]=i.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=i(87997),h=i(55835),f=i(31586),m=i(68708),p=i(25764),g=i(38836),y=i(99331);class v extends g.EndableWrapper{constructor(e){super(e.name,(()=>u(this,n,"m",a).call(this)),e.rank??p.EndableRanks.first,e.endTimeoutMs),n.add(this),this.opts=e,r.set(this,void 0),s.set(this,void 0),o.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,r,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,i=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,n,"m",a).call(this);const h=()=>{u(this,n,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,r,(0,d.setInterval)(u(this,o,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,r,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,n,"a",l)&&(u(this,o,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,r=new WeakMap,s=new WeakMap,o=new WeakMap,n=new WeakSet,a=function(){(0,h.map)(u(this,r,"f"),d.clearInterval),c(this,r,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const n=i(50989);t.EndableRanks=(0,n.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const o=i(19851),l=i(45599),u=i(56409),c=i(50213),d=i(27395),h=i(25764),f=i(99331),m=i(56519);t.EndableWrapper=class{constructor(e,t,i=h.EndableRanks.first,a){this.endTimeoutMs=a,n.set(this,void 0),this.onEnds=[],r.set(this,(0,o.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,r,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(i,this)}setName(e){a(this,n,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,n,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,r,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},n=new WeakMap,r=new WeakMap},99331:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const n=i(7282);let r=!1;t.ending=function(){return r},t.setEnding=function(e){r=(0,n.isTest)()?e:e||r}},45608:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const r=n(i(1708)),s=i(22573),a=i(45599),o=i(37975),l=i(50213),u=i(71567),c=i(57159),d=i(57902),h=i(28874),f=i(27395),m=i(99331),p=i(56038),g=(0,a.defer)((()=>(0,l.mkLogger)((0,o.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,a.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(p.PromiseTimer.instance().report())}));async function v(e){g().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const i=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==i.errno||!0===i.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const n=(0,s.toNotBlank)(e?.reason)??i.toString();for(const e of t.onFatalHandlers)await e(n)}(0,m.ending)()||(await(0,f.endEndables)(),r.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,a.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])r.default[e].on(t,(i=>{v({reason:`${e}:${t}`,status:0,error:i})}))}))},60172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.firstDefinedLater=t.laterPromise=void 0,t.laterPromise=function(e){let t,i;return{promise:new Promise(((e,n)=>{t=e,i=n})),later:async()=>{try{const i=await e();return t(i),i}catch(e){throw i(e),e}}}},t.firstDefinedLater=async function(...e){if(null!=e)for(const t of e){if(null==t)continue;const e=await t();if(null!=e)return e}}},5916:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=i(45599),f=i(50357),m=i(31586),p=i(41583),g=i(62344),y=i(50213),v=i(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:n}){return new S(e,t,i,n)};class S extends g.ExtensibleFunction{constructor(e,t,i,l){super(),n.add(this),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=l,r.set(this,void 0),s.set(this,0),a.set(this,void 0),o.set(this,[])}_call(){return this.isStale()?c(this,n,"m",u).call(this,this.later()):c(this,a,"f")}unset(){d(this,s,0,"f"),d(this,r,void 0,"f"),d(this,a,void 0,"f")}set(e){return c(this,n,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,n,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,o,"f").push(e)}prior(){return this.isStale()?void 0:c(this,a,"f")}lastValue(){return c(this,a,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,r,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,r,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,r,"f")?void 0:Date.now()-c(this,r,"f")}elapsedMs(){return c(this,a,"f")?.settledMs??c(this,a,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,l=async function(e,t){var i;try{const i=await t;if(!(0,f.eql)(e?.value??await(e?.promise),i))for(const e of c(this,o,"f"))await e.onChange(i)}catch(e){const t=(0,p.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,o,"f"))e.onError(t)}finally{d(this,s,(i=c(this,s,"f"),++i),"f")}},u=function(e){d(this,r,Date.now(),"f");const t=c(this,a,"f");return d(this,a,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,a,"f").setTimeout(this.timeoutMs),c(this,n,"m",l).call(this,t,c(this,a,"f")),c(this,a,"f")}},1728:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoizeAsync=void 0;const n=i(98553),r=i(80049);t.memoizeAsync=function(e,t){let i=0;const s=new r.FifoCacheAsync(t),a=t=>(i++,s.getOrSetAsync((0,n.stringify)(t),(async()=>e(t))));return a.clear=e=>{if(null==e)return s.clear();{const t=(0,n.stringify)(e);return s.deleteIf((e=>t===e))}},a.size=()=>s.size,a.callCount=()=>i,a}},22781:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.oneAtATime=void 0;const l=i(62344),u=i(37461);t.oneAtATime=function({fn:e,runLaterIfBusy:t=!1,undefinedIfBusy:i}){return new c(e,t,i)};class c extends l.ExtensibleFunction{constructor(e,t=!1,i=!1){super(),this.fn=e,this.runLaterIfBusy=t,this.undefinedIfBusy=i,n.set(this,void 0),r.set(this,!1),s.set(this,!1)}_call(){return a(this,r,"f")?(o(this,s,!0,"f"),!0===this.undefinedIfBusy?void 0:a(this,n,"f")):(o(this,r,!0,"f"),o(this,n,(0,u.postrun)({fn:this.fn,postrun:()=>{o(this,r,!1,"f"),!0===this.runLaterIfBusy&&a(this,s,"f")&&(o(this,s,!1,"f"),setImmediate((()=>this._call())))}}),"f"))}isRunning(){return a(this,r,"f")}prior(){return a(this,n,"f")}async force(){return await a(this,n,"f"),this._call()}}n=new WeakMap,r=new WeakMap,s=new WeakMap},37461:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.postrun=void 0,t.postrun=async function(e){try{return await e.fn()}finally{await e.postrun()}}},56519:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const n=i(40958),r=i(76790),s=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(20214),c=i(13538),d=i(42279),h=i(32639),f=i(59455),m=i(41583),p=i(48884),g=i(50213),y=i(88158),v=i(15674),w=i(42638);var S=i(20214);async function b(e){if(null==e)return[];const t=(0,n.compact)(await e);return(0,n.isEmpty)(t)?[]:(0,n.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function M({name:e,arr:t,f:i,timeoutMs:r}){const s=[];for(const a of(0,n.compact)(await t))try{const e=await((0,l.gt0)(r)?(0,c.thenOrTimeoutError)(i(a),r):i(a));null!=e&&s.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return s}async function _({arr:e,f:t,name:i,maxConcurrent:r,timeoutMs:s,promises:a}){if(null==e)return[];const o=(0,n.compact)(await e);if((0,n.isEmpty)(o))return[];if((r=Math.round(r??(0,v.maxCpus)()))<=1)return M({arr:e,f:t,name:i,timeoutMs:s});const u=a??(o.length<=r?w.PermissivePromises:new w.Promises(i,(()=>r))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(i,o.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,g.mkLogger)(i).warn("failed to apply",{ea:e,error:t})}})));return(0,n.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,i){const n=[];for(const r of(0,p.batches)((0,f.toA)(await e),t)){const e=await b(r);n.push(...await b(i(e)))}return n},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,o.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,n.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,n.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=M,t.mapAsyncSerial=async function(e){return(await M(e)).map((e=>e[0]))},t.thenCollectParallel=_,t.mapAsync=async function({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s}){return(await _({arr:e,f:t,name:i,maxConcurrent:n,timeoutMs:r,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:i,maxConcurrent:r,timeoutMs:s}){return(await _({name:e,arr:(0,n.compact)(t),f:i,maxConcurrent:r,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const i=await _({name:"partitionAsync",arr:e,f:t});return[i.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),i.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*a.secondMs,t.tryAll=async function(e,i=(e=>console.error(e)),n=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,n)}catch(e){i((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),i=(()=>{})){let n,r=null;try{n=await((0,h.isFunction)(e)?e():e)}catch(e){r=(0,m.toErr)(e);try{await t(e)}catch{}}try{await i(r??n)}catch{}if(null!=r)throw r;return n},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,s.isTrue)(i)},t.thenMap2=async function(e,t,i){const n=await e;if(null==n)return;const r=await t;return null!=r?i(n,r):void 0},t.thenMapOr=async function(e,t,i){const n=await e;if(null==n)return i();const r=await t(n);return null==r?i():r},t.thenMap2Or=async function(e,t,i,n){const r=await e;if(null==r)return n();const s=await t;if(null==s)return n();const a=await i(r,s);return null==a?n():a},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const n of e){i++;try{if(null==n)continue;const e=await t(n,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:i}){const n=await _({name:e,arr:t,f:i});return(0,r.sortBy)(n,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(42659),o=i(49769),l=i(31586),u=i(68708),c=i(42279),d=i(41583),h=i(22454),f=i(14121),m=i(50213),p=i(7282),g=i(34102),y=i(82647),v=i(25764),w=i(38836),S=i(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,i){const n=Date.now(),r=(0,l.clamp)(10*a.secondMs,a.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-n)+"ms")}),r);try{const r=await(0,c.tot)(t),s=Date.now()-n;return i?.(r,s),this.push(e,s),r}catch(t){throw this.errors.incr(e),i?.((0,d.toErr)(t),Date.now()-n),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),i=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),n=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",i.stats()],...n])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,o.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:i.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,i])=>({...e,[t]:(0,l.mapFinite)(i.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:i.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,i])=>({...e,[t]:{sumSec:(0,l.sigFigs)(i.sum/a.secondMs,3),...(0,u.omit)(i.stats(),"sum")}})),{})}}function M(e,t,i){return P.instance().time(e,t,i)}function _(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,n.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,r.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,p.isTest)()&&(0,g.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=M,t.timeSync=function(e,t){const i=Date.now(),n=t();return _(e,Date.now()-i),n},t.pushTime=_,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,i){return(0,n.lazy)((async()=>M(e,t)),i)}},42638:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(i(66261)),m=i(40958),p=i(55835),g=i(31586),y=i(42279),v=i(54993),w=i(89788),S=i(82647),b=i(15674),P=i(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class M{constructor(e,t){n.add(this),this.name=e,this.ee=new f.default.EventEmitter,r.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),a.set(this,[]),o.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,r,t,"f")}get maxConcurrency(){return Math.floor((0,g.clamp)(1,(0,b.maxCpus)(),d(this,r,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,o,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,a,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,a,"f").map((e=>e.name)),pendingNames:d(this,o,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:i,serialId:r}){const s=d(this,n,"m",l).call(this,{name:e,l:t,payload:i,serialId:r});return this.laterPop(),s}enqueueAll(e,t){const i=t.map((t=>d(this,n,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialId:e,payload:i})}push(e,t,i){return d(this,n,"m",u).call(this,new P.Deferred(e,{payload:i}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,a,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,o,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,o,"f").length,e),i=this.runningSerialIds,r=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,a,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,o,"f").length}hasPending(){return d(this,o,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,g.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,o,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,o,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=M,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakSet,l=function({name:e,l:t,payload:i,serialId:n}){const r=new P.Deferred(e,{payload:i,serialId:n});return d(this,o,"f").push({d:r,l:t}),r},u=function(e,t){const i=Date.now();return this.lastWorkTs=i,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,a,"f"),e),this.settleMsAvg.push(Date.now()-i),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,a,"f").push(e),e},t.maybeRun=function(e,t){const i=new M(e);return()=>i.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return new M(e,(0,p.map)(i,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class i extends Error{}t.RedoableError=i},4867:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const n=i(40958),r=i(34546),s=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,n.compact)([(0,r.asPromise)(e).finally((()=>o=!1)),(0,a.gt0)(t)?(0,s.delay)(t).then((()=>{if(o)throw new l.TimeoutError})):void 0,i?.abortPromise_().then((()=>{if(o)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,n.compact)([(0,r.asPromise)(e).finally((()=>l=!1)),(0,a.gt0)(t)?(0,s.delay)(t).then((()=>o.Timeout)):void 0,i?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let i=e=>null;t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)}},73614:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const n=i(87997);t.setUnrefTimeout=function(e,t,...i){return(0,n.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,n.setInterval)(e,Math.round(t),...i).unref()}},31562:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const n=i(38639),r=i(42659),s=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:n,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const n=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??r.minuteMs)/5);await(0,s.delay)(n,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:n.isTrue,timeoutResult:!1})}},9727:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const r=n(i(1708)),s=i(45599),a=i(41400),o=i(50357),l=i(68708),u=i(48884),c=i(36638),d=i(44198),h=i(59958),f=i(96706),m=i(34102),p=i(19851),g=i(19043),y=i(66184),v=i(50213),w=i(7282),S=i(88158),b=i(45969),P=i(43334),M=i(28874),_=i(3790);function E(e){return x().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const x=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(M.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>E(e))))},(0,a.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,M.allSettings)())t.watchLater(e)}));const T=["HOME","LANG","USER"],D=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],k=(0,p.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?T:D),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,M.pathWithDefaults)(),e}));function C(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const i of(0,M.persistedSettings)()){const n=e?i.value:i.envValue;null==n||(0,o.eql)(n,i.defaultValue)||i.addToEnv(t)}return t}t.sanitizedEnv=(0,p.lazy)((()=>(0,l.filter)(r.default.env,(e=>E(e)||!(0,_.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=C,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:O({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let F=!1;function O({overrides:e,forceCLocale:i=!0,forWorker:n=!1}={}){const r=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...k(),...i?(0,g.childProcLocale)():{},...C(n),...e??{}});for(const e of(0,M.transientSettings)())e.deleteFromEnv(r);if((0,y.isLogged)("debug")&&!F){F=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(r).map((([e,t])=>[e,(0,_.isHiddenEnvKey)(e)?"(hidden)":t])),[i,n]=(0,u.partition)(t,(([e])=>E(e)));e.debug("PS env:",(0,l.fromEntries)(i)),e.debug("non PS env:",(0,l.fromEntries)(n))}return r}t.childEnv=O},84777:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const r=n(i(31421)),s=n(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),w=i(45255),S=i(22911),b=i(4867),P=i(73614),M=i(70025),_=i(57159),E=i(36868),x=i(66184),T=i(45643),D=i(95402),k=i(9727),C=(0,a.lazy)((()=>(0,p.mkLogger)("child.ChildProcess")));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function O(e,t=30*u.secondMs){if(null==e)return!1;C().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return C().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===s.default.pid)return C().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===s.default.ppid)return C().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,E.closeStreams)(e);{const t=e.kill();C().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,D.killPid)(i).catch((e=>{C().warn("endProcess(): kill("+i+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,g.isSingleSpecTests)())return!0;if(await(0,T.waitForPidExit)(i,t))return C().debug("endProcess(): exitted",F(e)),!0;{D.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");C().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),t||await(0,D.killPid)(i,!0).catch((e=>{C().warn("endProcess(): kill("+i+",true) failed: "+e)}))}return(0,T.waitForPidExit)(i,5e3)}function I(e,i,n,r=0){const a=new Date,o=[];return(0,v.niceable)(i,n)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(r,u.secondMs)&&o.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&O(e)}),r-250)),o.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,D.addPid)({pid:e.pid,cmd:i,timeoutMs:r,ppid:s.default.pid},a)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>o.forEach(clearTimeout))),e}function L(e,t,i,n){const s=(0,k.spawnOptions)(n);return(0,x.isLogged)("trace",C().context)?C().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:s}):C().debug("execFile()",{command:e,args:t,timeoutMs:i}),I(r.default.execFile(e,t,s),e,t,i)}async function A(e,t,i){const n=i.quiet??!1,r=i.ignoreStderr??!1,s=i.ignoreExitCode??!1,a=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===i.disconnect){try{a.disconnect?.()}catch{}return{result:"",pid:a.pid}}const u=a.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],p=[],g=[],y=new S.Deferred(f);a.on("error",(e=>g.push(e))),a.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),a.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,E.endStream)(a.stdin);const v=new d.Latch;null==a.stdout?v.resolve():(a.stdout.on("error",(e=>g.push(e))),a.stdout.on("data",(e=>m.push(e))),a.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==a.stderr||r?P.resolve():(a.stderr?.on("error",(e=>g.push(e))),a.stderr?.on("data",(e=>p.push(e))),a.stderr?.on("end",(()=>P.resolve()))),C().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:i.timeoutMs,halt:i.halt}),C().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const x=p.join("");(0,l.notBlank)(x)&&g.push(new Error(x)),!n&&(0,o.isNotEmpty)(g)&&C().warn(f+" resulted in errors:",g);const T=i.isIgnorableError??M.isIgnorableError,D=g.filter((e=>!0!==T(e)));if(D.length>0)throw 1===D.length?D[0]:new _.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:D});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:x}}catch(e){throw C().error("stdoutResult_() failed",e),await(0,D.killPid)(a.pid,!0),e}}t.endProcess=O,t.ReniceAfterMs=(0,a.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,a.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,i,n){const s=(0,k.spawnOptions)(n);return C().debug("spawn()",{command:e,args:t,maxAgeMs:i}),I(r.default.spawn(e,t,s),e,t,i)},t.execFile=L,t.stdoutResult_=A,t.stdout_=async function(e,t,i){const n=await A(e,t,i);return C().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(n.result),meta:{cmd:e,args:t,opts:i,result:n}})}},3790:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const n=i(22573),r=i(41400),s=i(19851),a=i(28874);(0,r.later)((()=>a.Settings.sensitiveEnvRegExp.watchLater((()=>o.unset()))));const o=(0,s.lazy)((()=>{try{return new RegExp(a.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${a.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(a.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,n.blank)(e)&&o().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||a.Settings.license.includesEnvKey(e)}},55534:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceExitCommand=void 0,t.ServiceExitCommand="--exit"},34330:function(e,t,i){var n,r,s,a,o,l,u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.WatchedChild=t.mkBasicWatchedChild=void 0;const d=i(58587),h=i(19851),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(54993),w=i(27395),S=i(25764),b=i(99331),P=i(42638),M=i(38835),_=i(8769),E=i(57159),x=i(66003),T=i(50213),D=i(45643),k=i(28874),C=i(84777);t.mkBasicWatchedChild=function(e){return new F({name:(0,f.compact)([e.cmd,...e.args]).join(" "),childFactory:()=>(0,C.spawn)(e.cmd,e.args,30*p.minuteMs),onStdout:()=>{},onError:()=>!0,ignoreStopErrors:!0,...e})};class F{constructor(e){n.add(this),this.startTs=Date.now(),this._stopped=!1,this.logger=(0,h.lazy)((()=>(0,T.mkLogger)("WatchedChild("+(0,f.compact)([this.name,this.pid]).join(":")+")"))),this.startRate=new d.Rate,this.mutex=new P.Promises("child.WatchedChild.mutex",(()=>1)),r.set(this,!1),this.onError=(e,t,i)=>{const s=new E.WrappedError(e,{cause:t}),a=!1!==s.ignorable;this.logger().log(a?"warn":"error","onError()",s),u(this,r,"f")||a||(this.lastError=s,(0,_.onError)(s),!0!==s.fatal?(i??this.opts.onError(e,s))&&(this.logger().warn("onError requested restart",{src:e,error:s}),u(this,n,"m",o).call(this)):this.end())},this.name=e.name,this.opts={dataSep:"\n",maxErrorsPerMinute:k.Settings.fatalErrorRatePerMinute.valueOrDefault,endableRank:S.EndableRanks.first,exitCommand:"",restartOnExit:!0,endTimeoutMs:null,...e},(0,w.addEndable)(this.opts.endableRank,this),u(this,n,"m",o).call(this)}get endTimeoutMs(){return(0,g.denull)(this.opts.endTimeoutMs)}get stopped(){return this._stopped}get ended(){return u(this,r,"f")}async end(){return c(this,r,!0,"f"),u(this,n,"m",s).call(this)}get proc(){return this.cp}get pid(){return(0,g.map)(this.cp,(e=>e.pid))}running(){return(0,d.pidExists)(this.pid)}notRunning(){return!this.running()}writeStdin(e){return this.cp?.stdin?.write(e)}async stop(){return this.logger().info("stop()"),this._stopped=!0,this.mutex.serial("",(()=>(this._stopped=!0,u(this,n,"m",s).call(this))))}isErrorRateExceeded(){return this.logger().tap({msg:"isErrorRateExceeded()",result:(0,y.gt)(this.startRate.eventsPerMinute,this.opts.maxErrorsPerMinute),meta:{startRatePerMin:this.startRate.eventsPerMinute,maxErrorsPerMin:this.opts.maxErrorsPerMinute}})}async restart(e=!1){return this.logger().info("restart()",{stopped:this._stopped,ended:u(this,r,"f")}),!u(this,r,"f")&&!(0,b.ending)()&&(e||!(0,y.lt)(this.startRate.msSinceLastEvent,k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault)?this.mutex.serial("",(async()=>(await u(this,n,"m",s).call(this),this._stopped=!1,u(this,n,"m",l).call(this)))):void this.logger().info("restart(): last restart was too recent. Ignoring.",{msSinceLastEvent:this.startRate.msSinceLastEvent,minTimeBetweenServiceRestartsMs:k.Settings.minTimeBetweenServiceRestartsMs.valueOrDefault}))}async start(){return this.logger().info("start()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.serial("",(async()=>(this._stopped=!1,u(this,n,"m",l).call(this))))}}t.WatchedChild=F,r=new WeakMap,n=new WeakSet,s=async function(){this.logger().info("#stop()",{stopped:this._stopped,ended:u(this,r,"f")});const e=this.cp;return this.cp=void 0,u(this,n,"m",a).call(this,e)},a=async function(e){if(null==e)return!0;if((0,y.gt0)(e.pid)&&(0,m.notBlank)(this.opts.exitCommand)&&!0===e.stdin?.writable)try{e.stdin.write(this.opts.exitCommand+"\n"),await(0,D.waitForPidExit)(e.pid,(this.endTimeoutMs??p.secondMs)/2)}catch(e){this.logger().warn("stopChild: error writing to stdin",{error:e})}return(0,C.endProcess)(e,this.endTimeoutMs)},o=async function(){return this.logger().info("#restart()",{stopped:this._stopped,ended:u(this,r,"f")}),this.mutex.maybeRun("",(async()=>(await u(this,n,"m",s).call(this),!this._stopped&&!u(this,r,"f")&&(this.isErrorRateExceeded()?(this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),this.opts.onRestartPaused?.(),(0,_.onError)("Can't restart "+this.name+", failure rate is too high."+M.FatalErrorFlag,this.lastError),!1):(this.logger().info("#restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.opts.onRestart?.(),u(this,n,"m",l).call(this))))))},l=async function(){if(this.logger().info("#start()",{stopped:this._stopped,ended:u(this,r,"f")}),this._stopped||u(this,r,"f")||(0,b.ending)())return!1;if(this.running())return!1;this.startRate.onEvent();const e=this.cp=await this.opts.childFactory();this.logger.unset(),this.logger().info("#start(): spawned pid "+this.pid);const t="cp("+e.pid+")";return[{o:e,desc:""},{o:e.stdin,desc:".stdin"},{o:e.stdout,desc:".stdout"},{o:e.stderr,desc:".stderr"}].forEach((({o:e,desc:i})=>{(0,g.map)(e,(e=>e.on("error",(e=>this.onError(t+i+".on(error)",e)))))})),(0,g.map)(this.cp.stdout,(e=>(0,x.onDataChunked)(e,this.opts.dataSep,(e=>{this.logger().trace("onDataChunked()",e),this.opts.onStdout(e)})))),(0,g.map)(this.cp.stderr,(e=>e.on("data",(async e=>{(0,v.toS)(e).includes("Error: Cannot find module")&&(0,_.onError)("Failed to start "+this.name+M.FatalErrorFlag,new Error(e)),!0===await(this.opts.onStderr?.(e))&&this.onError(t+".stderr.on(data)",e)})))),this.cp.on("exit",(async(e,t)=>{this.logger().info("onExit",{code:e,signal:t,stopped:this._stopped,ended:u(this,r,"f")}),(0,b.ending)()||(this.opts.restartOnExit?(await u(this,n,"m",o).call(this),this.logger().info("onExit(): finished setting up new child",{pid:this.pid})):(this.logger().info("onExit(): this.opts.restartOnExit is false. Ending.",{pid:this.pid}),this.end()))})),!0}},46199:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=t.ciSafePath=void 0;const a=s(i(53916)),o=i(17217),l=i(19935),u=i(7282),c=i(84699),d=i(9595),h=i(4001),f=i(95696);function m(e){return(0,h.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}t.ciSafePath=function(e,t){if(!(0,u.isTest)())return(0,o.toNativePath_)(e);const i=f.PosixFile.for(e),n=t?.stableBasename??1?m(i):i.base.normalize(),r=i.sibling(n);if(r.isSelfOrDescendantOf((0,l.examples)()))return a.join("$examples",r.posixPathFrom((0,l.examples)()));const s=(0,d.originalsDir)();if(r.isSelfOrDescendantOf(s))return a.join("$library",r.posixPathFrom(s));const h=i.findAncestor((e=>e.base.startsWith(c.TestLibraryDirPrefix)));return null!=h?a.join("$library",r.posixPathFrom(h)):i.baseWithGrandparent},t.stableBasename=m},80061:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const n=i(1708),r=i(31586),s=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,r.toInt)(n.env.maxLineLen)??n.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,a.EditionName)()+" v"+o.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},54772:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bestLabhashName=t.bestLabName=t.bestRgbName=t.colorToTuple=t.bestRgbTripletName=t.ColorNames=void 0;const n=i(19851),r=i(40958),s=i(49769),a=i(31586),o=i(48884),l=i(50213),u=i(81168),c=i(85810),d=i(42079),h=i(91482),f=i(3048),m=i(85409),p=i(16050),g=i(42022),y=i(85042),v=(0,n.lazy)((()=>(0,l.mkLogger)("color.ColorNames")));function w(e){const t=(0,y.normalizeRgbHex)(e.rgb);if(null==t)return void v().warn(`skipping invalid entry (bad rgb): ${e.rgb}`,e);const i=(0,c.rgbhex2Lab)(t);if(null==i)return void v().warn(`skipping invalid entry (failed to convert to L*a*b): ${t}`,e);const n=(0,c.toLabhash)(i,g.ModeBits);return{...e,rgb:t,lab:i,labhash:n,closeLabhashes:[n],closeRgb:[t],name:(0,u.capitalize)(e.name)}}function S(e,i){return null==e?void 0:(0,o.leastBy)(i??(0,t.ColorNames)(),(t=>(0,f.ciede2000_delta_e)(t.lab,e)))}t.ColorNames=(0,n.lazy)((()=>(0,r.compact)([...d.CrayonColors,...d.CrayonSupplements,...h.DarkWikipediaColors,...p.LightWikipediaColors,...m.Greys].map(w)))),t.bestRgbTripletName=function(e,i=(0,t.ColorNames)()){return S((0,c.rgb2lab)(e),i)},t.colorToTuple=w,t.bestRgbName=function(e){return P((0,c.rgbhex2Labhash)(e))},t.bestLabName=S;const b=new Map;function P(e){return(0,a.gte0)(e)?(0,s.getOrSet)(b,e,(()=>{const i=(0,t.ColorNames)().find((t=>t.labhash===e));if(null!=i)return i;const n=(0,c.unlabhash)(e),s=S(n);return null!=n&&null!=s&&((0,r.pushUniq)(s.closeLabhashes,e),(0,r.pushUniq)(s.closeRgb,(0,c.lab2rgbhex)(n))),s})):void 0}t.bestLabhashName=P},85810:(e,t,i)=>{e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.hsv2rgb=t.hsl2hsv=t.hsv2hsl=t.hsl2rgb=t.rgb2hsl=t.rgbhex2hsl=t.rgb2hsv=t.closestLab=t.maxLabhash=t.minLabhash=t.unlabhash=t.toLabhash=t.LabBitZip=t.xyz2rgb=t.lab2xyz=t.xyz2lab=t.rgb2xyz=t.clampLab=t.lab2rgb=t.rgb2lab=t.rgb2labArray=t.rgb2labTriplets=t.lab2rgbhex=t.rgbhex2Labhash=t.rgbhex2Lab=void 0;const n=i(19851),r=i(40958),s=i(49769),a=i(55835),o=i(31586),l=i(48884),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return M(w(e))}function y(e){return(0,f.clampRGB)(E(_(e)))}function v(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map((e=>e/255)).map((e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92));return(0,c.matXvec)(m,t)}t.rgbhex2Lab=function(e){return(0,a.map)((0,f.rgbhex2triplet)(e),g)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,a.map)((0,f.rgbhex2triplet)(e),(e=>x(g(e),t)))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(y(e))},t.rgb2labTriplets=function(e){return(0,r.stepRange)(0,e.length,3).map((t=>g([e[t],e[t+1],e[t+2]])))},t.rgb2labArray=function(e){const t=[],i=[],n=[];for(let r=0;re>b?Math.pow(e,1/3):(P*e+16)/116));return v([116*i-16,500*(t-i),200*(i-n)])}function _(e){const[t,i,n]=v(e),r=(t+16)/116,s=i/500+r,a=r-n/200,o=s*s*s,l=a*a*a,u=o>b?o:(116*s-16)/P,c=t>8?Math.pow(r,3):t/P,d=l>b?l:(116*a-16)/P;return[u*S.X,c*S.Y,d*S.Z]}function E(e){return(0,c.matXvec)(p,e).map((e=>{const t=e<0?-1:1,i=e*t;return(0,o.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))}))}function x(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.xyz2lab=M,t.lab2xyz=_,t.xyz2rgb=E,t.LabBitZip=(0,n.lazy)((()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]))),t.toLabhash=x;const T=new Map;function D(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function k(e){const[t,i,n]=(0,f.clampRGB)(e),r=Math.max(t,i,n),s=r-Math.min(t,i,n),a=s?r===t?(i-n)/s:r===i?2+(n-t)/s:4+(t-i)/s:0;return[60*(a<0?a+6:a),r?s/r*100:0,r/255*100]}function C(e){return F(k(e))}function F(e){const[t,i,n]=e,r=(200-i)*n/100;return[t,r>0&&r<200?i*n/100/(r<=100?r:200-r)*100:0,r/2]}function O(e){const[t,i,n]=e,r=i*(n<50?n:100-n)/100;return[t,r>0?2*r/(n+r)*100:0,n+r]}function I(e){const t=e[0]/360*6,i=e[1]/100,n=e[2]/100,r=Math.floor(t),s=n*(1-i),a=n*(1-(t-r)*i),o=n*(1-(1-t+r)*i),l=r%6;return(0,f.clampRGB)([255*[n,a,s,s,o,n][l],255*[o,n,n,a,s,s][l],255*[s,s,o,n,n,a][l]])}t.unlabhash=function(e,t=h.ModeBits){return t===h.ModeBits?(0,s.getOrSet)(T,e,(()=>D(e,t))):D(e,t)},t.minLabhash=(0,n.lazy)((()=>(0,t.LabBitZip)().zipMin(h.ModeBits))),t.maxLabhash=(0,n.lazy)((()=>(0,t.LabBitZip)().zipMax(h.ModeBits))),t.closestLab=function(e,t){return(0,l.leastBy)(e,(e=>(0,d.ciede2000_delta_e)(e,t)))},t.rgb2hsv=k,t.rgbhex2hsl=function(e){return C((0,f.rgbhex2triplet)(e))},t.rgb2hsl=C,t.hsl2rgb=function(e){return I(O(e))},t.hsv2hsl=F,t.hsl2hsv=O,t.hsv2rgb=I,i.c[i.s]===e&&console.log(x([0,0,0]))},42079:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CrayonSupplements=t.CrayonColors=void 0,t.CrayonColors=[{name:"Aquamarine",rgb:"#95E0E8"},{name:"Asparagus",rgb:"#7BA05B"},{name:"Blue-green",rgb:"#0095B7"},{name:"Royal blue",rgb:"#273BE2"},{name:"Blush",rgb:"#DB5079"},{name:"Brilliant rose",rgb:"#E667CE"},{name:"Brown",rgb:"#AF593E"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Burnt umber",rgb:"#805533"},{name:"Cadet blue",rgb:"#A9B2C3"},{name:"Canary",rgb:"#FFFF99"},{name:"Carmine",rgb:"#E62E6B"},{name:"Carnation pink",rgb:"#FFA6C9"},{name:"Celestial blue",rgb:"#7070CC"},{name:"Cerise",rgb:"#DA3287"},{name:"Cerulean blue",rgb:"#339ACC"},{name:"Chestnut",rgb:"#B94E48"},{name:"Cobalt blue",rgb:"#8C90C8"},{name:"Copper",rgb:"#DA8A67"},{name:"Cornflower",rgb:"#93CCEA"},{name:"Cotton candy",rgb:"#FFB7D5"},{name:"Denim",rgb:"#1560BD"},{name:"Eggplant",rgb:"#614051"},{name:"Fern",rgb:"#63B76C"},{name:"Fuchsia",rgb:"#C154C1"},{name:"Russet",rgb:"#87421F"},{name:"Green",rgb:"#01A638"},{name:"Green-yellow",rgb:"#F1E788"},{name:"Indigo",rgb:"#4F69C6"},{name:"Jungle green",rgb:"#29AB87"},{name:"Magenta",rgb:"#F653A6"},{name:"Maize",rgb:"#F2C649"},{name:"Maroon",rgb:"#C32148"},{name:"Medium chrome green",rgb:"#6CA67C"},{name:"Medium violet",rgb:"#8F47B3"},{name:"Melon",rgb:"#FEBAAD"},{name:"Middle blue-green",rgb:"#8DD9CC"},{name:"Middle blue-purple",rgb:"#8B72BE"},{name:"Green-yellow",rgb:"#ACBF60"},{name:"Middle purple",rgb:"#D982B5"},{name:"Middle yellow-red",rgb:"#ECAC76"},{name:"Midnight blue",rgb:"#003366"},{name:"Mulberry",rgb:"#C8509B"},{name:"Navy blue",rgb:"#0066CC"},{name:"Olive green",rgb:"#B5B35C"},{name:"Orange",rgb:"#FF8833"},{name:"Orchid",rgb:"#E29CD2"},{name:"Peach",rgb:"#FFCBA4"},{name:"Periwinkle",rgb:"#C3CDE6"},{name:"Pine green",rgb:"#01796F"},{name:"Pink flamingo",rgb:"#FC74FD"},{name:"Plum",rgb:"#8E3179"},{name:"Raw umber",rgb:"#665233"},{name:"Red-orange",rgb:"#FF681F"},{name:"Red",rgb:"#ED0A3F"},{name:"Salmon",rgb:"#FF91A4"},{name:"Vivid scarlet",rgb:"#FD0E35"},{name:"Sea green",rgb:"#93DFB8"},{name:"Sepia",rgb:"#9E5B40"},{name:"Shamrock",rgb:"#33CC99"},{name:"Sky blue",rgb:"#76D7EA"},{name:"Spring green",rgb:"#ECEBBD"},{name:"Sunset orange",rgb:"#FE4C40"},{name:"Tan",rgb:"#FA9D5A"},{name:"Teal blue",rgb:"#008080"},{name:"Thistle",rgb:"#D8BFD8"},{name:"Vivid tangerine",rgb:"#ED3C10"},{name:"Vivid violet",rgb:"#a625c3"},{name:"Wisteria",rgb:"#C9A0DC"},{name:"Yellow-green",rgb:"#C5E17A"},{name:"Yellow-orange",rgb:"#FFAE42"},{name:"Yellow",rgb:"#FBE870"}],t.CrayonSupplements=[{name:"Artichoke",rgb:"#8F9779"},{name:"Aubergine",rgb:"#48213A"},{name:"Brandy rose",rgb:"#B1847F"},{name:"Burgundy",rgb:"#800020"},{name:"Burnt sienna",rgb:"#E97451"},{name:"Crimson red",rgb:"#990000"},{name:"Dark brown",rgb:"#664228"},{name:"Dark coral",rgb:"#CD5B45"},{name:"Dark green",rgb:"#006400"},{name:"Dark raspberry",rgb:"#872657"},{name:"Dark turquoise",rgb:"#610079"},{name:"Deep teal",rgb:"#004040"},{name:"Deep coffee",rgb:"#704241"},{name:"Dusty rasberry",rgb:"#917980"},{name:"Ecru",rgb:"#BCAC7C"},{name:"Evergreen",rgb:"#05472A"},{name:"Eggplant",rgb:"#380835"},{name:"Eggplant purple",rgb:"#430541"},{name:"Emerald green",rgb:"#028F1E"},{name:"Flamingo pink",rgb:"#D67C99"},{name:"Grape",rgb:"#6C3461"},{name:"Kelly green",rgb:"#4CBB17"},{name:"Light forest green",rgb:"#4F9153"},{name:"Medium dark brown",rgb:"#AF7200"},{name:"Medium dark cyan-blue",rgb:"#2D537C"},{name:"Mustard",rgb:"#FAAF18"},{name:"Neon green",rgb:"#39FF14"},{name:"Pear",rgb:"#D1E231"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Phthalo blue",rgb:"#0016C7"},{name:"Pink lace",rgb:"#FFDDF4"},{name:"Raw sienna",rgb:"#884B15"},{name:"Rebecca purple",rgb:"#663399"},{name:"Sap green",rgb:"#536916"},{name:"Blue sapphire",rgb:"#133ECB"},{name:"Sand",rgb:"#B38751"},{name:"Shadow blue",rgb:"#778BA5"},{name:"Shadow green",rgb:"#121E06"},{name:"Swamp green",rgb:"#748500"},{name:"Verdigris",rgb:"#43B3AE"},{name:"Vivid blue-magenta",rgb:"#4817E8"},{name:"Vivid blue-purple",rgb:"#ACACE6"},{name:"Vivid blue",rgb:"#47ABCC"},{name:"Vivid green-yellow",rgb:"#D9E650"},{name:"Vivid green",rgb:"#7BE214"},{name:"Vivid turqoise",rgb:"#06ECD2"},{name:"Vivid lavender",rgb:"#A354FD"},{name:"Vivid mint",rgb:"#00F28C"},{name:"Vivid pink",rgb:"#D752FB"},{name:"Vivid red-purple",rgb:"#C31D7E"},{name:"Vivid red",rgb:"#D92121"},{name:"Vivid yellow-red",rgb:"#F2BA49"},{name:"Vivid yellow",rgb:"#FAFA37"}]},91482:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DarkWikipediaColors=void 0,t.DarkWikipediaColors=[{name:"Bistre",rgb:"#3D2B1F"},{name:"Black bean",rgb:"#3D0C02"},{name:"Black pearl",rgb:"#041322"},{name:"Shadow blue",rgb:"#001440"},{name:"Charcoal",rgb:"#36454F"},{name:"Dark indigo",rgb:"#1F0A52"},{name:"Dark magenta",rgb:"#8B008B"},{name:"Dark moss green",rgb:"#4A5D23"},{name:"Dark navy",rgb:"#02075D"},{name:"Dark pastel blue",rgb:"#779ECB"},{name:"Dark purple",rgb:"#580040"},{name:"Dark tan",rgb:"#918151"},{name:"Dark yellow-green",rgb:"#304000"},{name:"Dark yellow",rgb:"#9B870C"},{name:"Deep violet",rgb:"#330066"},{name:"Dusk",rgb:"#4E5481"},{name:"Elderberry",rgb:"#1d1a34"},{name:"Grey jade",rgb:"#757C55"},{name:"Grey magenta",rgb:"#83667F"},{name:"Grey ochre",rgb:"#716659"},{name:"Grey olive",rgb:"#656c5a"},{name:"Grey sage",rgb:"#69724d"},{name:"Taupe",rgb:"#483C32"}]},3048:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciede2000_delta_e=t.diffCIECorr=t.MaxCie=t.MinCie=t.cie94_delta_e=t.cie76_delta_e=void 0;const n=i(31586),r=i(97352);t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,n,s]=e,[a,o,l]=t,u=i-a,c=n-o,d=s-l,h=(0,r.sqrt)(n**2+s**2),f=h-(0,r.sqrt)(o**2+l**2),m=(0,r.sqrt)(c**2+d**2-f**2);return(0,r.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.MinCie=2,t.MaxCie=20,t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,n.clamp)(0,t.MaxCie,l(e,i)-t.MinCie)/t.MaxCie};const s=1,a=1,o=1;function l(e,t){const[i,n,l]=e,u=(0,r.sqrt)(n**2+l**2),[c,d,h]=t,f=(u+(0,r.sqrt)(d**2+h**2))/2,m=.5*(1-(0,r.sqrt)(Math.pow(f,7)/(Math.pow(f,7)+Math.pow(25,7)))),p=n*(1+m),g=d*(1+m),y=(0,r.sqrt)(p*p+l*l),v=(0,r.sqrt)(g*g+h*h);let w=Math.abs(p)+Math.abs(l)===0?0:Math.atan2(l,p);w+=2*(w<0?1:0)*Math.PI;let S=Math.abs(g)+Math.abs(h)===0?0:Math.atan2(h,g);S+=2*(S<0?1:0)*Math.PI;const b=c-i,P=v-y;let M=y*v==0?0:S-w;M-=2*(M>Math.PI?1:0)*Math.PI,M+=2*(M<-Math.PI?1:0)*Math.PI;const _=2*(0,r.sqrt)(y*v)*Math.sin(M/2),E=(i+c)/2,x=(y+v)/2;let T;y*v==0?T=w+S:(T=(w+S)/2,T-=(Math.abs(w-S)>Math.PI?1:0)*Math.PI,T+=2*(T<0?1:0)*Math.PI);const D=(E-50)**2,k=1-.17*Math.cos(T-Math.PI/6)+.24*Math.cos(2*T)+.32*Math.cos(3*T+Math.PI/30)-.2*Math.cos(4*T-63*Math.PI/180),C=1+.015*D/(0,r.sqrt)(20+D),F=1+.045*x,O=1+.015*x*k,I=30*Math.PI/180*Math.exp(-1*((180/Math.PI*T-275)/25)**2),L=2*(0,r.sqrt)(Math.pow(x,7)/(Math.pow(x,7)+Math.pow(25,7))),A=-1*Math.sin(2*I)*L;return(0,r.sqrt)(Math.pow(b/(s*C),2)+Math.pow(P/(a*F),2)+Math.pow(_/(o*O),2)+A*P/(a*F)*_/(o*O))}t.ciede2000_delta_e=l},76490:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColor=t.dominantColorsToRgbHex=void 0;const n=i(40958),r=i(31586),s=i(97352),a=i(54772),o=i(85810),l=i(42022),u=i(1971);t.dominantColorsToRgbHex=function(e){return(0,n.compact)(e.map((e=>[e.rgbhex,(0,r.fmtPct)(e.pct)])))};class c{static fromModeData(e){return(0,n.compact)((0,r.times)(u.ModeCount,(t=>c.fromLabhash({labhash:e[`mode${t}`],pct:e[`mode${t}pct`]}))))}static toModeData(e){const t={};return(0,r.times)(u.ModeCount,(i=>{t["mode"+i]=e[i]?.labhash??null,t["mode"+i+"pct"]=e[i]?.pct??null})),t}static fromLabhash({labhash:e,labhashBits:t=l.ModeBits,pct:i}){const n=(0,s.mapGt0)(e,(e=>(0,o.unlabhash)(e,t)));return null!=n&&(0,r.gt0)(i)?new c(n,i,e):void 0}static fromCentroid(e,t){return new c(e.centroid,Math.round(e.size/t*100))}constructor(e,t,i){this.lab=e,this.pct=(0,r.clamp)(0,100,t),this.labhash=i??(0,o.toLabhash)(e,l.ModeBits)}get rgbhex(){return(0,o.lab2rgbhex)(this.lab)}get color(){return(0,a.bestLabhashName)(this.labhash)}toGreyscale(){return new c([this.lab[0],0,0],this.pct)}eql(e){return this.labhash===e.labhash&&(0,r.closeTo)(this.pct,e.pct,5)}}t.DominantColor=c},40401:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeNearCentroids=t.mergeLabhashes=t.dominantColorsFromModes=t.maybeFilterGrey=t.centroidsScore=t.extractDominantColors=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(41400),o=i(98553),l=i(31586),u=i(68708),c=i(48884),d=i(22454),h=i(50213),f=i(56038),m=i(82647),p=i(44983),g=i(70417),y=i(28874),v=i(85810),w=i(3048),S=i(76490),b=i(1971),P=(0,n.lazy)((()=>(0,h.mkLogger)("color.DominantColors")));t.extractDominantColors=function(e,t=b.ModeCount){return(0,f.timeSync)("img.extractDominantColors",(()=>function(e,t=b.ModeCount){const i=Date.now(),n=y.Settings.dominantColorKmeansRuns.valueOrDefault,a=new d.CountingSet;for(const i of x({labs:e,minK:t}))a.incr((0,v.toLabhash)(i));const h=_[y.Settings.dominantColorDeltaE.valueOrDefault]??w.ciede2000_delta_e;const f=a.sortedByKey().valuesToA((e=>(0,v.unlabhash)(e)));let g=(0,l.round)(t+y.Settings.dominantColorMergeThreshold.valueOrDefault);function D(e){const i=t,n=4*t;g=Math.round(Math.max(i,Math.min(n,e)))}const C=f.length<=g?[]:(0,r.compact)(M.slice(0,n).map((e=>{const n=(0,p.kmeans)(f,g,{...E,seed:e}),r=k(n.centroids,f.length);if(r.lengtht&&D(g-1);const s=r.slice(0,t),o=(0,l.sigFigs)(function(e){const t=new m.Average;for(const[i,n]of a.entries()){const r=(0,v.unlabhash)(i),s=(0,c.leastByCtx)(e,(e=>h(e.centroid,r)));null!=s&&(0,l.times)(n,(()=>t.push(s.value)))}return t.p84}(s),2);return{...n,centroids:s,description:{kIn:g,kOut:n.centroids.length,kMerged:r.length,score:o,iterations:n.iterations,uniqColors:a.size,elapsedMs:Date.now()-i},score:o}})));P().trace("extractDominantColors()",{kmeansResults:C.map((e=>(0,u.pick)(e,"description","score")))});const F=(0,c.leastBy)(C,(e=>e.score));if(null==F)return P().info("kmeans failed or was disabled, using dominantColorsFromModes",{runs:n}),T(a,t);const O=(0,o.stringify)({...F?.description,elapsedMs:Date.now()-i}),I=(0,s.sortBy)(F?.centroids,(e=>-e.size)).map((e=>S.DominantColor.fromCentroid(e,f.length)));return P().debug("extractDominantColors() result",{description:O,score:F?.score,totalColors:a.size,totalPixels:f.length,iters:F?.iterations,dominantColors:(0,S.dominantColorsToRgbHex)(I),pixelCount:f.length}),{dominantColors:I,description:O,dominantColorScore:F?.score}}(e,t)))},t.centroidsScore=function(e,t){const i=new m.Average;for(const n of e){const e=(0,c.leastBy)(t,(e=>(0,w.ciede2000_delta_e)(e.centroid,n)));null!=e&&i.push((0,w.ciede2000_delta_e)(e.centroid,n))}return i};const M=[6147062518717073,8176726750919909,5426648081701673,0xce2a345532a3c,0x713f9716da824,6348935463312109,5900323173950995,7358780886584433,5704068712193493,0x51ceeef755892,0xe1557fe94c084,0xd42d7cc96d6b4,0xcbc36dfd76e8a,6738189173486085,8537822851166899,5390086061821835,7712057976331355,0xe9b820db7a8e4,0xb96cebcd6aa40,7036994544380825,5353634786120155,0x99a11417794bc,0xa93d36019aaae,0x74a470887095e,5481147022770415,5347523348244809,0x541d1098e90fc,0xa24d9fb3510c2,0x78aa8e4f692fa,6354921850669697,0x714e1ec1b0a14,8622097963014773,0x6ff5d462d8eb6,0x6782a6b5166b8,7128984079394103,0xe6efba28a3752,5088704486053871,0xc84df40627fae,8018285280412081,4524300326741245,8307147030534695,8135486835878813,7699950603263999,0xb2889592968ae,5903399874280295,7462660765348991,6442509751447017,0xe218d44834db6,7214173935589545,6001326758941961,0x53eb7d39bbb50,0xc3a7ab8add332,0x4e6e81bc443e2,6757635537583321,8501611905255957,0x51840465cc07c,5958243312989149,8928005021308717,5032083390680559,0xb35d70ac51c68,0xfc3826a2dfe7c,0xd155853c61e96,0xda2045ee9be1e,4753952745315177],_={cie76:w.cie76_delta_e,cie94:w.cie94_delta_e,ciede2000:w.ciede2000_delta_e},E=(0,n.lazy)((()=>({maxIterations:50,initialization:"kmeans++",distanceFunction:_[y.Settings.dominantColorDeltaE.valueOrDefault]})));function x({labs:e,minK:t,thresh:i,retries:n=3}){if(n<0)return P().debug("maybeFilterGrey(): exhausted retries: grey filtering disabled."),e;const r=i??y.Settings.dominantColorGreyThreshold.valueOrDefault;if(!(0,l.gt0)(r))return P().debug("maybeFilterGrey(): grey threshold is <= 0: grey filtering disabled."),e;const s=e.filter((e=>Math.abs(e[1])+Math.abs(e[2])>=r));return s.length>=e.length/2?(P().debug("maybeFilterGrey(): sufficient remaining pixels with this threshold.",{greyThreshold:r,minK:t,pixelCount:e.length,filteredCount:s.length}),s):(P().debug("maybeFilterGrey(): insufficient remaining pixels with this threshold. Retrying with smaller threshold.",{greyThreshold:r,minK:t,retries:n,pixelCount:e.length,filteredCount:s.length}),x({labs:e,minK:t,thresh:.75*r,retries:n-1}))}function T(e,t){const i=e.countSum,n=e.size;D(e);const s=e.size,a=(0,r.compact)(e.top(t).map((([e,t])=>S.DominantColor.fromLabhash({labhash:e,pct:Math.round(100*t/i)})))),l=100-(0,g.sumf)(a,(e=>e.pct));return{dominantColors:a,description:"dominantColorsFromModes: "+(0,o.stringify)({uniqColors:n,mergedColors:s,pixelCount:i,pctOmitted:l})}}function D(e,t=y.Settings.dominantColorMergeThreshold.valueOrDefault){const i=[];for(const[n,r]of[...e.entriesByCountDesc()]){const s=(0,v.unlabhash)(n),a=i.find((e=>(0,w.ciede2000_delta_e)(e.lab,s)<=t));null==a?i.push({lab:s,labhash:n}):(e.delete(n),e.incr(a.labhash,r))}return e}function k(e,t,i=y.Settings.dominantColorMergeThreshold.valueOrDefault){if(i<=0)return e;const n=[];for(const t of e){const e=n.find((e=>(0,w.ciede2000_delta_e)(t.centroid,e.centroid)<=i));null==e?n.push(t):e.size+=t.size}const r=t/100;return(0,s.sortBy)(n.filter((e=>e.size>r)),(e=>-e.size))}(0,a.later)((()=>{y.Settings.dominantColorDeltaE.watchLater((()=>{E.unset()}))})),t.maybeFilterGrey=x,t.dominantColorsFromModes=T,t.mergeLabhashes=D,t.mergeNearCentroids=k},85409:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Greys=void 0,t.Greys=[{name:"Black",rgb:"#000000"},{name:"90% black",rgb:"#1b1b1b"},{name:"80% black",rgb:"#303030"},{name:"70% black",rgb:"#474747"},{name:"60% black",rgb:"#5e5e5e"},{name:"Grey",rgb:"#777777"},{name:"60% white",rgb:"#919191"},{name:"70% white",rgb:"#ababab"},{name:"80% white",rgb:"#c6c6c6"},{name:"90% white",rgb:"#e2e2e2"},{name:"White",rgb:"#ffffff"}]},86758:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.labsAreGreyscale=t.isLab=void 0;const n=i(19851),r=i(31586),s=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,n.lazy)((()=>(0,s.mkLogger)("color.Lab")));t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,r.within)(0,100,e[0])&&(0,r.within)(-110,110,e[1])&&(0,r.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.greyscaleColorThreshold.valueOrDefault,i=new a.Average,n=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),n.push(e[2])}const r=(i.stdDev??0)+(n.stdDev??0),s=r{Object.defineProperty(t,"__esModule",{value:!0}),t.LightWikipediaColors=void 0,t.LightWikipediaColors=[{name:"Beige",rgb:"#F5F5DC"},{name:"Laurel green",rgb:"#A9BA9D"},{name:"Light sage",rgb:"#93A58B"},{name:"Light green-cyan",rgb:"#CFEADE"},{name:"Pastel purple",rgb:"#B39EB5"},{name:"Pewter blue",rgb:"#8BA8B7"},{name:"Powder blue",rgb:"#B0E0E6"},{name:"Vanilla",rgb:"#F3E5AB"}]},42022:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitModeData=t.pickModeData=t.ModeDataKeys=t.isModeData=void 0;const n=i(31586),r=i(68708),s=i(50989);t.isModeData=function(e){return(0,n.gt0)(e.mode0)&&(0,n.gt0)(e.mode0pct)},t.ModeDataKeys=(0,s.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct"),t.pickModeData=function(e){return(0,r.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,r.omit)(e,...t.ModeDataKeys.values)}},85042:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clampRGB=t.rgbTriplet2hex=t.rgbhex2triplet=t.normalizeRgbHex=void 0;const n=i(31586),r=i(39926),s=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map((e=>(0,n.clamp)(0,255,Math.round(e))))}t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,s.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map((e=>(0,n.clamp)(0,255,parseInt(e,16))))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map((e=>(0,r.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0"))).join("")},t.clampRGB=l},76596:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const n=i(51168),r=i(19851),s=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,r.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,(e=>e.getTime()),(()=>0)),n=(0,o.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(i,n)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0;const n=i(77988),r=i(19851),s=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,r.lazy)((()=>(0,l.concatRegexp)([/^/,/(?\d{2,}[-+\dTZ:.,]+?)/i,/(?:--|\/)/,/(?\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?\d+)\/(?\d+)/),/$/]))),h=["year","month","day","hour","minute","second","millisecond"];class f{static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),n=i?.groups;return null==n?void 0:f.for((0,c.parseExifDateTime)(n.start,t),(0,c.parseExifDateTime)(n.end,t),(0,a.toInt)(n.index),(0,a.toInt)(n.splits))}toJSON(){return{_ctor:"DateInterval",start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,s.map)(e.start,(e=>n.ExifDateTime.fromJSON(e))),(0,s.map)(e.end,(e=>n.ExifDateTime.fromJSON(e))),e.index,e.splits)}static for(e,t,i=0,n=1){if(null==e||!e.isValid||null==t||!t.isValid)return;n=(0,a.clamp)(1,1e3,(0,a.toInt)(n,{defaultValue:1})),i=(0,a.clamp)(0,n-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const r=e.toMillis(),s=(t.toMillis()-r)/(n+1)*(i+1),o=e.plus({milliseconds:s});return null==o?void 0:new f(e,o,t,i,n)}constructor(e,t,i,n=0,r=1){this.start=e,this.middle=t,this.end=i,this.index=n,this.splits=r,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map((n=>function({start:e,end:t,middle:i,field:n}){return null!=e[n]&&null!=t[n]?i[n]:void 0}({start:e,middle:t,end:i,field:n})))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToJson=t.isoToDated=t.datedOverlap=t.isoToPrecisionMs=t.datedToPrecisionMs=t.datedToDateTime=t.datedToStartDateTime=t.datedToEndTs=t.datedToStartTs=t.toDate=t.mapDated=t.toDated=t.isDated=void 0;const n=i(77988),r=i(51168),s=i(19851),a=i(76790),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(51926),f=i(50213),m=i(76596),p=i(24689),g=i(66649),y=i(98247),v=i(21330),w=i(928),S=i(54261),b=i(73389),P=i(51275),M=(0,s.lazy)((()=>(0,f.mkLogger)("date.Dated")));function _(e){return null!=e&&(e instanceof v.FuzzyDate||e instanceof n.ExifDate||e instanceof n.ExifDateTime||e instanceof Date||e instanceof p.DateInterval||(0,b.isDateTime)(e)||(0,m.isDateObject)(e))}function E(e){return null==e?void 0:e instanceof p.DateInterval?e.start.toMillis():e instanceof n.ExifDate?e.toMillis(0):(0,g.datedToMillis)(e)}function x(e){if(null!=e)return e instanceof p.DateInterval?e.end.toMillis():e instanceof n.ExifDate?e.toMillis(l.dayMs):e instanceof v.FuzzyDate?e.following().toMillis()-1:(0,c.map2Numeric)((0,g.datedToMillis)(e),D(e),((e,t)=>e+t))}function T(e){try{if(null==e||(0,h.isString)(e)||(0,c.isNumber)(e))return;return(0,b.isDateTime)(e)?e:e instanceof n.ExifDateTime||e instanceof v.FuzzyDate?e.toDateTime():e instanceof p.DateInterval?e.middle.toDateTime():e instanceof Date?r.DateTime.fromJSDate(e):(0,y.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void M().warn("datedToDateTime() failed",{d:e,error:t})}}function D(e){if(e instanceof p.DateInterval)return e.precisionMs;if((0,S.hasTime)(e)){if((0,c.gt0)((0,w.getMillisecond)(e)))return 0;if((0,c.gt0)((0,w.getSecond)(e)))return l.secondMs-1;if((0,c.gt0)((0,w.getMinute)(e)))return l.minuteMs-1;if((0,c.gt0)((0,w.getHour)(e)))return l.hourMs-1}return(0,c.gt0)((0,w.getDay)(e))?l.dayMs-1:(0,c.gt0)((0,w.getMonth)(e))?l.monthMs-1:l.yearMs-1}function k(e,t){const i=E(e),n=x(e);if(null!=i&&null!=n)return(0,c.gt0)(t)&&t>n-i?{start:Math.round((i+n)/2-t/2),end:Math.round((i+n)/2+t/2)}:{start:i,end:n}}function C(e,t,i,n){const[r,s]=(0,a.sortBy)([k(e,i),k(t,n)],(e=>e?.start));return null!=r&&null!=s&&null!=r&&null!=s&&(r.start===s.start||r.end>=Math.min(s.start,s.end))}function F(e,t){return(0,o.blank)(e)?void 0:p.DateInterval.fromISO(e,t)??(0,y.parseExifDateTime)(e,t)??v.FuzzyDate.fromISO(e)}t.isDated=_,t.toDated=function(e){return _(e)?e:void 0},t.mapDated=function(e,t){return _(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,d.maybeCall)(e,"toJSDate")??(0,d.maybeCall)(e,"toDate")},t.datedToStartTs=E,t.datedToEndTs=x,t.datedToStartDateTime=function(e){return e instanceof p.DateInterval?e.start.toDateTime():e instanceof n.ExifDate?r.DateTime.fromObject(e):T(e)},t.datedToDateTime=T,t.datedToPrecisionMs=D,t.isoToPrecisionMs=function(e){return(0,u.map)(F(e),D)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:n}){if(null==e||null==t)return!1;if(i??(i=D(e)),n??(n=D(t)),C(e,t,i,n))return!0;const r=(0,P.getZoneName)(e),s=(0,P.getZoneName)(t);return null==r&&null!=s&&(e=(0,v.setZone)(e,s)??e),null==s&&null!=r&&(t=(0,v.setZone)(t,r)??t),C(e,t,i,n)},t.isoToDated=F,t.datedToJson=function(e){const t=e.toJSON?.();return null!=t?t:e instanceof r.DateTime?{...e.toObject(),zone:e.zoneName}:e}},66649:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=void 0;const n=i(31586),r=i(81168);t.datedToMillis=function(e){if(null!=e&&!(0,r.isString)(e))return(0,n.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}},4328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const n=i(22573),r=i(31586),s=i(54557),a=i(91655),o=new s.FifoCache(512);function l(e){return(0,r.isNumber)(e)?e:(0,n.blank)(e)?void 0:o.getOrSet(e,(()=>(0,a.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,n.blank)(e)?void 0:u.getOrSet(e,(()=>(0,a.fmtFullDuration)((0,r.isNumber)(e)?e:l(e))))}},91655:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const n=i(51168),r=i(40958),s=i(22573),a=i(42659),o=i(31586),l=i(51926),u=i(68852),c=i(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,o.isNumber)(e))return;if((0,o.isNumber)(e))return e;if((0,o.isDigits)(e))return(0,o.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=n.Duration.fromISO(e);if(t.isValid)return t.toMillis();const i=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(i,e);if(0===d.length)return;const h=(0,r.compact)(d.map((e=>function(e,t){const i=(0,o.toFloat)(e);if(null!=i){if((0,s.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*a.yearMs;case"weeks":case"week":case"w":return i*a.weekMs;case"days":case"day":case"d":return i*a.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*a.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*a.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,o.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:a.yearMs,s:"y"},{ms:a.weekMs,s:"w"},{ms:a.dayMs,s:"d"},{ms:a.hourMs,s:"h"},{ms:a.minuteMs,s:"m"},{ms:a.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,i=""){if(!(0,o.isNumber)(t))return;if(0===t)return"0";if(!(0,o.gte0)(t))return(0,o.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const n=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&n.push(i+e.s)}return n.join(i)}},98247:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToExifDateTime=t.parseExifDateTimeRe=t.parseExifDateTime=t.parseExifDateTimeFromRFC2822=t.parseExifDateTimeFormat=t.concatDateTime=t.UnsetZone=void 0;const n=i(77988),r=i(51168),s=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(21330),p=i(98725),g=i(54261),y=i(17415);function v(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:r,month:s,day:a,hour:c,minute:h,second:p}=(0,d.mapEntries)(n.groups,((e,t)=>(0,l.toInt)(t)));if(null==r||null==s||null==a)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==c||null==h))return;const g=(0,o.map)((0,l.toFloat)(n.groups.subsec),(e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0)),v=(0,y.timezoneOffsetFromRegExpMatch)(n);return b({year:r,month:s,day:a,hour:c??0,minute:h??0,second:p??0,millisecond:g,zone:(0,m.zoneOffsetToName)(v)??i,rawValue:e,tzoffsetMinutes:v})}t.UnsetZone=r.Info.normalizeZone(n.UnsetZoneOffsetMinutes),t.concatDateTime=function(e,t){if(!(e instanceof n.ExifDate&&t instanceof n.ExifTime))return;const i=new n.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:i,defaultZone:s}){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromFormat(e,i,{zone:s??t.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:n.ExifDateTime.fromDateTime(r.DateTime.fromRFC2822(e,{zone:t.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:n.ExifDateTime.from(e,t)??v(e,S(),t)},t.parseExifDateTimeRe=v;const w=/[-:_\s]?/,S=(0,s.lazy)((()=>(0,h.concatRegexp)([p.nonNumericLookbackRE,p.yearRE,w,p.monthRE,w,p.dayRE,/[T\s]/,p.hourRE,w,p.minuteRE,w,p.secondRE,p.subsecRE,/\s?/,h.RegExpOptional.from((0,y.TimezoneOffsetRE)())])));function b(e){if(null!=e&&(0,g.hasTime)(e)){if(e instanceof n.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,y.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=n.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}t.dateObjectToExifDateTime=b},74417:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJsonDateToMillis=t.fmtDateShort=t.shortDateTimeFormat=t.isoToDateTime=t.fmtDateTime=t.recent=void 0;const n=i(51168),r=i(22573),s=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600);t.recent=function(e,t=5*s.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=n.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,(e=>((0,r.mapNotBlank)(t,(t=>e=e.setLocale(t))),e.toLocaleString(i))))};const p=/(\.\d\d\d)\d+/;t.isoToDateTime=function(e){if((0,r.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=n.DateTime.fromISO(e.replace(p,((e,t)=>t)),{setZone:!0});return t.isValid?t:void 0};const g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,(()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"})))}t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*s.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()}},12959:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filestampUTC=t.filestamp=void 0;const n=i(39926);t.filestamp=function(e=new Date){return[e.getFullYear(),(0,n.pad2)(e.getMonth()+1),(0,n.pad2)(e.getDate()),"-",(0,n.pad2)(e.getHours()),(0,n.pad2)(e.getMinutes()),(0,n.pad2)(e.getSeconds())].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,n.pad2)(e.getUTCMonth()+1),(0,n.pad2)(e.getUTCDate()),"-",(0,n.pad2)(e.getUTCHours()),(0,n.pad2)(e.getUTCMinutes()),(0,n.pad2)(e.getUTCSeconds())].join("")}},21330:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.utcToZone=t.toIsoDate=t.setZone=t.dateBetween=t.gtDated=t.closeTo=t.diffMillis=t.sameDay=t.toFuzzyDate=t.datedToYMD=t.datedToEXIF=t.datedToISO=t.datedToOffsetMinutes=t.toExifDateTime=t.zoneOffsetToName=t.clearIgnorableSubpaths=t.addIgnorableSubpath=t.ignorableSubpaths=t.FuzzyDate=void 0;const s=i(77988),a=i(51168),o=i(57975),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(19851),g=i(28874),y=i(24689),v=i(79842),w=i(66649),S=i(98247),b=i(98725),P=i(928),M=i(54261),_=i(73389),E=i(89724),x=i(17415),T=i(88600),D=i(51275);function k(e,t=2){return null==e?"":(0,m.leftPad)(e,t,"0")}class C{constructor(e,t,i){this.year=e,this.month=t,this.day=i,n.set(this,(0,p.lazy)((()=>(0,T.whyNotValidDate)(this.toDateTime()))))}static fromISO(e){if(!(0,u.blank)(e))return this.for(b.ISO_YMD_RE.exec(e)?.groups??b.ISO_YMD_LAX_RE.exec(e)?.groups)}toJSON(){return{_ctor:"FuzzyDate",...this}}static fromJSON(e){return this.for(e)}static for(e){const t=(0,h.toGt0)(e?.year);if(null==e||null==t||tk(e))).join("-")}toLocal(){return(0,E.datedToLocal)(this)}toDateTime(){return a.DateTime.fromObject((0,f.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}following(){const e=this.toDateTime(),t=null!=this.day?(0,f.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,f.pick)(e.plus({month:1}),"year","month"):(0,f.pick)(e.plus({year:1}),"year");return new C(t.year,t.month,t.day)}}function F(e,t){if(e instanceof s.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,M.hasTime)(e))return;const i=(0,u.mapNotBlank)(t,(t=>(0,x.zoneToTzOffsetMinutes)((0,w.datedToMillis)(e),t)));return null==t||null!=i?(0,d.map)((0,P.getYear)(e),(n=>(0,d.map)((0,P.getMonth)(e),(r=>(0,d.map)((0,P.getDay)(e),(s=>(0,d.map)((0,P.getHour)(e),(a=>(0,S.dateObjectToExifDateTime)({year:n,month:r,day:s,hour:a,minute:(0,P.getMinute)(e)??0,second:(0,P.getSecond)(e)??0,millisecond:(0,P.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))))))):void 0}t.FuzzyDate=C,t.ignorableSubpaths=[],t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.zoneOffsetToName=function(e,t=!0){if(null==e)return;if(0===e)return t?"UTC":"";const i=e<0?"-":"+",n=15*(0,h.round)(e/15),r=Math.abs(n),s=Math.floor(r/60),a=Math.floor(Math.abs(r%60));return`${t?"UTC":""}${i}${k(s)}:${k(a)}`},t.toExifDateTime=F,t.datedToOffsetMinutes=function(e){return(0,d.map)(e,(e=>e instanceof s.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0))},t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof y.DateInterval?e.toString({includeOffset:t}):!(0,M.hasTime)(e)||(i??(0,v.datedToPrecisionMs)(e))>=c.dayMs?L(e):F(e,(0,D.getZoneName)(e))?.toISOString({includeOffset:t})};const O="yyyy:MM:dd HH:mm:ss.SSS",I=O+"ZZ";function L(e,t="-"){return(0,l.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map((e=>k(e))).join(t)}function A(e){return(0,d.map)(e,(e=>(0,d.map)((0,P.getYear)(e),(t=>new C(t,(0,P.getMonth)(e),(0,P.getDay)(e))))))}function R(e,t){const[i,n]=[e,t].map(w.datedToMillis);return null==i||null==n?void 0:i-n}t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof y.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?a.DateTime.fromMillis(t):(0,v.datedToDateTime)(t);return null!=i&&i.isValid?i.toFormat((0,D.hasZone)(t)?I:O):void 0},t.datedToYMD=L,t.toFuzzyDate=A,t.sameDay=function(e,t){return(0,h.lte)(R(e,t),c.dayMs)},t.diffMillis=R,t.closeTo=function(e,t,i){return(0,d.mapOr)(R(e,t),(e=>Math.abs(e)!1))},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[P.getYear,P.getMonth,P.getDay,P.getHour,P.getMinute,P.getSecond,P.getMillisecond])if((0,h.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,n=1){if(null==(0,w.datedToMillis)(e)||null==(0,w.datedToMillis)(t))return;const[r,s]=[e,t].map((e=>(0,w.datedToMillis)(e))).sort(),o=(s-r)/(n+1),l=(0,D.getZoneName)(e),u=l===(0,D.getZoneName)(t)?l:void 0,c=a.DateTime.fromMillis(r+o*i,{zone:u});return[e,t].some((e=>!(0,M.hasTime)(e)))?A(c):c},t.setZone=function(e,t,i){const n={...(0,f.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,D.hasZone)(e)},r=(0,x.normalizeZone)(t);return null!=e&&null!=r&&(0,M.hasTime)(e)?e instanceof y.DateInterval?e.setZone(r,n):F(e)?.setZone(r,n):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)];return(0,h.gt0)(t[0])?(0,l.compact)(t).map(m.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,v.datedToDateTime)(e);if(null==i)return;const n=(0,D.getZoneName)(e);return null!=n&&"UTC"!==n||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)}},98725:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.parseDated=t.parseDateTime=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.agoMs=t.dateTimeBetween=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=t.parseFuzzyDate=t.parseYMD=t.extractDateFromPath=void 0;const o=i(77988),l=i(51168),u=i(19851),c=i(40958),d=i(22573),h=i(49769),f=i(31586),m=i(51926),p=i(59455),g=i(48884),y=i(50213),v=i(68852),w=i(4001),S=i(28874),b=i(24689),P=i(79842),M=i(66649),_=i(98247),E=i(21330),x=i(54261),T=i(73389),D=i(16400),k=i(88600),C=(0,u.lazy)((()=>(0,y.mkLogger)("date.FuzzyDateParser")));t.extractDateFromPath=function(e){return C().tap({msg:"extractDateFromPath",result:L.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return L.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return L.instance().parse(e)},t.nonNumericLookbackRE=/(?(?:19|20)\d{2})/,t.yearishRE=/(?(?:19|20)?\d{2})/,t.monthRE=/(?[0-3]\d)/,t.monthishRE=/(?[0-3]?\d)/,t.dayRE=/(?[1-3]\d|0[1-9])/,t.dayishRE=/(?[1-3]\d|0?[1-9])/,t.hourRE=/(?1\d|2[0-3]|0\d)/,t.minuteRE=/(?[0-5]\d)/,t.secondRE=/(?[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?\.\d+)?/,t.dateTimeBetween=function(e,t){return e.until(t).divideEqually(2)[0].end},t.agoMs=function(e){return(0,f.mapNumeric)((0,M.datedToMillis)(e),(e=>Date.now()-e))},t.ISO_YMD_RE=(0,v.concatRegexp)([/^/,t.yearRE,v.RegExpOptional.from(/-/,t.monthRE,v.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,v.concatRegexp)([/^/,t.yearishRE,v.RegExpOptional.from(/-/,t.monthishRE,v.RegExpOptional.from(/-/,t.dayishRE)),/$/]),t.parseDateTime=function(e,t){const i=I({input:e,defaultZone:t,descPredicate:e=>null!=e.match(/DateTime/i)});return(0,T.isDateTime)(i)?i:(0,x.isExifDateTime)(i)?i.toDateTime():void 0};const F=new Map;function O(e,t,i){try{const n=(0,_.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=n)return n;const r=(0,h.getOrSet)(F,t,(()=>{const e=l.DateTime.fromFormatExplain(l.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void C().warn("extractDateTime() failed to parse format",{format:t});const i=(0,m.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")}));return(0,_.parseExifDateTimeFormat)({input:r?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void C().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function I({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:n=!0,descPredicate:r=(()=>!0)}){if(null==e)return;if((0,P.isDated)(e))return e;const s=(0,c.uniq)((0,c.compactBlanks)((0,p.toA)(e)).map(w.stripDSC));if(0!==s.length)for(const{desc:e,f:a}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,_.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:_.parseExifDateTimeFromRFC2822};for(const t of(0,c.uniq)([...(0,c.compactBlanks)(S.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,c.compactBlanks)(S.Settings.extraDateTimeFormats.values)){const n=(0,d.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${n})`,f:i=>O(i,n,(0,d.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromEXIF",f:e=>o.ExifDate.fromEXIF(e)}),!0===e.includeFuzzyDate)for(const e of L.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:n}))if(r(e))for(const e of s){const t=a(e);if(null!=t&&(0,k.isValidDate)(t))return t}}t.parseDated=I;class L{constructor(e={}){n.add(this),this.opts=e,this.ymdParsers=[],this.ymParsers=[],this.yParsers=[],this.allParsers=[],null==e.fuzzyDateParsing&&S.Settings.fuzzyDateParsing.watchLater((()=>a(this,n,"m",s).call(this))),null==e.fuzzyYearParsing&&S.Settings.fuzzyYearParsing.watchLater((()=>a(this,n,"m",s).call(this))),a(this,n,"m",s).call(this)}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??S.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??S.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}extractDateFromPath(e){if(!S.Settings.usePathsToInferDates.valueOrDefault)return;E.ignorableSubpaths.forEach((t=>{(0,c.startsWith)(e,t)&&e.splice(0,t.length)})),e=e.filter((t=>(0,d.notBlank)(t)&&null==e[0].match(R)));const t=[...e].reverse();for(const e of t){const t=I({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,g.first)(t,(e=>this.parseYM(e)))??this.parseYM(e.join(" "))??(0,g.first)(t.slice(1),(e=>this.parseY(e)))}}t.FuzzyDateParser=L,n=new WeakSet,r=function(e){const t=new A(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)},s=function(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new v.RegExpEscaped("(?"+(0,D.monthNames)().map(v.escapeRegExp).join("|")+")");a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,t.monthRE,/\2/,t.dayRE]),a(this,n,"m",r).call(this,[t.yearRE,t.optSeps,e,/\2/,t.dayishRE]),a(this,n,"m",r).call(this,[e,t.optSeps,t.dayishRE,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,/,?\2/,t.yearRE]),a(this,n,"m",r).call(this,[/^(?\d\d\d\d):(? {2}|\d\d):(? {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,t.monthishRE]),a(this,n,"m",r).call(this,[e,t.seps,t.yearRE]),a(this,n,"m",r).call(this,[t.yearRE,t.seps,e]),a(this,n,"m",r).call(this,[t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){console.error(e)}},L.instance=(0,u.lazy)((()=>new L));class A{constructor(e){this.regex=e instanceof RegExp?e:(0,v.concatRegexp)([...e,/(?:$|\D)/],"i")}get source(){return this.regex.source}get hasDay(){return this.source.includes("(?")}get hasMonth(){return this.source.includes("(?")||this.source.includes("(?")}apply(e){const t=this.regex.exec(e)?.groups;if(null!=t)return E.FuzzyDate.for({year:(0,f.toInt)(t.year),month:(0,f.toInt)(t.month)??(0,D.monthName2index)(t.monthname),day:(0,f.toInt)(t.day)})}}const R=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSecMs=t.hasSeconds=t.getCentisecond=t.getMillisecond=t.getSecond=t.getMinute=t.getHour=t.getDay=t.getMonth=t.getYear=void 0;const n=i(55835),r=i(31586),s=i(54261);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,n.map)(l(e),(e=>Math.floor(e/10)))},t.hasSeconds=function(e){return(0,s.hasTime)(e)&&((0,r.gt0)(a(e))||(0,r.gt0)(o(e))||(0,r.gt0)(l(e)))},t.getSecMs=function(e){return(0,n.map)(o(e),(t=>{const i=l(e)??0;let n=(t+i/1e3).toString();for(t<10&&(n="0"+n),0===i&&(n+=".");n.length<6;)n+="0";return n}))}},54261:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isExifDateTime=t.hasTime=void 0;const n=i(77988),r=i(31586),s=i(68708);t.hasTime=function(e){if(!(0,s.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,r.gt0)(t.hour)||(0,r.gt0)(t.minute)||(0,r.gt0)(t.second)||(0,r.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof n.ExifDateTime}},73389:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=void 0;const n=i(51168);t.isDateTime=function(e){return n.DateTime.isDateTime(e)??!1}},89724:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localPlusMs=t.tsToLocal=t.agoLocal=t.nowLocal=t.localToTs=t.localToDateTime=t.fmtLocalDateShort=t.localToDateObject=t.datedToLocalSec=t.datedToLocal=t.maybeDatedToLocal=t.isoToLocal=t.localIsFuzzy=void 0;const n=i(51168),r=i(19851),s=i(42659),a=i(55835),o=i(31586),l=i(28874),u=i(76596),c=i(79842),d=i(66649),h=i(74417),f=i(21330),m=i(928),p=i(54261),g=i(17415),y=(0,r.lazy)((()=>v(l.Settings.datesBeforeAreEstimated.valueOrDefault)??v(l.Settings.datesBeforeAreEstimated.defaultValue)));function v(e){return(0,a.map)((0,c.isoToDated)(e),w)}function w(e){return(0,o.isNumber)(e)?_(e):100*S(e)+((0,m.getCentisecond)(e)??0)}function S(e){if((0,o.isNumber)(e))return Math.floor(_(e)/100);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute,m.getSecond])t=100*t+(i(e)??0);return t}function b(e,t){if(null==e||e<0)return;let i=e;const n=()=>{const e=i%100;return i=Math.floor(i/100),e},r=10*n(),s=n(),a=n(),l=(0,o.toGt0)(n()),u=(0,o.toGt0)(n()),c=(0,o.toGt0)(n());return{year:i,month:c,day:u,hour:l,minute:a,second:s,millisecond:r,zone:(0,g.normalizeZone)(t)}}function P(e,t){const i=b(e,t);return(0,p.hasTime)(i)?(0,u.dateObjectToDateTime)(i):f.FuzzyDate.for(i)}function M(e,t){return _(Date.now()-e,t)}function _(e,t){return w(n.DateTime.fromMillis(e,{zone:t}))}t.localIsFuzzy=function(e){return null==e||e%1e6==0||e{Object.defineProperty(t,"__esModule",{value:!0}),t.monthNames=t.monthName2index=void 0;const n=i(19851),r=i(76790),s=i(31586),a=i(9092),o=(0,n.lazy)((()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const n=new Intl.DateTimeFormat(t,{month:i});(0,s.times)(12,(r=>{const s=n.format(new Date(2017,r));e.set(s,r+1),"short"===i&&"en-US"===t&&e.set(s+".",r+1)}))}}return e}));t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,r.sort)([...o().keys()])}},17415:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.luxonTzOffsetToOffsetMinutes=t.ianaZoneToOffsetMinutes=t.timezoneOffsetFromRegExpMatch=t.isoToOffsetMinutes=t.TimezoneOffsetRE=t.zoneToExifOffsetMinutes=t.fmtOffsetMinutes=t.zoneToTzOffsetMinutes=t.zoneOffsetMinutes=t.normalizeZone=t.isUTCZone=t.toValidIanaZone=t.isValidZone=t.normalizeZoneOffsetMinutes=t.offsetToMinutes=t.ValidTimezoneOffsets=t.MaxTzOffsetHours=void 0;const n=i(77988),r=i(51168),s=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(39926),d=i(51926),h=i(54993),f=i(48884),m=i(68852);function p(e){const[t,i]=e.split(":").map(Number);return(e.startsWith("-")?-1:1)*(60*Math.abs(t)+i)}t.MaxTzOffsetHours=14,t.ValidTimezoneOffsets=["-12:00","-11:00","-10:30","-10:00","-09:30","-09:00","-08:30","-08:00","-07:30","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","-01:00","-00:44","+00:00","+00:20","+00:30","+01:00","+01:24","+01:30","+02:00","+02:30","+03:00","+03:30","+04:00","+04:30","+04:51","+05:00","+05:30","+05:40","+05:45","+06:00","+06:30","+07:00","+07:20","+07:30","+08:00","+08:30","+08:45","+09:00","+09:30","+09:45","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"],t.offsetToMinutes=p;const g=(0,s.lazy)((()=>t.ValidTimezoneOffsets.map(p)));function y(e,i=14){if(!(0,l.isNumber)(e)||Math.abs(e)>60*t.MaxTzOffsetHours)return;const n=(0,f.leastBy)(g(),(t=>Math.abs(t-e)));return null!=n&&Math.abs(n-e)=0?"+":"-")+(0,c.pad2)(i)+":"+(0,c.pad2)(n)}t.isUTCZone=function(e){return S(e)||0===b(e)?.offset(Date.now())},t.normalizeZone=b,t.zoneOffsetMinutes=function(e){return y(e.tzoffsetMinutes)??y(e.offset)??(0,o.map)(e.zone,(t=>t.offset(e.toMillis())))},t.zoneToTzOffsetMinutes=P,t.fmtOffsetMinutes=M,t.zoneToExifOffsetMinutes=function(e,t){const i=P(e,t);return null==i?void 0:M(i)};const _=/\b(?Z|UTC|GMT)\b/,E=/(?[-±+−])/,x=/[-−]/,T=/(?[01]\d)/,D=/(?[01]?\d)/,k=/(?::(?\d\d))/;function C(e){return S(e)?0:F((0,t.TimezoneOffsetRE)().exec(e))}function F(e){if(null==e||(0,u.isEmptyObj)(e.groups))return;if(!(0,a.blank)(e.groups.utc))return 0;const t=(0,l.toInt)(e.groups.tzHour),i=x.test((0,h.toS)(e.groups.tzSign))?-1:1,n=(0,l.toInt)(e.groups.tzMinutes)??0,r=null==t?void 0:i*(60*t+n);return v(r)?r:void 0}t.TimezoneOffsetRE=(0,s.lazy)((()=>(0,m.concatRegexp)([new m.RegExpEscaped("(?:"),_,new m.RegExpEscaped("|"),E,T,m.RegExpOptional.from(k),new m.RegExpEscaped(")"),/(?:$|[^-−+:_\d.T/])/]))),t.isoToOffsetMinutes=C,t.timezoneOffsetFromRegExpMatch=F;const O=/\b(?(?:Etc\/)?GMT)\b/,I=(0,s.lazy)((()=>(0,m.concatRegexp)([O,E,D,m.RegExpOptional.from(k)])));function L(e){return F(I().exec(e))}t.ianaZoneToOffsetMinutes=L,t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,a.blank)(e))return;const i=L(e)??C(e);if(null!=i)return M(i);if(null!=t){const i=b(e);if(null!=i)return M(i.offset(t))}}},88600:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validYMD=t.mapValidDate=t.whyNotValidDate=t.isValidDate=t.toValidMillis=void 0;const n=i(51168),r=i(19851),s=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(21330),g=i(928),y=i(89724),v=(0,r.lazy)((()=>(0,c.mkLogger)("date.ValidDate"))),w=(0,r.lazy)((()=>(0,s.compact)(h.Settings.badDates.values.map((e=>(0,f.isoToDated)(e)))))),S=(0,r.lazy)((()=>(0,s.compact)(w().map((e=>(0,p.datedToISO)(e)))))),b=(0,r.lazy)((()=>(0,s.compact)(w().map((e=>(0,y.datedToLocal)(e)))))),P=(0,r.lazy)((()=>(0,s.compact)(w().map((e=>(0,m.datedToMillis)(e))))));function M(e){if(null==e)return!1;const t=E(e);return v().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}t.toValidMillis=function(e){return M(e)?e:void 0},t.isValidDate=M;const _=String(new Date("bad"));function E(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===_)return _;const t=(0,s.compact)([e.invalidExplanation]);if(0===t.length&&t.push(...function(e,t,i){const r=[];if((0,l.isNumber)(e)||r.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&r.push("year is less than "+h.Settings.minValidYear.key),(0,u.gt)(e,x())&&r.push("year is in the future"),null==t&&null!=i&&r.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&r.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&r.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const s=n.DateTime.fromObject({year:e,month:t,day:i});s.isValid||r.push(s.invalidExplanation??"not valid")}return(0,s.compact)(r)}((0,g.getYear)(e),(0,g.getMonth)(e),(0,g.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&t.push("not valid js Date"),0===t.length){const i=h.Settings.maxValidFutureMs.valueOrDefault;if((0,l.gt0)(i)){const n=(0,m.datedToMillis)(e);(0,u.gt)(n,Date.now()+i)&&t.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}}return P().includes((0,m.datedToMillis)(e))?t.push("bad date (via millis)"):b().includes((0,y.datedToLocal)(e))?t.push("bad date (via localtime)"):S().includes((0,p.datedToISO)(e))&&t.push("bad date (via ISO)"),(0,a.toNotBlank)((0,s.uniq)((0,s.compactBlanks)(t)).join("; "))}catch(t){return v().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.whyNotValidDate=E;const x=(0,r.lazy)((()=>n.DateTime.now().plus({milliseconds:h.Settings.maxValidFutureMs.valueOrDefault}).year),o.dayMs);t.mapValidDate=function(e,t){return M(e)?t(e):void 0},t.validYMD=function(e,t,i){return null==E({year:e,month:t,day:i})}},51275:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getZoneName=t.hasZone=void 0;const n=i(77988),r=i(31586),s=i(24689),a=i(73389);t.hasZone=function(e){return null!=e&&!(0,r.isNumber)(e)&&(e instanceof s.DateInterval||e instanceof n.ExifDateTime?e.hasZone:!!(0,a.isDateTime)(e)&&null!=e.zone&&e.zone.isValid&&"local"!==e.zone.type&&e.zone.name!==n.UnsetZoneName&&e.zone.offset(Date.now())!==n.UnsetZoneOffsetMinutes)},t.getZoneName=function(e){return null==e||e instanceof Date?void 0:(0,a.isDateTime)(e)?e.zoneName===n.UnsetZoneName?void 0:e.zone?.name:e instanceof n.ExifDateTime?e.zone:void 0}},84248:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const n=i(50989);t.AutoVacuumModes=(0,n.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const n=i(50989);t.CheckpointTypes=(0,n.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const n=i(50989);t.RepairModes=(0,n.strEnum)("dump","recover")},15056:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupDir=t.pathToDb=t.pathToDbDir=t.Schemas=void 0;const n=i(50989),r=i(7311);function s(e,t){return e.join(t)}t.Schemas=(0,n.strEnum)("models"),t.pathToDbDir=s,t.pathToDb=function(e,t){return s(e,t).join(r.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")}},7311:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const n=i(50989);t.SynchronousModes=(0,n.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const a=s(i(76760)),o=i(40958),l=i(22573),u=i(55835),c=i(72993),d=i(19851),h=i(97352),f=i(94174),m=i(44198),p=i(96706),g=i(8769),y=i(57159),v=i(70698),w=i(64680),S=i(29882),b=i(45969),P=i(43334),M=i(28874),_=i(41692),E=i(32774),x=i(80612),T=i(32551),D=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function k(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+D(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,p.getEnv)("TEMP"),(0,p.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const i of t)(0,l.blank)(i)||e.push({dir:(0,a.join)(i,".photostructure-cache"+D()),preexistingDir:i});return e}}function C(){if((0,b.isDocker)())return(0,o.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,a.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:E.DefaultDockerLibraryDir+"/.photostructure/cache"+D(),preexistingDir:E.DefaultDockerLibraryDir},...k()]);const e=(0,o.compactBlanks)(P.isWin?[(0,p.getEnv)("LOCALAPPDATA"),a.default.resolve((0,T.homeDir)(),"AppData","Local")]:P.isMac?[a.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,a.join)((0,T.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,i=e.map((e=>({dir:(0,a.join)(e,t),preexistingDir:e})));return i.push(...k()),i}t.tmpCacheDirs=k,t.tmpDirs=function(){return(0,x.filterDirs)({dirs:k(),desc:"tmp"})},t.cacheDirs=C,t.defaultCacheDir=(0,d.lazy)((()=>(0,x.firstDir)({dirs:C(),desc:"cache"})));const F=(0,d.lazy)((()=>{(0,_.setSettingsDefaults)(),M.Settings.cacheDir.watchLater(O)}));function O(){M.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,g.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{F();const e=M.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=O},46292:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const n=i(19851),r=i(45969),s=i(41692),a=i(32774),o=i(10924),l=i(84373),u=i(80612);t.configDir=(0,n.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,r.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,o.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:a.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:a.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,r.isDocker)()?c:(0,o.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const n=i(66430),r=i(45969),s=i(32774);t.defaultLibraryDir=function(){return(0,r.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,r.isDocker)()&&(0,n.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const r=n(i(76760)),s=i(40958),a=i(72993),o=i(44198),l=i(96706),u=i(43334),c=i(80612),d=i(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),r.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(r.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,o.env)().XDG_DATA_HOME,(0,o.env)().XDG_CONFIG_HOME,r.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:r.default.join(e,(0,a.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const n=i(22573),r=i(96706),s=i(29882);t.envConfigDir=function(){const e=(0,r.getEnv)("PS_CONFIG_DIR");if(!(0,n.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const n=i(44652),r=i(40958),s=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,r.compact)(e))if(!(0,s.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,s.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,n.mkdirpSync)(i),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,r.compact)(e.map((e=>o({dirs:[e],desc:t}))))}},32551:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const n=i(48161),r=i(76760),s=i(1708),a=i(19851),o=i(40958),l=i(68284),u=i(43334);t.homeDir=(0,a.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,o.compactBlanks)(e)){const e=(0,r.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,n.homedir)()}))},35280:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.inHiddenPhotoStructureDir=void 0;const n=i(29882),r=i(49776),s=i(9595);t.inHiddenPhotoStructureDir=function(e){if((0,n.toPathnames)(e).some((e=>e.toLowerCase().startsWith(".photostructure"))))return!0;for(const t of[s.libraryDataDir,s.libraryPreviewsDir,r.cacheDir])if((0,n.containedByNativePath)({descendant:e,ancestor:t(),acceptSelf:!0}))return!0;return!1}},9595:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.libraryPreviewsDir=t.libraryDataDir=t.originalsDir=t.libraryDir=void 0;const n=i(22573),r=i(54993),s=i(29882),a=i(28874);function o(e){return(0,n.toNotBlank)((0,r.toS)(e))??a.Settings.libraryDir.valueOrDefault}t.libraryDir=o,t.originalsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.originalsDir.valueOrDefault)},t.libraryDataDir=function(e){return(0,s.resolveMaybe)(o(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,s.resolveMaybe)(o(e),a.Settings.previewsDir.valueOrDefault)}},87290:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLibraryDbDir_=t.setupLibrarySyncReportsDir_=t.librarySyncReportsDir=t.setupLibraryPreviewsDir_=t.libraryPreviewsDirPosixFile=t.setupLibraryOriginalsDir_=t.libraryOriginalsDirPosixFile=t.setupLibraryDataDir_=t.setupLibraryDirs_=t.libraryDataDirPosixFile=t.libraryDirPosixFile=void 0;const n=i(40958),r=i(55835),s=i(37805),a=i(15056),o=i(38835),l=i(64680),u=i(95696),c=i(73428),d=i(13940),h=i(28874),f=i(9595),m=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit https://forum.photostructure.com .\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${s.version}\n`;function p(e){return u.PosixFile.forMaybe((0,f.libraryDir)(e))}function g(e){return u.PosixFile.forMaybe((0,f.libraryDataDir)(e))}async function y(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function v(e){const t=g(e);if(null==t)throw new Error("empty libraryDataDir"+o.NoLibraryErrorFlag);await y(t),await(0,l.mkNoMedia_)(t);const i=t.join("README.txt");return await(0,c.writeTextfile_)(i.nativePath,m),t}function w(e){return u.PosixFile.forMaybe((0,f.originalsDir)(e))}async function S(e){return y(w(e),!1)}function b(e){return u.PosixFile.forMaybe((0,f.libraryPreviewsDir)(e))}async function P(e){return y(b(e))}function M(e){return p(e)?.join(h.Settings.syncReportsDir.valueOrDefault)}async function _(e){return y(M(e))}async function E(e){return y((0,r.map)(g(e),(e=>(0,a.pathToDbDir)(e,a.Schemas.models))))}t.libraryDirPosixFile=p,t.libraryDataDirPosixFile=g,t.setupLibraryDirs_=async function(e){const t=p(e);await y(t,!1);const i=await v(t);return(0,n.uniq)([t,i,await S(t),await P(t),await _(t),await E(t),await(0,d.imageCacheDir_)()])},t.setupLibraryDataDir_=v,t.libraryOriginalsDirPosixFile=w,t.setupLibraryOriginalsDir_=S,t.libraryPreviewsDirPosixFile=b,t.setupLibraryPreviewsDir_=P,t.librarySyncReportsDir=M,t.setupLibrarySyncReportsDir_=_,t.setupLibraryDbDir_=E},46296:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const r=n(i(76760)),s=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(54993),c=i(72993),d=i(96706),h=i(45969),f=i(43334),m=i(32707),p=i(6707),g=i(49776),y=i(32774),v=i(80612),w=i(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:r.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,a.compact)((0,g.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>r.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,o.notBlank)(e))return e;const t=(0,p.readTomlFileSync)((0,m.systemSettingsFile)()),i=(0,u.toS)(t?.logDir);return(0,o.notBlank)(i)?i:b()}catch(e){return console.error("defaultLogDir_() failed",e),r.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const n=i(76760),r=i(19851),s=i(22573),a=i(44198),o=i(43334),l=i(24399),u=i(32551);async function c(){return o.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,r.lazy)((async()=>{if(o.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,r.lazy)((()=>(0,a.env)().XDG_PICTURES_DIR??(0,n.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const n=i(38639),r=i(7282),s=i(29325),a=i(44198);t.getDevEnvFlag=function(e){return!(0,r.isProd)()&&!(0,s.isPacked)()&&((0,n.toBoolean)((0,a.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,a.env)()[e]=String(t)}},34580:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const n=i(38639),r=i(44198);t.doNotTrack=function(){return(0,n.isTrue)((0,r.env)().DO_NOT_TRACK)}},44198:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const r=n(i(73024)),s=i(76760),a=n(i(1708)),o=i(19851),l=i(40958),u=i(41400),c=i(68708),d=i(76850),h=i(7282),f=i(23560),m=i(32551),p=i(34102),g=i(53265),y=i(45969),v=i(59958),w=i(6012),S=i(96706);t.env=(0,o.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>a.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===a.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),i={...a.default.env};for(const n of e)try{const e=(0,d.debom)(r.default.readFileSync((0,g.resolve)(n))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,n]of(0,c.entries)(s))t.test(e)||(i[e]=n)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+n,e)}return i})),(0,u.later)((()=>{(0,p.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const n=i(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,n.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const n=i(50989);t.EnvKeys=(0,n.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const n=i(22573),r=i(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const i={};if((0,n.blank)(e))return i;let s;for(const a of(0,r.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(a));){if(null==s.groups)continue;const{key:e,val:r}=s.groups;if((0,n.blank)(e)||null==r)continue;const a=r.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");i[t?e.toLowerCase():e]=a}}return i}},96706:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const r=n(i(1708)),s=i(19851),a=i(22573),o=i(38639),l=i(41400),u=i(40583),c=i(79840),d=i(83556),h=i(34102),f=i(44198),m=i(83373);function p(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function g(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,a.firstNotBlank)(r.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,r.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=p,(0,l.later)((()=>{f.env.watchLater(p),(0,h.ee)().on("clearCache",p)})),t.getEnv=g,t.isEnvTrue=function(e){return(0,o.isTrue)(g(e))}},98314:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const n=i(58587),r=i(19851),s=i(40958),a=i(22573),o=i(26905),l=i(96249),u=i(51926),c=i(23541),d=i(54993),h=i(89788),f=i(50213),m=i(81168),p=i(84542),g=i(41954),y=i(38835),v=i(70025),w=i(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,g.getErrorDescriptions)(e));const i=[...e.filter(c.isError).map(o.errorName),...e.map(o.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,p.splitCompactLines)(e))).flatMap((e=>e.split(o.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(i)))}function b(e){return(0,s.compact)(e).filter((e=>!o.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(a.notBlank)}function P(e,t){const i=(0,s.uniqSubstrings)(b(e)),n=t?.maxLen??400,r=t?.trailingChars??64,a=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(i.join(o.ErrorDelimiter)),n-a.length,r)+a.sort().join("")}function M(e,t){return e instanceof w.WrappedError?e.toString():(0,a.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,r.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new n.Rate,t.fatalErrorRate=new n.Rate,t.internalErrorRate=new n.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(M(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,a.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const i=(0,d.toS)(t?.[e]);if((0,a.notBlank)(i))return i}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=M,t.MissingError="(missing error)",t.errorToVerbose=function(e,i=256,n=7){return(0,a.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,o.shortStack)(e?.stack,n).join("; ")}},41954:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const n=i(40958),r=i(26905),s=i(55835),a=i(54993),o=i(81168);t.describeError=function(e){const t=(0,o.stripSuffix)((0,a.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,s.map)((0,r.errorErrno)(i),(e=>t.push(u.get(e)))),(0,s.map)((0,r.errorCode)(i),(e=>t.push(l[e]?.description)));return(0,n.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const n=i(40958),r=i(76790),s=i(50989),a=i(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,r.sortBy)((0,n.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const n=i(40958),r=i(38639),s=i(26905),a=i(54993),o=i(68852),l=i(73568),u=i(78656),c=i(98314),d=i(38835);function h(e){return(0,a.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const i=(0,a.toS)(e)+(0,n.compact)(t).join("");return h(i)+f(i).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const p=/Can't write [a-z\d]+ files/i,g=(0,o.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,c.errorToS)(e);return!p.test(i)&&(!!g.test(i)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,r.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const i=(0,c.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const i=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>i.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,r.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,r.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},51837:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const n=i(38835);class r extends Error{constructor(e){super(e+n.InternalErrorFlag)}}t.InternalError=r},8769:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const n=i(22573),r=i(31586),s=i(68708),a=i(7282),o=i(23560),l=i(45608),u=i(34102),c=i(28874),d=i(98314),h=i(38835),f=i(70025),m=i(57159),p=i(5012);function g(e,t){try{if((0,n.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,p.stack)()),!1;const i=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const r=!0===i.fatal,c=!0===i.ignorable;if(!r&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),r&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",i));const h=!r||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:i}),!r||(0,a.isTest)()||(0,o.isWebService)()||(0,l.exit)({reason:i.toString(),status:i.errno??13}),r}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,r.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,o.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,r.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,r.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=g,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,i){return g(e+h.InternalErrorFlag,{cause:t,...i})}},57159:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const n=i(40958),r=i(22573),s=i(38639),a=i(26905),o=i(98553),l=i(68708),u=i(59455),c=i(41583),d=i(48884),h=i(81168),f=i(98314),m=i(38835),p=i(70025);t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof g&&(null==t||(0,r.blank)(i.message)||e.message.includes(i.message)))return e;const n=(0,r.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,i?.message);return new g(n??"(missing error message)",i)};class g extends Error{constructor(e,t={}){super(e),this.causes=(0,n.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,a.errorName)(t)??(0,d.first)(this.causes,a.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(a.errorCode)],a.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,a.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,r.toNotBlank)(e.path))),this.flags=t?.flags??[];const i=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??i.some(p.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(i.map(p.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(i.map(p.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(i.map(p.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,p.stripErrorFlags)(function(e,t){let i=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const n=t?.path;return(0,r.blank)(n)||(i=(0,h.dedupeNeedle)(i,n,"file")),(0,f.joinErrorMessages)([i[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,o.stringify)(t.meta):void 0,...i.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new g(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=g},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const a=i(49769),o=i(55835),l=i(54993),u=i(22911),c=i(89788),d=i(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,n.set(this,new Map),r.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,a.getOrSet)(s(this,n,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,o.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const i=this.target.emit(e,...t),a=s(this,n,"f").get(e);return null!=a&&(a.resolve(t),s(this,n,"f").delete(e)),i}emitDebounced(e,...t){(0,o.map)(s(this,r,"f").get(e),clearTimeout),s(this,r,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},n=new WeakMap,r=new WeakMap},34102:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const n=i(78474),r=i(19851),s=i(15197);t.ee=(0,r.lazy)((()=>{const e=new n.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const r=n(i(73024)),s=n(i(1708)),a=i(19851),o=i(22573),l=i(65843),u=i(16287),c=i(43334),d=(0,a.lazy)((()=>s.default.geteuid?.())),h=(0,a.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,o.blank)(e)&&(r.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,r.default.constants.R_OK|r.default.constants.W_OK):g({stat:e,r:!0,w:!0,x:!0})}function p(e,t){return c.isWin?f(t,r.default.constants.R_OK):g({stat:e,r:!0,x:!0})}function g({stat:e,r:t=!1,w:i=!1,x:n=!1,processUid:r,processGid:s}){if(null==e)return!1;const a=r??d(),o=null!=s?[s]:h()??[],l=0===a,u=l||e.uid===a,f=l||o.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!n||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=p,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,l.selfAndAncestorG)(e)){const n=await(0,u.statMaybe)(i);if(null!=n){if(!n.isDirectory())return!1;if(t){if(!p(n,e))return!1}else if(t=!0,!m(n,e))return!1}}return!0},t.access=g},21144:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const r=n(i(76760)),s=i(19851),a=i(81168),o=i(57159),l=i(43334),u=i(88561),c=i(29882),d=i(65238),h=i(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const i=(0,c.parseNativePath)((0,h.resolve)(...e)),n=await m(i.dir);for(const e of await(0,d.readdir_)(n))if((0,a.equalsIgnoreCase)(e.basename,i.base))return r.default.join(n,e.basename);throw new o.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const n=i(73024),r=i(76760);function s(e){return[...a(e)]}function*a(e){for(;e!==(0,r.dirname)(e);)e=(0,r.dirname)(e),yield e}function o(e){try{return(0,n.readdirSync)(e)}catch(e){return[]}}function l(e,t){const i=o(e);return t.every((e=>i.includes(e)))}t.ancestors=s,t.ancestorG=a,t.selfAndAncestorG=function*(e){yield e,yield*a(e)},t.childrenSync=o,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,i){var n,r,s,a,o,l=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&l(t,e,i);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(i(44652)),p=c(i(73024)),g=i(51455),y=f(i(76760)),v=f(i(1708)),w=i(46466),S=f(i(57975)),b=f(i(38522)),P=i(19851),M=i(40958),_=i(5233),E=i(22573),x=i(42659),T=i(50357),D=i(96249),k=i(98553),C=i(55835),F=i(31586),O=i(68708),I=i(97790),L=i(39926),A=i(51926),R=i(59455),N=i(54993),B=i(48884),z=i(22911),j=i(99331),V=i(56519),W=i(56038),H=i(31562),U=i(76850),q=i(70025),G=i(34102),$=i(80875),J=i(50213),K=i(70417),Z=i(43334),X=i(81168),Y=i(96859),Q=i(65162),ee=i(94174),te=i(64660),ie=i(21144),ne=i(84542),re=i(89968),se=i(20197),ae=i(88561),oe=i(50597),le=i(33456),ue=i(29882),ce=i(78133),de=i(43899),he=i(65238),fe=i(53265),me=i(17217),pe=i(16287),ge=i(68284),ye=i(66003),ve=i(27794),we=i(73428),Se=i(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new ae.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(n.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,J.mkLogger)("fs.BaseFile("+this.nativePath+")"))),r.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),a.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(r=new WeakMap,a=new WeakMap,n=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,M.compact)(e),i=await Promise.all(t.map((e=>e.shaMs())));return t[(0,B.leastIndex)(i)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const i=(0,me.isSimpleFile)(e)?e.nativePath:(0,N.toS)(e);if((0,E.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const n=be().get(i);if(null!=n)return n;const r=(0,fe.resolve)(i),s=new Pe(r,t);return be().set(i,s),be().set(r,s),s}static clear(e){(0,G.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(re.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,G.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,r,"f").unset(),h(this,a,void 0,"f"),this}clearThisAndParent(){return(0,G.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,X.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,V.thenMap)(this.stat(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,C.map)(this.statSync(),(e=>new re.DirectoryEntry(this.dir,new re.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,r,"f").call(this);if(null==t||null==e||(0,M.isEmpty)(t))return t;const i=[];for(const n of t)!0===await e(n)&&i.push(n);return i}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,V.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,n,"m",s).call(this)??await d(e=this.clearThisAndParent(),n,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,M.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>p.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,M.isNotEmpty)(e)?(0,M.includesAll)(t,e):(0,M.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,M.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,V.thenMap)(this.children(),(async t=>{for(const i of t)await i.visitDescendants(e),await e(i)}))}async descendants(e){const t=[];t.push(...(0,R.toA)(await this.childFiles(e)));const i=await this.childDirectories();if(null==i)return t;for(const n of i)t.push(...(0,R.toA)(await n.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,F.gt0)(t))return;const i=await d(this,r,"f").call(this)??[];for(const t of i)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const n of i)if(n.isDirectory()){const i=await this._directoryEntryChild(n).someDescendant(e,t-1);if(null!=i)return i}}descendantsSync(e){const t=this.directoryEntrySync(),i=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&i.push(this.forDirectoryEntry(t))})),i}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Z.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,ie.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,M.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(E.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,C.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,i)=>this.join((0,N.toS)(e),(0,L.pad2)(t+1),(0,L.pad2)(i))))}child(...e){if((0,M.isEmpty)(e))return this;const t=(0,D.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(i,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,i="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(i,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,i){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(i??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,pe.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??await(0,pe.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,a,void 0,"f"),h(this,a,d(this,a,"f")??(0,ge.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,V.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,V.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,V.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,V.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,x.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,pe.statTimes)(e)}maxStatMs(){return(0,V.thenMap)(this.statTimes(),B.max)}maxStatDate(){return(0,V.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,V.thenMap)(this.statTimes(),K.min)}minStatDate(){return(0,V.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,V.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,V.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,V.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Z.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,M.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,V.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>=(0,x.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,V.thenMap)(this.mtimeMs(),(i=>Math.abs(i-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,V.thenMap)(this.mtime(),(t=>(0,x.unixtime)(t)>(0,x.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,V.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,C.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,I.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,H.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*x.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,oe.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,oe.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,$.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,$.parseJSON)((0,p.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,p.readFileSync)(this.nativePath)}readFile_(){return(0,g.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,V.thenMap)(this.zReadFile_(e),N.toS)))}readLines(e="warn"){return(0,V.thenMap)(this.readTextFile(e),ne.splitLines)}readFileSync(){try{return p.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,k.stringify)(e,t?.replacer,t?.spaces),(0,O.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,_.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,j.ending)()?1:3,timeoutMs:0,retryDelay:x.secondMs,errorIsRetriable:q.isRetriableError})}async gunzip(){return d(this,n,"m",o).call(this,(0,X.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,n,"m",o).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,n,"m",o).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return p.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return p.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children((async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath));if((0,M.isEmpty)(i))return;const n=await e.sha();if(null!=n)for(const e of i.sort(((e,t)=>-(0,Y.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===n)return e}))}firstMatchingLine(e){const t=new z.Deferred("firstMatchingLine("+this+")"),i=p.default.createReadStream(this.nativePath,{flags:"r"});return i.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),i.close()):t.maybeReject(e)})),i.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(i,(0,A.newlineRe)(),(n=>{const r=e.exec(n);null!=r&&(t.maybeResolve(r),i.close())})),t.promise}contemporary(e,t){return(0,V.thenMap2Or)(this.statTimes(),e.statTimes(),((e,i)=>{for(const n of e)for(const e of i)if((0,F.closeTo)(n,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),i=new z.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&i.setTimeout(e.timeoutMs),Me)try{const n=(0,p.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(n,r)=>{try{const s=await e.f(n,(0,C.denull)(r));t(s)&&i.resolve(s)}catch(e){i.reject(e)}}));i.finally((()=>{n.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,F.gt0)(e.intervalMs)){const n=setInterval((async()=>{try{const n=await e.f();t(n)&&i.resolve(n)}catch(e){i.reject(e)}}),e.intervalMs);e.persistent||n.unref(),i.finally((()=>{clearInterval(n)}))}return i}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,X.equalsIgnoreCase)(e.basename,this.base))),t=(0,B.leastBy)(e,(e=>(0,Y.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,C.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},o=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const i=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([p.default.createReadStream(this.nativePath,{autoClose:!0}),t,p.default.createWriteStream(i.nativePath,{autoClose:!0})]),await this.unlink(),i}))},Pe.attrTTL=3*x.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let Me=!0;t.useFsWatch=function(e){Me=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},19748:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=t.extFilter=t.excludedPathFilter=void 0;const n=i(28874),r=i(88840),s=i(14036),a=i(29882);function o(e){return t=>n.Settings.respectFileExtensions.valueOrDefault?(0,s.isExtType)(t?.ext,e):null}t.excludedPathFilter=function(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>(0,a.toPathnames)(e.nativePath).every((e=>!t.has(e.toLowerCase())))},t.extFilter=o,t.isBrowserExtension=o(r.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=o(r.ExtTypes.Video),t.isAssetFileExtension=o(r.ExtTypes.AssetFile)},84542:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const n=i(40958),r=i(96249),s=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,r.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,s.newlineRe)()))))}t.Newline=o.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,n.compactBlanks)(l(...e))}},70698:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const n=i(76760),r=i(19851),s=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(16287),d=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,r.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,n.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,d.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const r=n(i(76760)),s=n(i(1708)),a=i(19851),o=i(22573),l=i(45969),u=i(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,a.lazy)((()=>[...(0,o.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,r.default.join(e,"System32"),r.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const o=s(i(44652)),l=a(i(73024)),u=i(76760),c=i(57975),d=i(19851),h=i(59455),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),w=i(17217),S=i(16287),b=i(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const M=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class _{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:n}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},r=await o.stat(t);return new _(i,new P(n,r))}clear(){return(0,p.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void M().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>_.fromSimpleDirent(this.nativePath,e)))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new _(this.nativePath,new P(e.name,e))))}catch(e){return void M().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const i of t)i.isDirectory()&&await i.visitDescendants(e);for(const i of t)i.isFile()&&await e(i);for(const i of t)i.isDirectory()&&await e(i)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async i=>{!0===await e(i)&&t.push(i)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await o.unlink(this.nativePath),(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await o.rmdir(this.nativePath,e),(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},20197:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const r=n(i(76760)),s=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(n.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},n=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(n.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=r.default.join(n.dir,`${n.name}-${(0,s.leftPad)(e,i.leftPad,"0")}${n.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)}},92423:function(e,t,i){var n,r,s,a=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notInHiddenPhotoStructureDir=t.whyExcludedDirectoryRecursive=t.notExcludedDirs=t.isExcludedDirectory=t.whyExcludedDirectory=t.notExcludedDirPredicates=t.isExcludedFile=t.whyExcludedFile=t.notExcludedFilePredicates=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=t.formatPathForGlob=void 0;const l=o(i(83058)),u=i(19851),c=i(40958),d=i(76790),h=i(22573),f=i(55835),m=i(51926),p=i(54993),g=i(48884),y=i(9092),v=i(54557),w=i(50213),S=i(88158),b=i(56519),P=i(46292),M=i(32551),_=i(35280),E=i(87290),x=i(96706),T=i(57902),D=i(43334),k=i(78984),C=i(33995),F=i(28874),O=i(21144),I=i(83278),L=i(48313),A=i(85772),R=i(78133),N=i(46356),B=i(17217),z=(0,u.lazy)((()=>(0,w.mkLogger)("fs.ExcludeGlobs"))),j=new v.FifoCache(256),V=/[\\/]$/;function W(e){const t=(0,p.toS)(e),i=j.get(t);if(null!=i)return i;const n=(0,B.isSimpleFile)(e)?e:I.BaseFile.for(e),r=V.test(t)||n.isDirectorySync(),s=(0,R.native2posix)(n.nativePath),a=r?(0,m.ensureSuffix)(s,"/"):s;return j.set(t,a),j.set(a,a),j.set(n.nativePath,a),a}t.formatPathForGlob=W;class H{constructor(e,t,i=!0){if(n.add(this),this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,R.native2posix)(t),z().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,c.compactBlanks)([this.exclude?"not":"",t,"("+(0,m.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=l.default.makeRe(this.pattern,{nocase:F.Settings.globsCaseInsensitive.valueOrDefault,dot:!0,posixSlashes:!0}),this.valid=!0}catch(e){this.valid=!1,z().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,S.pairToObject)(this.reason,a(this,n,"m",r).bind(this)):{}}}n=new WeakSet,r=function(e){const t=W(e),i=this.re.test(t)??this.exclude;return z().tap({msg:"apply()",level:i?T.LogLevels.debug:T.LogLevels.trace,result:i?!this.exclude:this.exclude,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})};class U{constructor(){s.set(this,[])}push(...e){for(const t of e){if(!t.valid){z().warn("Ignoring invalid glob",{glob:t});continue}const e=a(this,s,"f").find((e=>e.pattern===t.pattern));null==e?a(this,s,"f").push(t):z().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new H((0,R.native2posix)(e),t))}toA(){return a(this,s,"f")}}s=new WeakMap;const q=new H("**/.*","hidden file"),G=new H("**/.*/","hidden directory"),$=(0,u.lazy)((()=>{const e=new U;e.push(G,q);for(const t of[{s:"bin",desc:"command binary"},{s:"dev",desc:"device file"},{s:"etc",desc:"system configuration file"},{s:"initrd",desc:"initial ramdisk"},{s:"proc",desc:"process metadata"},{s:"sbin",desc:"system binary"},{s:"snap",desc:"snap software"},{s:"sys",desc:"system metadata"},{s:"Dell",desc:"Windows driver"},{s:"Drivers",desc:"Windows driver"},{s:"Intel",desc:"Windows driver"},{s:"Microsoft",desc:"Windows driver"},{s:"NVIDIA",desc:"Windows driver"},{s:"Windows.old",desc:"Windows system"},{s:"Windows",desc:"Windows system"}])e.push(new H((D.isWin?"*":"")+"/"+t.s+"/",t.desc));if(D.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=(0,x.getEnv)(t);(0,h.blank)(i)||e.pushNativePath(i,`%${t}%`)}D.isLinux&&e.push(new H(`${(0,M.homeDir)()}/snap/`,"Snap software"));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$SysReset",desc:"Windows"},{s:"3rdParty",desc:"code"},{s:"Application Data",desc:"Windows apps"},{s:"Application Support",desc:"macOS apps"},{s:"Applications",desc:"macOS apps"},{s:"arangodb",desc:"3rd party"},{s:"cache",desc:"Cache directory"},{s:"CacheClip",desc:"Movie cache directory"},{s:"caches",desc:"Cache directory"},{s:"Chipset_Software",desc:"Windows apps"},{s:"cmake",desc:"code"},{s:"com.apple.TimeMachine.localsnapshots",desc:"macOS"},{s:"cpan",desc:"code"},{s:"DefinitelyTyped",desc:"TypeScript type"},{s:"Desktop DB",desc:"macOS metadata"},{s:"Desktop DF",desc:"macOS metadata"},{s:"Desktop.ini",desc:"macOS metadata"},{s:"DisplayDriver",desc:"Windows driver"},{s:"DLLs",desc:"Windows library"},{s:"dyld",desc:"macOS library"},{s:"ehthumbs.db",desc:"Windows thumbnail"},{s:"i18n",desc:"i18n code"},{s:"iMovie Cache",desc:"Apple iMovie cache"},{s:"iTunes Cache",desc:"Apple iTunes"},{s:"iTunes Media",desc:"Apple iTunes"},{s:"iTunes",desc:"Apple iTunes"},{s:"lib?(32|64|x64|s)",desc:"program library directory"},{s:"lost+found",desc:"fsck recovered directory"},{s:"macOS Install*",desc:"macOS installer"},{s:"Network Trash",desc:"AFP trash"},{s:"node_modules",desc:"Node.js library"},{s:"pkgconfig",desc:"code"},{s:"pkgs",desc:"Python code"},{s:"Program Files (x86)",desc:"Windows apps"},{s:"Program Files",desc:"Windows apps"},{s:"ProgramData",desc:"Windows application support"},{s:"resources/media/face",desc:"face thumbnail"},{s:"rubygems-*",desc:"Ruby code"},{s:"site-packages",desc:"Python code"},{s:"spotifycache",desc:"Spotify cache"},{s:"SteamApps",desc:"Game files"},{s:"System Volume Information",desc:"Windows system metadata"},{s:"System32",desc:"Windows system"},{s:"SystemTemp",desc:"Windows temporary"},{s:"temp",desc:"temporary"},{s:"Temporary Items",desc:"temporary"},{s:"test_suite",desc:"code"},{s:"testutil?(s)",desc:"code"},{s:"third_party",desc:"code"},{s:"Thumbnail?(s)",desc:"thumbnail"},{s:"Thumbs.db",desc:"Windows thumbnail"},{s:"tmp",desc:"temporary"},{s:"Trash",desc:"trash directory"},{s:"Windows",desc:"Windows"},{s:"Windows.old",desc:"Windows"},{s:"Windows10Upgrade",desc:"Windows upgrade"},{s:"Xcode.app",desc:"macOS code"},{s:"*.sparsebundle/bands",desc:"Time Machine backup"},{s:"ImageMagick*",desc:"ImageMagick source"},{s:"Install OS X*",desc:"macOS installer"},{s:"Install macOS*",desc:"macOS installer"},{s:"*.lrdata",desc:"LightRoom data"},{s:"MinGW*",desc:"code"},{s:"msys*",desc:"code"},{s:"vcpkg",desc:"code"}])e.push(new H("**/"+t.s+"/",t.desc));function t(t,i,n){if(!(0,h.blank)(t)){const r=(0,d.sort)((0,c.uniq)((0,c.compactBlanks)(i).map((e=>e.toLowerCase()))));1===r.length&&e.push(new H(`**/${t}/${r[0]}/`,n)),r.length>1&&e.push(new H(`**/${t}/(${r.join("|")})/`,n))}}(0,f.map)((0,P.configDir)(),(t=>e.pushNativePath(t,"PhotoStructure configuration"))),t("nix",["store"],"NixOS package"),e.push(new H("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),e.push(new H("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const n=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",n,"Linux /var"),t("mnt",n,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["Apple","Assistant","Bluetooth","com.apple.iTunesCloud","Containers","CoreAnalytics","Developer","Desktop Pictures","Documentation","Extensions","Finance","Fonts","Frameworks","FrontBoard","Group Containers","HTTPStorages","iTunes","KeyboardServices","Keychains","Logs","Messages","News","Passes","Photos","Preferences","Ruby","Saved Application State","Scripts","User Pictures","Updates","User Template","WebKit","WebServer"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return t("ps",["cache","config","logs","tmp"],"PhotoStructure docker directory"),e.toA()})),J=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},K=()=>{t.notExcludedDirs.unset()},Z=(0,u.lazy)((()=>{F.Settings.excludeGlobsOmitDefaults.watchLater(J),F.Settings.excludeGlobsAdd.watchLater(J),F.Settings.excludeGlobsOmit.watchLater(J),F.Settings.globsCaseInsensitive.watchLater(J),F.Settings.libraryDir.watchLater(K),F.Settings.originalsDir.watchLater(K),F.Settings.scanPaths.watchLater(K),F.Settings.argvScanPaths.watchLater(K)}));t.defaultDirPredicates=(0,u.lazy)((()=>[{notSymlinkLoop:ne,notInHiddenPhotoStructureDir:se,whyNoMedia:A.whyNoMedia,notHidden:re}])),t.defaultFilePredicates=(0,u.lazy)((()=>[{notInHiddenPhotoStructureDir:se}])),t.excludeGlobs=(0,u.lazy)((()=>{Z();const e=new y.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&z().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):z().warn("Failed to find and remove glob specified in PS_EXCLUDE_GLOBS_OMIT",{glob:t})}if(!F.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of $())t(e);for(const e of F.Settings.excludeGlobsOmit.values)i(e);for(const e of F.Settings.excludeGlobsAdd.values)t(new H(e,"(from PS_EXCLUDED_GLOBS_ADD)"));const n=(0,d.sortBy)(e.values(),(e=>(0,c.compactBlanks)(e.pattern.toLowerCase().split("/")))),[r,s]=(0,g.partition)(n,(e=>e.pattern.endsWith("/")));return{dir:r,file:s}})),t.excludeBundles=(0,u.lazy)((()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map((e=>e.bundle))],file:[...(0,t.defaultFilePredicates)(),...e.file.map((e=>e.bundle))]}}));const X=[{disableAllFilters:()=>!0}],Y=[{notBlank:()=>!1}];function Q(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Y:(0,t.excludeBundles)().file}function ee(e){return C.SyncPredicates.whyRejected(e,...Q(e))}function te(e){return F.Settings.disableAllFilters.valueOrDefault?X:(0,h.blank)(e)?Y:(0,t.excludeBundles)().dir}async function ie(e){return F.Settings.disableAllFilters.valueOrDefault?void 0:k.Predicates.whyRejected(e,...te(e))}function ne(e){return!(0,N.seemsLikeSymlinkLoop)(e)}function re(e){return(0,b.thenNot)((0,L.isHidden)(e))}function se(e){return!(0,_.inHiddenPhotoStructureDir)(e)}t.notExcludedFilePredicates=Q,t.whyExcludedFile=ee,t.isExcludedFile=function(e){return null!=ee(e)},t.notExcludedDirPredicates=te,t.whyExcludedDirectory=ie,t.isExcludedDirectory=async function(e){return null!=await ie(e)},t.notExcludedDirs=(0,u.lazy)((async()=>{const e=(0,c.uniq)((0,c.compactBlanks)([(0,E.libraryDirPosixFile)(),(0,E.libraryOriginalsDirPosixFile)(),...F.Settings.argvScanPaths.values,...F.Settings.scanPaths.values]));return z().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,c.uniq)([...e,...await Promise.all(e.map((e=>(0,O.actualPath)(e))))])})})),t.whyExcludedDirectoryRecursive=async function(e){const i=await(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await ie(t);if(null!=e)return e}},t.notInHiddenPhotoStructureDir=se},88561:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const a=i(40958),o=i(22573),l=i(41400),u=i(68708),c=i(25764),d=i(38836),h=i(34102),f=i(80049),m=i(50213),p=i(88158),g=i(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:g.ShortCommandTimeoutMs,...e}),n.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,n,"m",r).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,p.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,a.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,n=new WeakSet,r=async function(e){if((0,o.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const n=i(73024),r=i(22573),s=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(49047),c=i(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...i]of d)for(const n of i)e[n]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof n.Dirent?e.name:(0,l.toS)(e),i=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,r.blank)(i)?void 0:h()[i]??i}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const n=i(68708),r=i(17217),s=i(16287),a=i(68284);async function o(e){return(0,n.pick)(await(0,s.stat_)((0,r.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=o,t.fileStats=async function(e){try{return await o(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,a.statSync)((0,r.toNativePath)(e)))?void 0:(0,n.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},78923:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=void 0;const n=i(68817),r=i(19851),s=i(22573),a=i(50213),o=i(57159),l=i(32144),u=i(47783),c=i(14036),d=i(16170),h=i(95696),f=i(93854),m=i(16287),p=(0,r.lazy)((()=>(0,a.mkLogger)("fs.FileType"))),g=["image/tiff","audio/mpeg","image/x-sony-arw","image/x-nikon-nef"];t.readFileType_=async function(e){try{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,n.fromBuffer)(t);if(null!=i&&!g.includes(i.mime))return{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,d.normalizeMimetype)(i.mime)};if(!await(0,m.exists)(e))return;const r=(0,s.mapNotBlank)(await(0,u.readRawField)(e,"MIMEType"),d.normalizeMimetype),a=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,c.mimetypeExt)(r);return(0,s.blank)(r)||(0,s.blank)(a)?void 0:{ext:a,mime:r}}catch(t){if("EISDIR"===t?.code)return;throw p().warn("readFileType() failed for "+e,t),new o.WrappedError("Failed to read mimetype for "+e,{cause:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}}},73787:function(e,t,i){var n,r,s,a,o,l=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcher=void 0;const c=i(73024),d=i(50357),h=i(38836),f=i(43624);class m extends h.EndableWrapper{constructor(e,t,i){super("fs.FileWatcher("+e+")",(()=>this.close())),n.add(this),this.nativePath=e,r.set(this,[]),s.set(this,void 0),a.set(this,void 0),l(this,a,(0,f.fileStatsSync)(e),"f"),l(this,s,(0,c.watch)(e,{encoding:"utf8",persistent:!1,...t??{}},(e=>u(this,n,"m",o).call(this,e))),"f"),null!=i&&this.addListener(i)}addListener(e){null!=e&&u(this,r,"f").push(e)}close(){u(this,s,"f").close()}}t.FileWatcher=m,r=new WeakMap,s=new WeakMap,a=new WeakMap,n=new WeakSet,o=async function(e){const t=await(0,f.fileStats)(this.nativePath);if(!(0,d.eql)(u(this,a,"f"),t)){l(this,a,t,"f");for(const t of u(this,r,"f"))t(e,this.nativePath)}}},73209:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p,g,y,v,w,S=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},b=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},P=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withLock_=t.FsLock=void 0;const M=i(58587),_=P(i(44652)),E=i(87997),x=i(40958),T=i(17586),D=i(42659),k=i(50357),C=i(75240),F=i(55835),O=i(31586),I=i(30976),L=i(13538),A=i(54993),R=i(7282),N=i(68852),B=i(23560),z=i(25764),j=i(38836),V=i(99331),W=i(22781),H=i(38835),U=i(55222),q=i(63870),G=i(69734),$=i(17217),J=new RegExp("-(?\\d+)"+(0,N.escapeRegExp)(G.PsLockExt)+"$");class K extends j.EndableWrapper{static newUid(e=process.pid){return b(this,r,Math.max(Date.now(),S(this,r,"f",s)+1),"f",s),(0,x.compactBlanks)([U.TokenRadix.encode(S(this,r,"f",s)),B.serviceName.prior(),(0,A.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,$.basename)(e))}static pidFromBasename(e){return(0,O.toInt)(J.exec((0,A.toS)(e))?.groups?.pid)}static for(e){return S(this,r,"f",o).find((t=>t.opts.file===e.file))??new r(e)}constructor(e){var t,i;super(e.name??"FsLock",(()=>S(this,n,"m",w).call(this)),e.endableRank??z.EndableRanks.postdb,(0,q.commandTimeoutMs)()),n.add(this),this.opts=e,l.set(this,b(t=r,r,(i=S(t,r,"f",a),++i),"f",a)),u.set(this,!1),c.set(this,void 0),d.set(this,void 0),h.set(this,Date.now()),this.tryAcquire_=(0,W.oneAtATime)({runLaterIfBusy:!1,undefinedIfBusy:!0,fn:async()=>{if(S(this,u,"f"))return!0;await(this.lockfile??(this.lockfile=this.lockdir.join((0,G.fsLockFileBasename)(r.newUid())))).touch_(),this.startRefreshTimer_();try{return null!=this.lockfile&&!!await S(this,n,"m",g).call(this)&&(this.logger.debug("tryAcquire(): acquired"),!0)}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}}}),this.lockdir=(0,G.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file.baseWithGrandparent+")#"+S(this,l,"f")),this.staleMs=(0,O.round)(this.opts.timeoutMs/(0,I.randomFloat)(2,4)),S(r,r,"f",o).push(this)}get acquired(){return S(this,u,"f")}toLogJSON(){return{name:this.name,acquired:this.acquired}}async selfAndSiblingNames_(e){return await S(this,n,"m",f).call(this,e)??S(this,n,"m",p).call(this)}async siblingNames(e){return(await this.selfAndSiblingNames_(e)).filter((e=>e!==this.lockfile?.base))}async iAmLast_(e){return null!=this.lockfile&&(0,T.at)(await this.selfAndSiblingNames_(e),-1)===this.lockfile.base}async iAmOnly_(e){return null!=this.lockfile&&!0===(0,k.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}startRefreshTimer_(){if(null==S(this,c,"f")&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,R.isTest)()?10:D.secondMs);b(this,c,setInterval((()=>S(this,n,"m",y).call(this)),e),"f")}}stopRefreshTimer(){null!=S(this,c,"f")&&(clearInterval(S(this,c,"f")),b(this,c,void 0,"f"))}async acquire_({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={}){if(S(this,u,"f"))return!0;try{return!!await this.tryAcquire_()||(await this.lockdir.watchUntil({f:()=>this.tryAcquire_(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:Math.round(Math.min(this.staleMs,t)/5)}),!this.acquired&&e&&this.release(),this.acquired)}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}}release(){this.stopRefreshTimer(),b(this,u,!1,"f"),(0,F.map)(S(this,d,"f"),(e=>(0,E.clearTimeout)(e)));try{return this.lockfile?.unlinkSync_(),this.lockfile=void 0,this.logger.debug("#release() success"),!0}catch(e){return this.logger.warn("#release() failed to delete lockfile",e),!1}finally{!0===this.opts.dirty||((0,V.ending)()||this.ended?S(this,n,"m",v).call(this):(this.logger.debug("#release() scheduling lockdir cleanup",{ms:2*this.staleMs}),b(this,d,setTimeout((()=>S(this,n,"m",v).call(this)),(0,O.toGt0)(this.staleMs)??D.secondMs),"f"),S(this,d,"f").unref()))}}async withLock_(e){if(!0===this.opts.skipFsLock)return this.logger.debug("withLock(): skipLock is true, running f()"),e(this);if(S(this,u,"f"))return this.logger.debug("withLock() already acquired"),e(this);try{const t=await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_());return this.logger.debug("withLock()",{acquired:t}),t?await(0,L.thenOrTimeoutError)(e(this),this.opts.timeoutMs,!1):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.release()}}}t.FsLock=K,r=K,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,n=new WeakSet,f=async function(e){const t=!0===e?.vacuum?"arg.vacuum":(0,O.gt0)(this.staleMs)&&Date.now()>S(this,h,"f")+this.staleMs?"lastVacuumTs was too long ago":void 0;return this.logger.tap({msg:"#maybeVacuum()",level:null==t?"trace":"debug",result:null==t?void 0:await S(this,n,"m",m).call(this),meta:{why:t}})},m=async function(){b(this,h,Date.now(),"f");const e=[],t=await S(this,n,"m",p).call(this);for(const i of t){const t=this.lockdir.join(i);if((0,O.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+D.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});if(null!=i&&i{if(this.logger.warn("readdir() failed",{error:e}),"ENOENT"===e.code)return[];throw e}))).filter((e=>e.isFile()&&(0,G.isPsLockFileOrDir)(e))).map((e=>e.name))},g=async function e(t){if(null==this.lockfile)return this.release(),!1;const i=await this.selfAndSiblingNames_(t);if(null==this.lockfile)return this.release(),!1;if(!i.includes(this.lockfile.base)){if(!(0,R.isTest)())return this.release(),!1;r.internalErrors++,this.logger.throw("#iAmNext_(): missing lockfile, "+this.lockfile+H.InternalErrorFlag,{children:i,lockfile:this.lockfile})}const s=i[0]===this.lockfile.base;if(s)b(this,u,!0,"f");else if(!0!==t?.vacuum){const t=r.pidFromBasename(i[0]);if((0,O.gt0)(t)&&!(0,M.pidExists)(t))return this.logger.info("#iAmNext_(): auto-vacuuming, owner pid is gone."),S(this,n,"m",e).call(this,{vacuum:!0})}return this.logger.tap({msg:"#iAmNext_()",result:s,meta:{lockfiles:i}})},y=async function(){if(null==this.lockfile||await this.lockfile.notExists({refresh:!0}))this.logger.warn("#refreshLockfile_(): null or missing lockfile",{lockfile:this.lockfile,notExists:await(this.lockfile?.notExists())}),this.release();else try{await this.lockfile.touch_(),this.logger.debug("#refreshLockfile_(): Touched lockfile",{lockfile:this.lockfile,selfAndSiblings:await S(this,n,"m",p).call(this)})}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}},v=async function(){await S(this,n,"m",m).call(this);const e=this.lockdir.rmdirSync("trace");this.logger.debug("#rmLockDir() attempting lockdir rmdir...",{success:e})},w=function(){(0,x.filterInPlace)(S(r,r,"f",o),(e=>S(e,l,"f")!==S(this,l,"f")))},s={value:0},K.internalErrors=0,a={value:0},o={value:[]},t.withLock_=async function(e,t){return!0===e.skipFsLock?t():new K(e).withLock_(t)}},69734:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPsLockFileOrDir=t.uidFromFsLockfile=t.fsLockFileBasename=t.fsLockDir=t.PsLockExt=void 0;const n=i(22573),r=i(51926),s=i(54993),a=i(17217);function o(e){return(0,n.notBlank)(e)&&e.startsWith(".")&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock",t.fsLockDir=function(e){return e.sibling((0,r.ensurePrefixSuffix)(e.base,{prefix:".",suffix:t.PsLockExt}))},t.fsLockFileBasename=function(e){return(0,r.ensurePrefixSuffix)(e,{prefix:".",suffix:t.PsLockExt})},t.uidFromFsLockfile=function(e){if(null==e||(0,n.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?i.substring(1,i.length-t.PsLockExt.length):void 0},t.isPsLockFileOrDir=function(e){return!(0,n.blank)(e)&&o((0,a.basename)(e))}},4001:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const n=i(22573),r=i(55835),s=i(31586),a=i(51926),o=i(54993),l=i(97352),u=i(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,n.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function f(e,i){if(t.ymdIsoRE.test(e))return e;let n=e;for(const e of i.aggressive?d:c){const t=n.match(e);if((0,s.gt0)(t?.index)){const e=n.slice(0,t.index).trim();e.length>0&&(n=e)}}return e===n?e:f(n,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),i=t.pop();if((0,n.blank)(i))return e;const r=(0,u.parsePosixPath)(i),s=h(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=h(t),n=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,r.map)((0,l.extractInt)(n),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,p=/(?<=.{6})_cover$/i,g=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(p,"").trim();return(0,r.map)(m.exec(t),(e=>t=e[1].trim())),(0,r.map)(g.exec(t),(e=>t=e[1].trim())),t}},14977:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.matcherForExtOrCompressedExt=t.isExtOrCompressedExt=t.gzip_=void 0;const r=n(i(44652)),s=n(i(73024)),a=i(46466),o=n(i(38522)),l=i(49769),u=i(68852);t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz";return await(0,a.pipeline)(s.default.createReadStream(e,{autoClose:!0}),o.default.createGzip(),s.default.createWriteStream(t,{autoClose:!0})),await r.default.unlink(e),t},t.isExtOrCompressedExt=function(e,t){return d(t)(e)};const c=new Map;function d(e){return(0,l.getOrSet)(c,e,(()=>{const t=new RegExp("^"+(0,u.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i");return e=>null!=t.exec(e)}))}t.matcherForExtOrCompressedExt=d},50597:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const r=n(i(77598)),s=n(i(73024)),a=i(46466),o=i(19851),l=i(98553),u=i(68708),c=i(23467),d=i(80049),h=i(73913),f=i(50213),m=i(12089),p=i(37628),g=i(43624),y=i(17217),v=i(16287),w=(0,o.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,o.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:i=!0}={}){const n=(0,y.toNativePath_)(e);if(i){const t=S().get(n);if(null!=t){if((0,c.eql)(t.stats,await(0,g.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:n,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:n,prior:t}),S().delete(n)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),i=(0,y.toNativePath_)(e);return{sha:await M(s.default.createReadStream(i)),stats:(0,u.pick)(await(0,v.stat_)(i),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function M(e,t=[],i="sha512"){const n=r.default.createHash(i);return await(0,a.pipeline)([e,...t,n]),n.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=M,t.numericSha=function(e,t=48){return parseInt((0,p.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return r.default.randomBytes(h.HashBits/8).toString("base64")}},48313:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHidden=t.hide_=void 0;const n=i(19851),r=i(42659),s=i(55835),a=i(31586),o=i(84777),l=i(34102),u=i(43334),c=i(24399),d=i(28874),h=i(63870),f=i(83278),m=i(88561),p=i(17217),g=i(16287);t.hide_=async function(e){if(!u.isWin&&!u.isMac)return;const t=(0,p.toNativePath_)(e);await(0,g.exists)(t)&&(u.isWin?await c.PowerShell.instance().execute(`(Get-Item ${(0,c.pwshQuote)(t)}).Attributes += 'Hidden'`,(()=>{})):u.isMac&&await(0,o.stdout_)("chflags",["hidden",t],{timeoutMs:10*r.secondMs}),(0,l.ee)().emit("fileChanged",t))};const y=(0,n.lazy)((()=>new m.FileCache({name:"fs.hidden",maxSize:512,timeoutMs:(0,h.commandTimeoutMs)()})));t.isHidden=function(e){if(u.isLinux||!d.Settings.excludeHidden.valueOrDefault)return!1;const t=(0,p.isSimpleFile)(e)?e:f.BaseFile.for(e);return!t.isRoot&&(u.isWin?y().getOrSetAsync(t.nativePath,(()=>async function(e){if(e.isRoot)return!1;const t=await c.PowerShell.instance().executeJsonToA(["Get-Item -Force -LiteralPath",(0,c.pwshQuote)(e.nativePath),"-ErrorAction SilentlyContinue","| Select-Object -Property Name, Mode"].join(" "));return(0,s.mapOr)(t?.[0]?.Mode,(e=>["s","h"].some((t=>e.includes(t)))),(()=>!1))}(t))):!!u.isMac&&y().getOrSetAsync(t.nativePath,(()=>async function(e){try{const t=await(0,o.stdout_)("stat",["-f","%f",e.nativePath],{timeoutMs:10*r.secondMs}),i=(0,a.toInt)(t);return null!=i&&(32768&i)>0}catch(e){return!1}}(t))))}},25675:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const n=i(22573),r=i(54993),s=i(7282),a=i(43334),o=i(69375),l=/^\/dev(?:\/|$)/i,u=a.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=a.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=a.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=a.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,r.toS)(e))}function m(e){return(0,n.blank)(e)?"blank":(0,o.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const n=i(57075),r=i(51926),s=i(54993);class a extends n.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,i){const n=(this._prior+(0,s.toS)(e)).split((0,r.newlineRe)()),a=n.pop();this._prior=a??"";let o=!1;for(const e of n)o||(o=!this.push(e));o?setTimeout(i,1):i()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=a},64680:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const r=n(i(76760)),s=i(17217),a=i(73428);t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(r.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},85772:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t._dirHasNoMediaChild=t.whyNoMediaDir=t.whyNoMedia=t.hasNoMedia=t.isNoMediaName=void 0;const a=s(i(76760)),o=i(19851),l=i(40958),u=i(96249),c=i(59455),d=i(50213),h=i(68852),f=i(76740),m=i(46199),p=i(57902),g=i(43334),y=i(59107),v=i(83278),w=i(70698),S=i(88561),b=i(65238),P=i(16287),M=(0,o.lazy)((()=>(0,d.mkLogger)("fs.hasNoMedia()"))),_="NoMedia",E=new RegExp("(?:^|["+(0,l.uniq)([(0,h.escapeRegExp)(a.default.sep),"/"]).join("")+"])\\.?"+_+"$","im"),x=Object.freeze(["."+_,_]),T=Object.freeze((0,u.flatten)(x.map((function(e){return[e,e.toLowerCase(),e.toUpperCase()]}))));function D(e){return null!=E.exec(e)}t.isNoMediaName=D;const k=(0,o.lazy)((()=>new S.FileCache({name:"fs.noMediaDirsCache"})));async function C(e,t){if(null==e)return null;const i=v.BaseFile.for(e),n=await i.stat();if(null==n||!n.isFile()&&!n.isDirectory())return null;if(n.isFile())return D(i.base)||await(0,w.isCachedirTagFile)(i)?k().set(i.parent().nativePath,(0,m.ciSafePath)(i.nativePath)):C(i.parent());{const e=await k().getOrSetAsync(i.nativePath,(()=>F(i)));return null!=e||!1===t?.recurse||i.isRoot||await(0,y.isPosixMountpoint)(i)?e:C(i.parent())}}async function F(e){if(D(e.base))return k().set(e.parent().nativePath,e.nativePath),M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.nativePath)});const t=(0,b.readdirCached)(e.nativePath);if(null!=t)return I(e.nativePath,t);const i=new f.Abortable,n=await Promise.race([O(e.nativePath,i),(0,b.readdir)(e.nativePath).then((t=>I(e.nativePath,t,i)))]);return i.abort("done"),null!=n?n:await(0,w.isCachedirTagDirectory)(e)?M().tap({msg:"whyNoMedia()",result:(0,m.ciSafePath)(e.join(w.CACHEDIR_TAG).nativePath)}):null}async function O(e,t){for(const i of g.isCaseSensitiveFs?T:x){if(!0===t?.aborted)return null;const n=a.default.join(e,i);if(await(0,P.exists)(n,p.LogLevels.trace))return M().tap({msg:"_dirHasNoMediaChild",result:(0,m.ciSafePath)(n)})}return null}async function I(e,t,i){for(const n of(0,c.toA)(t)){if(!0===i?.aborted)return null;if(D(n.basename))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)((0,a.join)(e,n.basename))});if(n.basename===w.CACHEDIR_TAG){const t=(0,a.join)(e,n.basename);if(await(0,w.isCachedirTagFile)(t))return M().tap({msg:"dirHasNoMedia()",result:(0,m.ciSafePath)(t)})}}return null}t.hasNoMedia=async function(e,t){return null!=await C(e,t)},t.whyNoMedia=C,t.whyNoMediaDir=F,t._dirHasNoMediaChild=O},29882:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const r=n(i(44652)),s=n(i(76760)),a=i(19851),o=i(40958),l=i(5233),u=i(22573),c=i(98553),d=i(39426),h=i(51926),f=i(48884),m=i(50213),p=i(81168),g=i(70025),y=i(43334),v=i(78133),w=i(53265),S=i(17217),b=i(16287),P=i(66430),M=i(5545);function _(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,a.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=_,t.containsHiddenPathname=function(e){return C(e).some(_)},t.isNotHiddenPosixPath=function(e){return C(e).every((e=>!_(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return x((0,v.posix2native)(e))},t.extname=function(e){return x(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,p.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const E=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function x(e){const t=E.exec(e)?.groups,i=t?.ext2??"",n=s.default.parse(t?.path??e);return{...n,ext:(n.ext??"")+i,base:(n.base??"")+i}}function T(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function D(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),i=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(i))return!1;const n=e.acceptSelf??!1;return t===i?n:i.startsWith((0,p.ensureSuffix)(t,s.default.sep))}catch(i){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:i}),!1}}function k(e,t,i){if(null==t||null==i)return!1;const n=e(t),r=e(i);return null!=n&&null!=r&&(y.isLinux?n===r:(0,p.equalsIgnoreCase)(n,r))}function C(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function F(e){return(0,u.notBlank)(e)&&C(e).length===(y.isWin?1:0)}function O({p:e,maxLength:t}){const i=(0,S.toNativePath_)(e);if(i.length<=t)return i;const n=C(e),r=[],s=[n.pop()];for(;n.length>0;)if(r.length=t){n.unshift(r.pop());break}}else if(s.unshift(n.pop()),L([...r,...s]).length>=t){n.push(s.shift());break}return n.length>0&&r.push("…"),L([...r,...s])}function I(e){return e.startsWith("\\\\")}function L(e){return(0,h.ensurePrefix)((0,o.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=x,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=D,t.eqlBasename=function(e,t){return k(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return k(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return k(S.toNativePath_,e,t)},t.toPathnames=C,t.pathIsRoot=F,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:C(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const i=(0,S.toNativePath_)(e),n=(0,S.toNativePath_)(t);if((0,u.blank)(i)||(0,u.blank)(n))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return i===n?"":(0,p.stripPrefix)((0,v.native2posix)(n).normalize(),(0,p.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=O,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:n=e.length}){const r=[];for(const n of e.slice(0,i))r.push(O({p:n,maxLength:t}));return r.join(", ")+(n>i?`, and ${n-i} more…`:"")},t.posixPathFromParent=function(e){return C(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return C(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const i=x(e);return`${i.base}${t}${i.ext}`},t.isUNC=I,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(I(e)||null!=e.match(M.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(F(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await r.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;r.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>r.default.move(e,t,{overwrite:!0})),{errorIsRetriable:g.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=L,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:L(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>D({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const r=n(i(76760)),s=i(19851),a=i(40958),o=i(22573),l=i(31586),u=i(51926),c=i(12168),d=i(59455),h=i(54993),f=i(50213),m=i(44198),p=i(96706),g=i(45969),y=i(43334),v=i(64660),w=i(21144),S=i(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function M(e,t=P){const i=await(0,S.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,l.gte)(i.size,t)&&(0,v.isStatRX)(i,e)}function _(){if(y.isWin){const e=(0,o.toNotBlank)((0,p.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,o.toNotBlank)((0,p.getEnv)("SystemDrive"))??"C:",i=(0,o.toNotBlank)((0,p.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,r.default.join(e,"System32"),r.default.join(e,"System32","Wbem"),r.default.join(i,"chocolatey","bin"),r.default.join(t,"cygwin64","bin")]}return[...(0,g.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function E(){const e=(0,h.toS)((0,m.env)().PATH).split(r.default.delimiter);return(0,a.uniq)((0,a.compactBlanks)([...e,..._()]))}t.isRXFile=M,t.pathTo=async function({tool:e,alternativePath:t,paths:i}){const n=(0,a.uniq)((0,a.compactBlanks)([...E(),...(0,d.toA)(i)]));for(const i of(0,a.uniq)((0,a.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(i,".exe"):i;for(const t of n){const i=r.default.join(t,e);if(await M(i))return y.isLinux?i:(0,w.actualPath)(i)}}b().warn("Failed to find tool",{tool:e,dirs:n})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},95696:function(e,t,i){var n,r,s,a=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return o(t,e),t},u=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=t.uniquePrefixes=void 0;const d=l(i(44652)),h=c(i(73024)),f=c(i(51455)),m=c(i(76760)),p=i(46466),g=i(19851),y=i(40958),v=i(76790),w=i(5233),S=i(22573),b=i(42659),P=i(26905),M=i(75240),_=i(55835),E=i(31586),x=i(68708),T=i(13538),D=i(89937),k=i(12168),C=i(54993),F=i(48884),O=i(50213),I=i(45255),L=i(81168),A=i(56519),R=i(56038),N=i(31562),B=i(84777),z=i(9595),j=i(38835),V=i(70025),W=i(57902),H=i(55222),U=i(43334),q=i(33847),G=i(24399),$=i(28874),J=i(79915),K=i(45200),Z=i(34238),X=i(87001),Y=i(59107),Q=i(63870),ee=i(7014),te=i(83278),ie=i(88561),ne=i(32144),re=i(73209),se=i(48313),ae=i(29882),oe=i(17217),le=i(36868),ue=i(27794),ce=i(70257),de=i(13047),he=(0,g.lazy)((()=>new ie.FileCache({name:"fs.PosixFile"})));t.uniquePrefixes=function(e){return(0,F.contextFilter)(function(e){return(0,v.sortBy)(e,(e=>e.nativePath))}(e),((e,t,i)=>null==i||!e.isDescendantOf(i)))},t.NoOp=Symbol("no-op");class fe extends te.BaseFile{constructor(e,t){super(e,t),n.add(this),this.nativePath=e,this.pflog=(0,g.lazy)((()=>(0,O.mkLogger)("fs.PosixFile("+this.nativePath+")"))),this.uriObject_=(0,g.lazy)((()=>(0,K.nativePath2uri)(this.nativePath))),this.uri_=(0,g.lazy)((async()=>(await this.uriObject_()).toString())),this.fileuri=(0,g.lazy)((()=>Z.URI.file(this.nativePath).toString())),this.normalizedPathUri_=(0,g.lazy)((async()=>(await this.normalize()).uri_())),this.etag=(0,g.lazy)((()=>(0,A.thenMap)(this.stat(),(e=>[e.size,e.mtime.getTime()].map((e=>H.Radix58.encode(e))).join("-"))))),this.isMountpoint=(0,g.lazy)((async()=>await this.isDirectory()&&await(0,A.thenMapOr)((0,Y.mountpoints)(),(e=>e.includes(this.nativePath)),(()=>!1)))),this.existingSidecars=(0,g.lazy)((()=>(0,J.existingSidecars)(this))),this.unlock=(0,g.lazy)((()=>U.isMac?(0,B.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:I.ShortCommandTimeoutMs}):void 0))}static forDirectoryEntry(e){return fe.for(e.nativePath,e)}static forMaybe(e){return(0,S.notBlank)(e)?fe.for(e):void 0}static for(e,t){if(e instanceof fe)return e;if((0,S.blank)(e))throw new Error("PosixFile.for(): empty nativePathOrFile");if((0,L.isString)(e)){const t=he().get(e);if(null!=t)return t}const i=(0,oe.toNativePath_)(e),n=new fe(i,t);return(0,L.isString)(e)&&he().set(e,n),he().set(i,n),n}static forPosix(e){return fe.for(e.replace(/\//g,m.default.sep))}static forUri(e,t){return(0,A.thenMap)((0,K.uri2nativePath)(e,t),(e=>fe.for(e)))}for(e,t){return fe.for(e,t)}forDirectoryEntry(e){return fe.for(e.nativePath,e)}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.normalizedPathUri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uri(){return this.trap("uri",(()=>this.uri_()))}async mountpoint(){if(!(0,ae.containedByNativePath)({ancestor:(0,z.libraryDir)(),descendant:this,acceptSelf:!0})&&!(0,ae.containedByNativePath)({ancestor:(0,z.originalsDir)(),descendant:this,acceptSelf:!0}))return U.isWin&&this.nativePath.startsWith("\\\\")?fe.for(this.nativePath.split("\\").slice(0,4).join("\\")):(0,_.map)((0,ee.bestMountpoint)(this.nativePath,await(0,Y.mountpoints)()),(e=>fe.for(e)))}async isDeletedUri(e){if(await this.exists({refresh:!0}))return!1;if(this.isUNC)return this.pflog().tap({result:await this.isDeleted(),msg:"isDeletedUri(): is UNC, delegating to isDeleted()"});const t=(0,_.map)((0,S.notBlankOr)(e,(()=>this.uri_())),Z.toURI);if(null==t)return this.pflog().tap({result:await this.isDeleted(),level:"warn",msg:"isDeletedUri(): missing URI, delegating to isDeleted()"});if(t.isRootPath())return this.pflog().tap({result:await this.notExists(),msg:"isDeletedUri(): uri isRootPath",meta:{uri:t}});if((0,C.toS)(t.pathBase).normalize()!==this.base.normalize())return this.pflog().tap({level:"warn",result:await this.notExists(),msg:"isDeleted(): uri isn't correct, returning notExists()",meta:{uri:t,expectedBase:this.base,uriBase:t.pathBase}});const i=t.scheme===D.PS_LIBRARY_SCHEME?1:t.scheme===D.PS_LOCAL_FILE_SCHEME?2:t.scheme===D.PS_NETWORK_FILESYSTEM_SCHEME?3:1,n=(0,L.countChars)(t.path,"/")-i;return this.isDeleted(n)}async httpHeaders(){return{ETag:await this.etag(),"Last-Modified":await this.lastModifiedUtc()}}hide(){if(U.isWin||U.isMac)return this.trap("hide",(async()=>(await(0,se.hide_)(this),this)))}async hidden(){return(0,se.isHidden)(this)}isSidecar(){return(0,ne.isSidecarExt)(this.ext)}async existingExifSidecars(){return(await this.existingSidecars()).filter((e=>!(0,ne.isJsonExt)(e)))}async sidecar(){return(await this.existingExifSidecars()).find((e=>(0,L.equalsIgnoreCase)(e.ext,(0,J.defaultSidecarExt)())))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,J.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter((e=>(0,ne.isJsonExt)(e)))}async sidecareStats(e){return(e?.refresh??!1)&&this.existingSidecars.unset(),(0,y.compact)(await Promise.all([this,...await this.existingSidecars()].map((t=>t.stat(e)))))}async thisOrSidecareMaxMtimeMs(e){const t=await this.sidecareStats(e);return(0,F.max)(t.map((e=>e.mtimeMs)))}async writeStream_(e,t){return await(0,p.pipeline)((0,y.compact)([e,(0,_.map)(t?.onProgress,(e=>new le.ByteCounter(e))),d.createWriteStream(this.nativePath,{autoClose:!0,...(0,x.omit)(t,"onProgress")})])),e.destroy(),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:n=!1,timeoutMs:r,skipWip:s=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,w.retryOnReject_)((async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(s&&a)return e(this);await this.applyWip_({fn_:async n=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(n),skipFsLock:a,minSizeBytes:i,timeoutMs:r,dirty:l})}return o&&n?void 0:this.utimes()}),{maxRetries:o,timeoutMs:2*r,retryDelay:3*b.secondMs,errorIsRetriable:e=>"EBUSY"===(0,P.errorCode)(e)})}wip(){return this.sibling((0,ce.addWipPrefix)(this.base))}isWip(){return(0,ce.isWip)(this.name)}async wipIsRecent(e=ce.WipTimeoutMs){return await this.wip().isFile()&&(0,E.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ce.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:n=!1,timeoutMs:r,dirty:s=!1}){return await this.parent().mkdirp_(),(0,re.withLock_)({file:this,skipFsLock:n,timeoutMs:r,dirty:s},(async()=>{const n=this.wip();try{await n.unlink("trace");const s=await(0,T.thenOrTimeoutError)(e(n),r);if(s===t.NoOp)return s;if(await(0,N.untilTrue)((()=>n.clear().isNonEmptyFile(i)),{timeoutMs:I.ShortCommandTimeoutMs,intervalMs:250}))return await n.mv_(this),s;throw new Error(this+"applyWip(): still empty after waiting "+(0,M.fmtDuration)(I.ShortCommandTimeoutMs))}catch(e){throw this.pflog().warn("applyWip() threw error",e),await n.unlink("trace"),await this.unlink("trace"),e}}))}copyFile_(e){return(0,R.time)("fs.copyFile",(async()=>{const t=this.dest(e);if(this.nativePath===t.nativePath)return this;if(!0!==$.Settings.onlyNativeFileCopy.valueOrDefault)try{return await u(this,n,"m",r).call(this,t)}catch(e){if(!0===(0,V.isNonRetriableError)(e))return this.pflog().throw("_copyFile failed, but error wasn't retriable",{error:e,dest:t.nativePath,src:this.nativePath});this.pflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:t.nativePath,src:this.nativePath,error:e})}return await u(this,n,"m",s).call(this,t)}))}async maybeVerifySameOrThrow_(e){const t=Date.now();$.Settings.verifyFileCopies.valueOrDefault&&(await(0,N.untilTrue)((()=>this.matchesContent(e)),{timeoutMs:(0,Q.commandTimeoutMs)(),intervalMs:b.secondMs})||this.pflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:Date.now()-t}))}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,de.zpipe_)(this.nativePath,h.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,E.clamp)(I.ShortCommandTimeoutMs,10*b.minuteMs,(await this.size()??0)*Q.MinIoRate)}dest(e){const t=e.clear();return(0,S.notBlank)(this.ext)&&(0,S.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,b.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,_.mapOr)(e.subdir,(e=>this.parent().join(e)),(()=>this.parent()));return this.mv_(i.join(this.name+"-"+t+this.ext))}async renameWithNameSuffix_(e){return(0,A.thenMap)(this.withNameSuffix(e).ensureNew_({emptyIsNew:!0}),(e=>e.unlink("debug").then((()=>this.mv_(e)))))}async saveIfNewOrDelete(e){if(await this.clear().isEmpty())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}async mv_(e,t=W.LogLevels.debug){const i=(0,L.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.pflog().warn("mv(): no-op",new Error("internal error")),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.pflog().log(t,"mv_()",{dest:i});try{await(0,ae.move_)(this.nativePath,i.nativePath)}catch(e){this.pflog().warn("mv() failed. Calling unlock() and retrying...",e),await Promise.all([this.unlock(),i.unlock()]),await(0,ae.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}async equalsUri_(e){return(0,X.uriIsEquivalent)(await this.uriObject_(),e)}}t.PosixFile=fe,n=new WeakSet,r=async function(e){let t,i=e;const n=e.wip();try{const r=await this.stat_();if(null==r)return this.pflog().throw("Can't copy missing files"+j.NonRetriableErrorFlag);if(r.size>0){if($.Settings.verifyFileCopies.valueOrDefault&&null==await this.sha())return this.pflog().throw("Can't copy file without SHA"+j.NonRetriableErrorFlag);if(null==await n.parent().mkdirp())return this.pflog().throw("Cannot mkdirp "+e.dir);if(await f.default.copyFile(this.nativePath,n.nativePath,h.default.constants.COPYFILE_FICLONE),r.size>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},r.size,(()=>n.size({refresh:!0})))),!await(0,N.untilTrue)((async()=>(0,E.approximates)(r.size,await n.size({refresh:!0}))),{intervalMs:b.secondMs,timeoutMs:b.minuteMs}))return this.pflog().throw("copyFile_() failed",{expectedSize:r.size,actualSize:await n.size({refresh:!0})});await this.maybeVerifySameOrThrow_(n),i=e.eql(n)?e:await n.mv_(e,W.LogLevels.trace)}try{await(0,ue.touch_)({file:i,btimeMs:r.birthtimeMs,mtimeMs:r.mtimeMs,ensureFile:!1})}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't set utimes to match source: ${e}`)}try{await d.chmod(i.nativePath,r.mode)}catch(e){this.pflog().warn(`copyFile_(${i.nativePath}): couldn't chmod to ${r.mode}: ${e}`)}return this.pflog().debug(`copyFile_(${i.nativePath}): success`),i}catch(t){throw this.pflog().warn(`copyFile_(${n?.nativePath}) failed: ${t}`),await n.unlink(),n.eql(e)||await e.unlink(),t}finally{i?.clearThisAndParent(),(0,_.map)(t,(e=>e.end()))}},s=async function(e){let t;const i=e.wip();try{if(null==await e.parent().mkdirp())return this.pflog().throw("Can't mkdir destination directory",{src:this.nativePath,dest:e.nativePath});const n=await this.stat_(),r=n?.size;return null==n||null==r?this.pflog().throw("Can't copy missing files"):(r>5*k.MiB&&(t=new q.PullProgressObserver({op:"Copying",path:this.nativePath,dest:i.nativePath},r,(()=>e.clear().size()))),U.isWin?await G.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,G.pwshQuote)(this.nativePath)} -Destination ${(0,G.pwshQuote)(i.nativePath)}`,(e=>e)):U.isMac?await(0,B.stdout_)("ditto",[this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}):await(0,B.stdout_)("cp",["-a","-f",this.nativePath,i.nativePath],{timeoutMs:await this.copyTimeoutMs()}),await this.maybeVerifySameOrThrow_(i),await i.mv_(e,W.LogLevels.trace),await(0,ue.touch_)({file:e,reference:this,ensureFile:!1}),e.clearThisAndParent())}catch(t){return await i.unlink(),this.pflog().throw("_nativeCopyFile("+e+") failed"+j.DoNotSendErrorFlag,{error:t})}finally{(0,_.map)(t,(e=>e.end()))}}},62105:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.acceptFile=t.whyRejectFile=t.expensiveFileFiltersFor=t.acceptParentAndFileAndSimple=t.acceptFileSimple=t.whyRejectFileSimple=t.simpleFileFiltersFor=t.notFileTooBig=t.notFileTooSmall=t.notFileMissing=t.hasBrowserImgMimeType=t.notDimensionsTooSmall=t.requiredTagsFilter=void 0;const n=i(40958),r=i(22573),s=i(31586),a=i(54993),o=i(48884),l=i(56519),u=i(78984),c=i(28874),d=i(43207),h=i(47783),f=i(97573),m=i(16170),p=i(54979),g=i(1078),y=i(42231),v=i(83278),w=i(19748),S=i(92423),b=i(16287);function P(e){return async t=>(0,l.thenMapOr)((0,h.readRawTags)(t,!1),e,(()=>!1))}async function M(e){if(!(0,s.gt0)(c.Settings.minVideoDimension.valueOrDefault)&&!(0,s.gt0)(c.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?c.Settings.minVideoDimension.valueOrDefault:c.Settings.minImageDimension.valueOrDefault;return(0,s.gt0)(i)?(0,l.thenMapOr)((0,g.extractSizeInfoFromFile)(e),(e=>(0,s.gte)(e.ImageWidth,i)&&(0,s.gte)(e.ImageHeight,i)),(()=>!1)):null}async function _(e){if(!(0,s.gt0)(c.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.gte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.minVideoDurationSec.valueOrDefault):null)}async function E(e){if(!(0,s.gt0)(c.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,p.readMimeType)(e);return null!=t&&((0,m.isVideoMimeType)(t)?(0,s.lte)((0,d.extractDurationSec)(await(0,h.readRawTags)(e,!1)),c.Settings.maxVideoDurationSec.valueOrDefault):null)}async function x(e){return!(0,r.blank)(await(0,p.readMimeType)(e))}async function T(e){if(-100===c.Settings.rejectRatingsLessThan.valueOrDefault)return null;const t=await(0,h.readTags)(e),i=(0,s.toInt)(t?.Rating);return null==i||i>=c.Settings.rejectRatingsLessThan.valueOrDefault}async function D(e){return 0===c.Settings.keywordBlocklist.values.length?null:(0,f.rawTagKeywords)(await(0,h.readTags)(e)).every((e=>!0!==(0,y.leafIsExcluded)(e,c.Settings.keywordBlocklist.values)))}async function k(e){if(!c.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,h.readRawTags)(e);return null==t||(0,r.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,r.notBlank)(t.Make)&&(0,r.notBlank)(t.Model):null}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,b.exists)(e.nativePath)}async function F(e){const t=c.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.gte)(i,t)}async function O(e){const t=c.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,s.lte)(i,t)}function I(e){return[{isSupportedFileExtension:w.isAssetFileExtension},...(0,S.notExcludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:F,notFileTooBig:O}]}function L(e){return[...I(e),{notMissingMimeType:x},{supportedMimeType:m.isAssetFileMimeType},{notMissingMakeAndModelTags:k},{notDimensionsTooSmall:M},{notVideoTooShort:_},{notVideoTooLong:E},{notRejectedRating:T},{notExcludedKeyword:D}]}async function A(e,t){return await u.Predicates.whyRejected(e,...t??L(e))??await(0,S.whyExcludedDirectoryRecursive)(e.parent())}t.requiredTagsFilter=function(e){return P((t=>(0,o.allNotBlank)(...e.map((e=>t[e])))))},t.notDimensionsTooSmall=M,t.hasBrowserImgMimeType=P((e=>(0,n.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))),t.notFileMissing=C,t.notFileTooSmall=F,t.notFileTooBig=O,t.simpleFileFiltersFor=I,t.whyRejectFileSimple=function(e){return u.Predicates.whyRejected(e,...I(e))},t.acceptFileSimple=function(e){return u.Predicates.accepted(e,...I(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,S.isExcludedDirectory)(t)&&await u.Predicates.accepted(e,...I(e))},t.expensiveFileFiltersFor=L,t.whyRejectFile=A,t.acceptFile=async function(e){return null==await A(e)}},78133:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const r=n(i(76760)),s=i(22573),a=i(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(r.default.sep===r.default.posix.sep)return e;const i=(0,s.notBlank)(t)?r.default.sep+r.default.sep+t+r.default.sep:"",n=e.split(r.default.posix.sep);return(0,a.equalsIgnoreCase)(n[0],t)&&n.unshift(),i+n.join(r.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||r.default.sep===r.default.posix.sep||r.default.posix.sep===r.default.sep?e:e.split(r.default.sep).join(r.default.posix.sep)}},43899:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const r=n(i(76760)),s=n(i(1708)),a=i(19851),o=i(40958),l=i(48884),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(25675),p=i(53265);function g(...e){return(0,a.lazy)((()=>r.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,a.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(r.default.join((0,p.execDir)(),"resources"),r.default.join((0,p.execDir)(),"..","Resources")),t.push(...(0,o.compactBlanks)([(0,p.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const i of t){if((0,f.hasChildrenSync)(i,e))return i;for(const t of(0,f.ancestors)(i).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const n=r.default.join(i,"node_modules","photostructure");if((0,f.hasChildrenSync)(n,e))return n}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:g("bin"),Data:g("data"),ICC:g("data","icc"),Migrations:g("data","migrations"),Public:g("public"),Tools:g("tools"),Views:g("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const n=i(44652),r=i(19851),s=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,r.lazy)((()=>(0,a.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=o.LogLevels.info){try{return await(0,n.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const n=i(44652),r=i(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s=-1;try{const r=i??(await(0,n.stat)(e)).size-t,a=Buffer.alloc(r);return s=await(0,n.open)(e,"r"),await(0,n.read)(s,a,0,r,t)}finally{(0,r.mapGte0)(s,n.close)}}},69428:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const a=s(i(73024));t.readFileSync=function(e){try{return a.readFileSync(e)}catch{}}},55690:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readLines_=void 0;const n=i(44652),r=i(84542);t.readLines_=async function(e){return(0,r.splitCompactLines)(await(0,n.readFile)(e))}},32323:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const n=i(57075);class r extends n.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=r},65238:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const r=n(i(51455)),s=i(76760),a=i(19851),o=i(76790),l=i(22573),u=i(42659),c=i(41400),d=i(31586),h=i(13538),f=i(83104),m=i(54127),p=i(50213),g=i(95937),y=i(34102),v=i(28874),w=i(63870),S=i(88561),b=i(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,a.lazy)((()=>(0,p.mkLogger)("fs.Readdir")));async function M(){try{await r.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=M;const _=(0,a.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function E(e){(0,l.blank)(e)||_.prior()?.delete(e)}async function x(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await _().getOrSetAsync(e,(()=>async function(e){const i=Date.now()+2*(0,b.statTimeoutMs)(),n=T(e),r=await(0,h.thenOrTimeout)(n,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(r===f.Timeout&&(0,g.onTimeout)({soft:!1}),r!==f.Timeout&&r.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=E,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),_.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),M()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?M():E(e)))})),t.slowDirs=(0,a.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!_().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){E(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=_().get(e)},t.childDirectories_=async function(e){return(await x(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?x(e):T(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=x,t.readdirCached=function(e){return _().get(e)},t.readdirUncached_=T},53265:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const r=i(73024),s=n(i(76760)),a=i(40958),o=i(22573),l=i(45599),u=i(50213),c=i(43334),d=i(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,a.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function p(...e){for(const t of m()){const i=s.default.resolve(t,...e);if((0,r.existsSync)(i))return i}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,o.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(o.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?p(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=p},46356:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=void 0;const n=i(22454),r=i(28874),s=i(29882);t.seemsLikeSymlinkLoop=function(e){const t=new n.CountingSet;for(const i of(0,s.toPathnames)(e))t.incr(i.toLowerCase().normalize());return t.max()>r.Settings.maxDuplicatePathElements.valueOrDefault}},50274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const n=i(50989);t.SidecarExts=(0,n.strEnum)("xmp","mie","exv")},14427:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const n=i(22573),r=i(38639);t.isSimpleDirent=function(e){return null!=e&&(0,n.notBlank)(e.basename)&&(0,r.isBoolean)(e.isFile)&&(0,r.isBoolean)(e.isDirectory)}},17217:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const r=n(i(73024)),s=n(i(76760)),a=i(22573),o=i(98553),l=i(81168),u=i(43334),c=i(29882),d=i(53265),h=i(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,a.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,a.blank)(e.nativePath))throw new Error(`toNativePath(${(0,o.stringify)(e)})`);return e.nativePath}function p(e){return e instanceof r.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=p,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(p(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const g=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(g)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),i=t.indexOf(s.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,o.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(r.default.stat(e),(0,g.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,o.blank)(e)?void 0:v(e).catch((i=>{y().log(t,"stat() failed",{error:i,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=S(e),n=S(t);if(i!==n)return"inconsistent file type: "+i+" ≠ "+n;for(const i of["size","mtime"]){const n=e[i],r=t[i],s=(0,u.diff)(b(n),b(r));if(null==s||s>1)return"unmatched "+i+": "+n+" ≠ "+r}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const i=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,p.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await w(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const i=await w(e,t);return null!=i&&i.isDirectory()&&(0,m.isStatRWX)(i,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const r=n(i(73024)),s=i(22573);function a(e){try{return(0,s.blank)(e)?void 0:r.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()}},41080:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const n=i(28874);t.statTimeoutMs=function(){return n.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const n=i(22573),r=i(56409);t.onDataChunked=function(e,t,i){const n=new s(t,i,!0);return n.read(e),n.done};class s{constructor(e,t,i=!0){this.sep=e,this.onData=t,this.filterBlanks=i,this.incompleteChunk="",this.done=new r.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,n.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,n.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const r=n(i(57075)),s=i(41400),a=i(55835),o=i(68708),l=i(42279),u=i(99331),c=i(70025);class d extends r.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((i,n)=>{!1===e.write(t,(e=>{e&&n(e)}))?e.once("drain",i):i()}))},t.endStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,o.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,o.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:i,ea:n}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,a.map)(n,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(i,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends r.default.Transform{constructor(e){super({transform:(e,t,i)=>{this.onProgress(this.bytes+=e.length),i(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const r=n(i(73024)),s=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return r.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))}},74128:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},m=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.SyncReport=t.syncReport=t.recentSyncReports=t.ensureSyncReportReadme=t.syncReportReadme=t.syncReportDir=t.SyncReportHeaders=t.isRejectedState=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0;const p=i(51168),g=i(73024),y=i(4927),v=i(19851),w=i(40958),S=i(22573),b=i(42659),P=i(98553),M=i(31586),_=i(68708),E=i(50989),x=i(51926),T=i(85556),D=i(54993),k=i(89788),C=i(23467),F=i(7282),O=i(23560),I=i(77377),L=i(71567),A=i(73568),R=i(25764),N=i(38836),B=i(99331),z=i(12959),j=i(87290),V=i(46296),W=i(98314),H=i(38835),U=i(5012),q=i(32144),G=i(95696),$=i(36868),J=i(57902),K=i(28874),Z=i(84542),X=i(73428);t.AssetFileSyncStates=(0,E.strEnum)("noop","deleted","skipped","synced","unknown"),t.SyncFileStates=(0,E.strEnum)(...t.AssetFileSyncStates.values,"canceled","rejected","failed","timeout","enqueued","started","copied","blocklisted","note"),t.FileDoneStates=(0,I.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,E.strEnum)("scanning","canceled","failed","timeout","skipped","scanned"),t.SyncReportStates=(0,E.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values),t.isRejectedState=function(e){return null==e||["canceled","deleted","failed","rejected","timeout","unknown"].includes(e)};const Y={enqueued:"the file looks promising, and will be attempted to be imported soon.",rejected:"the file did not pass all import filters. The details column will explain why.",started:"the file was dequeued from the work queue, and is now going to be processed.",noop:"the current file metadata already matches your library database, so no operation was needed to sync this file.",deleted:"the file was determined to be deleted (the prior mountpoint exists, but the file doesn't exist anymore)",skipped:"the file lives on a volume that isn't currently mounted.",synced:"the file was imported.",blocklisted:"the file was blocklisted and files with the same SHA will not be imported in the future.",failed:"something went wrong. The details column will explain why.",timeout:"the file wasn't processed in a reasonable amount of time.",copied:'"automatic organization" is enabled (copyAssetsToLibrary=true), and the photo or video was copied into your library originals directory. The details column will contain the source file path.',note:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",canceled:"PhotoStructure was shut down while the file was processed.",unknown:"an internal error occurred during processing."},Q={scanning:"the directory contents are about to be read.",scanned:"the directory contents were completely processed.",skipped:"the directory was excluded. The details column will explain why.",canceled:"PhotoStructure was shut down before the directory was processed.",failed:"reading the directory contents failed.",timeout:"reading the directory contents took too long."};function ee(e){return(0,_.entries)(e).map((([e,t])=>` - "${e}": ${t}`)).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncDirStates.canceled]);function ie(){return(0,j.librarySyncReportsDir)()??G.PosixFile.for((0,V.logDir)()).join("sync-reports")}function ne(){return ie().join("README.txt")}t.SyncReportHeaders=(0,E.strEnum)(...(0,_.keys)(new class{constructor(e,t,i,n,r,s,a,o,l={}){this.ts=e,this.at=t,this.path=i,this.state=n,this.from=r,this.elapsedMs=s,this.details=a,this.url=o,this.meta=l}}(0,"","","unknown","",0,"",""))),t.syncReportDir=ie,t.syncReportReadme=ne,t.ensureSyncReportReadme=(0,v.lazy)((()=>(0,X.writeTextfile_)(ne().nativePath,(0,x.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports". \n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path directory.\n\nThese CSV files can be opened with most spreadsheet applications, like LibreOffice.\n\n\nColumn descriptions\n===================\n\nThe "ts" column is the timestamp for the row, in millis from 1970-01-01. Most spreadsheet applications don’t know how to parse these values, though, so we also add the at column.\n\nThe "at" column is ts in ISO format with only second resolution, and should be parsable by most spreadsheet software.\n\nThe "path" column is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" column explains why that row was added.\n\nThe "from" column specifies which codepath added the sync report row.\n\nThe "elapsedMs" column is only added to rows completing a given path, and records how long that process took.\n\nThe "details" column will include information about the path, like why a given file or folder were rejected.\n\nThe "url" column is only added to rows when a file or directory is imported. You may need to adjust the domain name of the URL to make it work correctly (it defaults to localhost).\n\n\nDirectory state values\n======================\n\nThe "state" column for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" column for files will be\n\n${ee(Y)}\n\n\nSee https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n")))),t.recentSyncReports=async function(e=b.dayMs){const t=Date.now()-e;return ie().descendants((async e=>(0,q.isCsvExt)(e)&&(0,M.gte)(e.mtimeMs(),t)))},t.syncReport=(0,v.lazy)((()=>new re));class re extends N.EndableWrapper{constructor(){super("fs.SyncReport()",(()=>f(this,n,"m",d).call(this)),R.EndableRanks.predb),n.add(this),r.set(this,void 0),s.set(this,void 0),a.set(this,void 0),o.set(this,0),l.set(this,0),this.outputFiles=new k.BoundedList(64),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return f(this,r,"f")?.nativePath}get rowCount(){return f(this,l,"f")}onProgress(e){if(null==e||(0,S.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,U.stack)()});{this.logger.log(te.has(e.state)?J.LogLevels.warn:J.LogLevels.info,"onProgress()",e);const t=Date.now(),i={path:(0,D.toS)(e.path),state:e.state,details:(0,D.toS)(e.details).trim().replace(/\r?\n/g,"; ")},r={ts:t,at:new Date(t).toISOString(),...i,...(0,_.pick)(e,"from","elapsedMs","url")};(0,_.isEmptyObj)(e.meta)||(r.meta=(0,P.stringify)(e.meta)),(0,F.isTest)()&&process.stdout.write((0,P.stringify)(e)+Z.Newline),f(this,n,"m",u).call(this,r)}}maybeSystemData(e){(0,O.isSyncService)()&&this.onProgress(e)}async wrap_({path:e,from:i,fn_:n}){const r=Date.now();this.onProgress({path:e,from:i,state:t.SyncFileStates.started});try{const s=await n(),a=s.state??(null!=s.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return a===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+H.InternalErrorFlag,{path:e,result:s}),this.onProgress({path:e,from:i,elapsedMs:Date.now()-r,...s,state:a}),s}catch(n){throw this.logger.warn("wrap_() caught error",{error:n}),this.onProgress({path:e,from:i,state:(0,B.ending)()||n instanceof A.AbortError?t.SyncFileStates.canceled:n instanceof T.TimeoutError?t.SyncFileStates.timeout:t.SyncFileStates.failed,details:(0,B.ending)()?void 0:(0,W.errorToS)(n),elapsedMs:Date.now()-r}),n}}get output(){return f(this,s,"f")??f(this,n,"m",h).call(this)}async flushClose(){return f(this,n,"m",u).call(this),this.close()}async close(){this.logger.info("Closing sync report");const e=f(this,s,"f");return m(this,s,void 0,"f"),m(this,l,0,"f"),await(0,$.endStream)(e),null==e?void 0:f(this,r,"f")}}t.SyncReport=re,r=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,n=new WeakSet,u=function(e){var t;const i=f(this,a,"f");if(m(this,a,e,"f"),null!=e&&(0,C.eqlPicked)(e,i,"path","state","details"))return this.logger.debug("deduping row",e),void m(this,o,(t=f(this,o,"f"),t++,t),"f");null!=i&&(0===f(this,o,"f")?f(this,n,"m",c).call(this,i):(f(this,n,"m",c).call(this,{...i,details:(0,w.compactBlanks)([i.details,`(repeated ${f(this,o,"f")+1} times)`]).join(" ")}),m(this,o,0,"f")))},c=function(e){var i;const n=(0,y.unparse)([e],{header:!1,columns:t.SyncReportHeaders.values});this.output.write(n+Z.Newline,(e=>{null!=e&&this.logger.error("Failed to write",e)})),m(this,l,(i=f(this,l,"f"),++i),"f")>K.Settings.syncReportMaxRows.valueOrDefault&&this.close()},d=function(){return this.logger.info("sync report ended",{rowCount:f(this,l,"f"),outputFiles:this.outputFiles}),this.flushClose()},h=function(){return m(this,r,function(){const e=p.DateTime.now();return ie().join(e.toFormat("y-MM-dd"),(0,z.filestamp)()+"-sync-report.csv")}().ensureNewSync_({emptyIsNew:!1}),"f"),this.outputFiles.push(f(this,r,"f").nativePath),this.logger.info("Opening new report: "+f(this,r,"f")),(0,F.isTest)()&&(0,L.stdoutWrite)({syncReport:f(this,r,"f").nativePath},!1),m(this,s,(0,g.createWriteStream)(f(this,r,"f").nativePath),"f"),f(this,s,"f").write((0,y.unparse)([t.SyncReportHeaders.values],{header:!1})+Z.Newline),f(this,s,"f")}},89966:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=t.pathToTool_=t.osToolsDir=t.toolsDir=void 0;const r=n(i(48161)),s=i(19851),a=i(55835),o=i(51926),l=i(60172),u=i(38835),c=i(43334),d=i(83278),h=i(8103),f=i(43899);function m(){return(0,a.map)(f.ProjectPath.Tools(),(e=>d.BaseFile.for(e)))}function p(){return(0,a.map)(m(),(e=>e.join(c.platformName+"-"+r.default.arch())))}async function g(e){if(c.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),!0!==await(m()?.isDirectory()))throw new Error("Cannot find project path for /tools/"+u.FatalErrorFlag);return(0,l.firstDefinedLater)((()=>(0,h.pathIfExists)(m()?.join("bin",e))),(()=>(0,h.pathIfExists)(m()?.join(e))),(()=>(0,h.pathIfExists)(p()?.join(e))),(()=>async function(e){return(0,l.firstDefinedLater)((()=>(0,h.pathTo)({tool:e})),(()=>{throw new Error("Cannot find path for "+e)}))}(e)))}t.toolsDir=m,t.osToolsDir=p,t.pathToTool_=g,t.dcrawEmuNativePath_=(0,s.lazy)((()=>g("dcraw_emu"))),t.rawIdentifyNativePath_=(0,s.lazy)((()=>g("raw-identify"))),t.jpegtranNativePath_=(0,s.lazy)((()=>g("jpegtran"))),t.sqliteNativePath_=(0,s.lazy)((()=>g("sqlite3")))},27794:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const r=n(i(44652)),s=i(19851),a=i(22573),o=i(42659),l=i(31586),u=i(68708),c=i(13538),d=i(29882),h=i(17217),f=i(16287),m=i(41080);function p(e){return null==e?void 0:(0,o.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,a.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const o=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(p(t.mtimeMs)??(await o())?.mtimeMs??Date.now()),g=Math.round(p(t.atimeMs)??(await o())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(r.default.utimes(n,new Date(g),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(r.default.ensureFile(n),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},84258:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=t.logger=void 0;const a=s(i(51455)),o=i(19851),l=i(59455),u=i(50213),c=i(17217);t.logger=(0,o.lazy)((()=>(0,u.mkLogger)("fs.Unlink"))),t.unlink=async function(e,i="warn"){for(const n of(0,l.toA)(e))try{null!=n&&await a.unlink((0,c.toNativePath_)(n))}catch(e){(0,t.logger)().log(i,"Failed to unlink "+n,{error:e})}}},5545:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const r=n(i(76760)),s=i(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const i=t.driveRe.exec(e)?.groups;return null==i?e:i.drive.toUpperCase()+(0,s.toS)(i.path??r.default.sep)}},70257:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isWip=t.rmWipPrefix=t.addWipPrefix=t.WipPrefix=t.WipTimeoutMs=void 0;const n=i(30976),r=i(45255),s=i(17217);t.WipTimeoutMs=r.ShortCommandTimeoutMs,t.WipPrefix=".WIP-",t.addWipPrefix=function(e){return t.WipPrefix+(0,n.randomChars)(5).toUpperCase()+"-"+e};const a=/^.WIP-[\da-z]{5}-/i;t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,s.basename)(e)??"")}},58722:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const n=i(57075),r=i(22911);class s extends n.Writable{constructor(e){super(e),this.deferred=new r.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=s},73428:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const r=n(i(44652)),s=n(i(76760)),a=i(51926),o=i(54993),l=i(34102),u=i(84542),c=i(29882);async function d(e,t){const i=s.default.dirname(e);await(0,c.mkdirp_)(i),await r.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",i)}function h(e,t){const i=s.default.dirname(e);(0,c.mkdirpSync_)(i),r.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",i)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,u.crlf)(...(0,a.wrap)(t));await d(e,i)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,a.ensureSuffix)(t.map(o.toS).join("\n"),"\n")))}},13047:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const r=n(i(73024)),s=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(80875),h=i(50213),f=i(57159),m=i(29882),p=i(57902),g=i(32323),y=i(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,i){const n=[],s=[r.default.createReadStream(e,{autoClose:!0,...i}).on("error",(e=>n.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,o.createGunzip)().on("error",(e=>n.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,o.createBrotliDecompress)().on("error",(e=>n.push(e)))),s.push(t),await(0,a.pipeline)(s),(0,u.isNotEmpty)(n))throw new f.WrappedError("zPipe("+e+") failed",{causes:n,path:e})}async function b(e,t){const i=new y.WritableToBuffer;return await S(e,i,t),await i.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),r.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=p.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=p.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}}},680:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=["library-db","library-directories","library-free-space","nodejs-version","proc-not-in-dmg","tools-exiftool","test-health-check","tools-powershell","tools-sharp","tools-sqlite-version"],t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},18454:function(e,t,i){var n,r,s,a,o,l,u,c,d,h,f,m,p,g,y,v,w,S,b,P,M=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},_=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const E=i(19851),x=i(40958),T=i(76790),D=i(22573),k=i(41400),C=i(50357),F=i(26905),O=i(50268),I=i(55835),L=i(68708),A=i(30976),R=i(51926),N=i(13538),B=i(42279),z=i(59455),j=i(54993),V=i(48884),W=i(89788),H=i(22454),U=i(50213),q=i(69591),G=i(22911),$=i(99331),J=i(5916),K=i(42638),Z=i(77740),X=i(98314),Y=i(70025),Q=i(28874),ee=i(63870),te=i(30933),ie=i(680),ne=i(33866),re=i(21525),se=i(82638),ae=(0,E.lazy)((()=>(0,U.mkLogger)("health.HealthCheck")));class oe{static traceLater_(e,t){const i=new G.Deferred(e);i.catch((t=>{M(this,r,"f",l).push(e+": failed: "+(0,X.errorToS)(t)),this.onResultChange()})),M(this,r,"m",o).call(this).push(i);try{return i.observe((0,B.tot)(t))}catch(e){throw i.reject(e),e}}static priorRunStates(){return M(this,r,"f",c).toA()}static allCritical(){return this.all().filter((e=>e.isCritical))}static addError(e){M(this,r,"f",l).push((0,R.isString)(e)?e:(0,X.errorToS)(e)),this.onResultChange()}static lastErrors(){return M(this,r,"f",l).toA()}static addLoadingMsg(e){M(this,r,"f",d).push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,x.compact)((0,z.toA)(e)).map(j.toS).join("\n").replace(/\n{3,}/g,"\n\n").replace(/\n{2,} {2}- /g,"\n - ").trim().split("\n")}static unseenOrOldestPendingTrace(){const e=this.allCritical().map((e=>e.result())).filter((e=>e.isPending));return ae().info("unseenOrOldestPendingTrace",{pending:e.map((e=>({name:e.name,id:e.id}))),shownCounts:M(this,r,"f",h).entriesByCountDesc()}),(0,I.map)((0,V.leastBy)(e,(e=>[M(this,r,"f",h).get(e.name),e.startedAt])),(e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt})))}static loadingMsg(){const e=M(this,r,"f",d).shift()??this.unseenOrOldestPendingTrace();return(0,I.map)(e,(e=>M(this,r,"f",h).incr(e.msg))),ae().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?ne.HealthCheckIds.values:[];return Q.Settings.skipHealthCheckIds.envValue=t,r.reset()}static findById(e){return M(this,r,"f",f).find((t=>t.id===e))}static testResults(){return this.all().map((e=>e.result()))}static testResultsCritical(){return this.allCritical().map((e=>e.result()))}static async errorResults(){return(await Promise.all(this.testResults())).filter((e=>"error"===e.level))}static async notOkResults(){return(await Promise.all(this.testResults())).filter((e=>(0,O.levelIsNotOK)(e.level)))}static runState(){return this.summary().state}static summaryFromResults(e){const t=M(this,r,"m",m).call(this,e);return this.summary.set(t),t}static async awaitSettled(){let e=r.summary();if(e.pendingCount>0){const t=await Promise.all(r.testResultsCritical());e=r.summaryFromResults(t),ae().info("awaitSettled(): summary result",{summary:e,results:t})}return ae().tap({msg:"awaitSettled(): done",level:"info",result:e})}static rerunSetup(){return this.reset(),this.awaitSettled()}static onResultChange(){r.summary.unset()}static reset(){if((0,$.ending)())ae().warn("Rejecting reset() when ending()",(0,F.shortStack)());else{this.onResultChange(),M(this,r,"f",l).clear(),M(this,r,"f",d).clear(),M(this,r,"f",h).clear(),M(this,r,"f",c).clear(),this.summary.clear(),_(this,r,!1,"f",u);for(const e of this.all())e.reset()}}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new r(e.section,e.id,e.pendingMsg,e.settings,e.later,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return M(this,r,"f",f).push(i),this.all.unset(),i}constructor(e,t,i,s,o,l,u,c,d,h,f,m,b,P=ee.commandTimeoutMs){n.add(this),this.section=e,this.id=t,this.pendingMsg=i,this.settings=s,this.ordinal=l,this.links=u,this.okLinks=c,this.warnLinks=d,this.noLibraryLinks=h,this.errorLinks=f,this.onReset=m,this.ttlMs=b,this.timeoutMs=P,p.set(this,void 0),g.set(this,{starting:!0}),y.set(this,0),w.set(this,(0,E.lazy)((async()=>{await M(this,p,"f").prior(),(0,C.eql)(M(this,g,"f"),M(this,n,"m",v).call(this))||(this.onReset?.(),await this.refresh(),M(this,w,"f").unset())}))),this.refresh=(0,E.lazy)((()=>new G.Deferred("refresh").observe((async()=>{await M(this,p,"f").prior();const e=M(this,p,"f").refresh();return e.finally((()=>this.refresh.unset())),e})()))),this.logger=(0,U.mkLogger)("health.HealthCheck."+this.id),this.isCritical=ie.CriticalHealthCheckIds.includes(this.id),this.sortBy=[O.HealthCheckSections.ordinal(this.section),l??999,this.id],_(this,p,(0,J.lazyAsync)({desc:this.pendingMsg,later:()=>M(r,r,"f",a).enqueue({name:this.id,l:()=>M(this,n,"m",S).call(this,o)}),ttlMs:b}),"f"),this.isCritical&&M(this,p,"f").watchLater({onChange:r.onCriticalResult,onError:r.onCriticalResult});for(const e of this.settings)Q.Settings[e].watchLater((()=>M(this,w,"f").call(this)))}isStale(){return M(this,p,"f").isStale()}isPending(){return null==this.toResultSyncMaybe()}settledAtLeastOnce(){return M(this,p,"f").settledCount()}reset(){return M(this,p,"f").unset(),this.onReset?.(),_(this,g,{starting:!0},"f"),this}setTTL(e){M(this,p,"f").setTTL(e)}result(){return M(this,p,"f").call(this)}isSkipped(){return Q.Settings.skipHealthCheckIds.values.includes(this.id)}toLevelSync(){return M(this,p,"f").lastValue()?.level??"pending"}toResultSyncMaybe(){return M(this,p,"f").lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=Date.now();return await(0,N.thenOrTimeoutMaybe)(this.result(),e)??M(this,n,"m",P).call(this,{error:"Timeout",level:"warn",elapsedMs:Date.now()-t})}}function le(e){if((0,x.isEmpty)(e))return{};const[t,i]=(0,V.partition)(e,(e=>"button"===e.type||"POST"===e.method)),n={};return(0,x.isNotEmpty)(i)&&(n.links=(0,x.uniqBy)(i)),(0,x.isNotEmpty)(t)&&(n.buttons=(0,x.uniqBy)(t)),n}t.HealthCheck=oe,r=oe,p=new WeakMap,g=new WeakMap,y=new WeakMap,w=new WeakMap,n=new WeakSet,o=function(){return(0,x.filterInPlace)(M(this,r,"f",s),(e=>!e.isPending)),M(this,r,"f",s)},m=function(e){const t=e??this.allCritical().map((e=>e.toResultSync())),i=ae().tap({level:"warn",msg:"#summary()",result:(0,se.summarizeHealthChecksSync)({errors:M(this,r,"f",l),skipPending:M(this,r,"f",u),healthCheckResults:t}),meta:{healthCheckResults:t}});return i.settled&&_(this,r,!0,"f",u),i.state!==M(this,r,"f",c).last?.state&&M(this,r,"f",c).push({state:i.state,ts:Date.now()}),i},v=function(){return(0,L.fromEntries)(this.settings.map((e=>[e,Q.Settings[e].valueOrDefault])))},S=async function(e){const t=Date.now(),i=this.timeoutMs()??(0,ee.commandTimeoutMs)();ae().debug("#wrapLater() starting",{id:this.id,timeoutMs:i,caller:(0,F.shortStack)()}),_(this,g,M(this,n,"m",v).call(this),"f");try{if((0,Z.getDevEnvFlag)("PS_SLOMO")&&await(0,k.delay)((0,A.randomInt)(.3*i,.7*i)),this.isSkipped())return M(this,n,"m",b).call(this,{test:{level:"disabled",msg:["Disabled by "+Q.Settings.skipHealthCheckIds.key]},elapsedMs:Date.now()-t});const r=await(0,N.thenOrTimeoutError)(e(),i);return M(this,n,"m",b).call(this,{test:r,elapsedMs:Date.now()-t})}catch(e){return M(this,n,"m",P).call(this,{error:e,elapsedMs:Date.now()-t})}},b=function({test:e,src:t="#toResult",elapsedMs:i}){var n,s;const a=r.normalizeMsg(e.msg),o=e.level??((0,j.toS)(a).toLowerCase().includes("error")?"error":(0,j.toS)(a).toLowerCase().includes("warn")?"warn":"ok"),l=(0,x.compact)([...e?.links??("ok"===o||"pending"===o?this.okLinks:"warn"===o?this.warnLinks:"no-library"===o?this.noLibraryLinks:"error"===o?this.errorLinks:[])??[],...this.links??[]]),u={section:this.section,id:this.id,ts:Date.now(),level:o,msg:a,elapsedMs:i,...le(l)};return u.runCount=(_(this,y,(s=M(this,y,"f"),n=s++,s),"f"),n),(0,$.ending)()?u:this.logger.tap({level:re.HealthCheckLevelToLogLevel[o],msg:t,result:u})},P=function({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const r=(0,R.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,D.toNotBlank)((0,X.errorToS)(e))??"(missing error)");return t??(t=!this.isCritical||!(0,Y.isFatalError)(e)&&r.toLowerCase().includes("warn")?"warn":"error"),M(this,n,"m",b).call(this,{test:{msg:r,level:t},src:"#toErrorResult",elapsedMs:i})},s={value:[]},a={value:new K.Promises("HealthCheck",(()=>(0,te.cpuCount)()))},l={value:new W.BoundedList(10)},u={value:!1},c={value:new W.BoundedList(10)},d={value:new W.BoundedList(100)},h={value:new H.CountingSet},f={value:[]},oe.all=(0,E.lazy)((()=>Object.freeze((0,T.sortBy)(M(r,r,"f",f),(e=>e.sortBy))))),oe.onCriticalResult=(0,q.debounce)((()=>{ae().info("onCriticalResult()",r.summary.refresh())}),250),oe.summary=(0,E.lazy)((()=>M(r,r,"m",m).call(r))),oe.resetDebounced=(0,q.debounce)((()=>r.reset()),50)},33866:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const n=i(50989);t.HealthCheckIds=(0,n.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},21525:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.summaryForLevel=t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=t.isHealthCheckLevelFatal=void 0;const n=i(82950),r=i(50268),s=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===r.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===r.HealthCheckLevels["no-library"])},t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"],t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,n.tt)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new s.UnreachableCaseError(e)}}},42495:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.restartResetOrShutdownButtons=t.WhatIsALibraryLink=t.DockerVolumeLink=void 0;const n=i(40958),r=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"},t.restartResetOrShutdownButtons=function(){return(0,n.compact)([(0,r.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])}},89035:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=t.memoryUsageTest=void 0;const r=n(i(48161)),s=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:n}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.li)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(n,2)])]}}function g(){return r.default.totalmem()f.Settings.maxMemoryMb.valueOrDefault?p({level:"error",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):(0,u.gt0)(f.Settings.maxMemoryMb.valueOrDefault)&&(0,d.memoryUsageMb)()>.75*f.Settings.maxMemoryMb.valueOrDefault?p({level:"warn",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB}):p({level:"ok",desc:"Used memory",bytes:(0,d.memoryUsageBytes)(),thresholdBytes:f.Settings.maxMemoryMb.valueOrDefault*c.MB})}t.memoryUsageTest=g,t.memoryUsageIsHigh=(0,s.lazy)((()=>"ok"!==g().level),o.secondMs),t.memoryHealthCheck=(0,l.defer)((()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",settings:["maxMemoryMb"],errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/bounce",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()})))},82638:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecksSync=t.summarizeHealthChecks=void 0;const n=i(40958),r=i(42659),s=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(21525),g=i(42495),y=(0,s.defer)((()=>(0,d.mkLogger)("health.SummarizeHealthChecks")));async function v({healthChecks:e,healthCheckResults:t,refresh:i,timeoutMs:n}){const r=new Map;for(const e of t??[])r.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map((e=>!0===i?e.refresh():e.result())),n))r.set(t.id,t);return[...r.values()]}t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await v(e)})};const w=(0,c.lazy)((()=>({...l.BaseHealthCheckSummary,libraryDir:m.Settings.libraryDir.valueOrDefault??null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}})));function S(e){const t=(0,n.uniqBy)(e.healthCheckResults,(e=>e.id)),i=t.filter((e=>"pending"===e.level)),s=i.length,a=i.map((e=>e.id)),c=t.length-s,d=0===s,h=(0,n.uniq)((0,n.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,g.restartResetOrShutdownButtons)()};for(const i of p.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const r=t.filter((e=>e.level===i));if((0,n.isNotEmpty)(r)){const e=t.filter((e=>!r.includes(e)&&(0,l.levelIsNotOK)(e.level))),u=(0,p.summaryForLevel)(i);return y().tap({msg:"summary() found "+r.length+" "+u.level+" checks",level:p.HealthCheckLevelToLogLevel[u.level],result:{...w(),level:u.level,state:u.state,links:u.links,buttons:u.buttons,settled:d,pendingIds:a,pendingCount:s,settledCount:c,linkIds:r.map((e=>e.id)),ts:Date.now(),msg:(0,n.uniq)([...u.msg,...u.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...r,...e].map((e=>e.msg[0])))])},meta:{checks:r.map((e=>e.id))}})}}return y().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:s,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,r.fmtDateShort)(Date.now())]}})}(0,a.later)((()=>{m.Settings.libraryDir.watchLater((()=>w.unset()))})),t.summarizeHealthChecksSync=S},95242:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=t.mkPreviewAssetFile_=void 0;const a=i(57975),o=i(40958),l=i(22573),u=i(33374),c=i(98553),d=i(55835),h=i(68708),f=i(48884),m=i(50213),p=i(92434),g=i(54296),y=i(51837),v=i(57159),w=i(83278),S=i(95696),b=i(62105),P=i(84258),M=i(38156),_=i(69589),E=i(28874),x=i(47783),T=i(29990),D=i(16047),k=i(42725),C=i(4192),F=i(32876),O=i(50961),I=i(181);t.mkPreviewAssetFile_=async function(e){const t=await(0,x.readTags)(e);return{nativePath:e.nativePath,fileSize:await e.size(),mtime:await e.thisOrSidecareMaxMtimeMs(),uri:await e.uri_(),mountpoint:(await e.mountpoint())?.nativePath,mimetype:t.mimetype,rotation:t.rotation,...t.dimensions,sha:await e.sha_()}};class L{constructor(e,t,i){n.add(this),this.ap=e,this.assetFiles=t,this.logger=(0,m.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,_.forceContextOrSetting)(i),this.assetFiles=(0,p.sortAssetFiles)(this.assetFiles)}[(n=new WeakSet,a.inspect.custom)](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map((e=>(0,h.pick)(e,"id","uri"))));const e=[];for(const t of this.assetFiles){const i=S.PosixFile.forMaybe(await(0,g.getAssetFileNativePath)(t));if(null!=i){{const e=await(0,b.whyRejectFile)(i);(0,l.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await s(this,n,"m",r).call(this,i,t)}catch(i){e.push(i),this.logger.warn("Failed to set shown file to ",{best:t,error:i})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,c.stringify)((0,h.pick)(t,"uri","mountpoint","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{doNotSend:!0,retriable:!1,files:this.assetFiles.map((e=>e.nativePath??e.uri)),causes:e})}async infoForBest_(e,t){await(0,I.throwIfInvalidFile_)(e);const i=await e.size(),n=await e.thisOrSidecareMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:n,best:t.uri}),null==i||null==n)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:r,width:s,height:a,sha:l,mimetype:u}=t;if(null==r||null==s||null==a||null==u||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const c=(0,T.fitSizes)(t,t.mimetype);return{assetId:t.assetId,assetFileId:t.id,uri:r,uris:this.assetFiles.map((e=>e.uri)),path:e.nativePath,mtime:n,filesize:i,width:s,height:a,sha:l,mimetype:u,fitSizes:c.map((([,e])=>e.name)).join(","),sqWidths:(0,o.compact)(k.ImageSize.sq().map((e=>e.outputSize(t)?.width))),fitWidths:c.map((([e])=>e.width))}}async priorIfValid_(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new y.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,c.stringify)({priorInfo:i,info:t}));const n=i.fitSizes.split(","),r=t.fitSizes.split(",");if(null!=i.sha&&i.sha===t.sha&&i.rotation===t.rotation&&(0,T.equivalentFitSizes)(n,r)){const s=(0,T.fitSizes)(e,e.mimetype),a=(0,o.diff)(n,r);if((0,o.isNotEmpty)(a)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:a});for(const e of a){const t=s.find((([,t])=>t.name===e));if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:s});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): SHA and rotation match, and previews exist.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}}t.AssetPreviewBuilder=L,r=async function(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.infoForBest_(e,t),n=await this.priorIfValid_(t,i);if(null!=n)return n;const r=new M.PushProgressObserver({path:e.nativePath,op:"Building previews"},k.ImageSize.sq().length+k.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const s=await this.ap.existingFiles(),a=await(0,O.sharpReadable_)({src:e,minDim:k.ImageSize.largestFit().max});if(null==a)throw new v.WrappedError("AssetPreviewBuilder.build(): "+t.uri+", "+e.nativePath+", is not readable by sharp.",{retriable:!1});const o=(0,O.toSharp)(a);if(t.mimetype.startsWith("image/")&&!(0,D.isHeifMimeType)(t.mimetype)&&null!=t.rotation&&0!==t.rotation&&(o.rotate(t.rotation),this.logger.debug("build(): rotating "+t.rotation+"°")),(0,w.isBaseFile)(a)&&a.desc.toLowerCase().includes("thumbnail"))try{o.trim(1)}catch{}const l=(0,T.fitSizes)(t,t.mimetype),c=[],m=[];let p,g;const y=k.ImageSize.largestSq(),S=(0,f.leastBy)(l,(([e,t])=>(0,d.map)(y.outputSize(e),(()=>t.megapixels()))))?.[1].name,b=(0,h.pick)(t,"width","height");{let e=o.clone(),t=b;for(const[i,n]of l){const s=Date.now(),a=t,o=this.ap.fileForWidth(n.reducer.name,i.width).wip();e=n.resize(i,e),t=i,n.name===S&&(g=e.clone(),p=i),(0,u.dmegapixels)(i)>=1&&n.reducer===F.Fit&&E.Settings.includePreviewTags.valueOrDefault&&m.push(o),await n.toJpeg({path:o.nativePath,sh:e,outputSize:i}),r.onProgress(),this.logger.debug("resize("+n.name+") "+(0,u.fmtDim)(a)+" -> "+(0,u.fmtDim)(i)+" in "+(Date.now()-s)+" ms"),c.push(o)}}{null==g?(this.logger.debug("square resize(): resorting to ",{origDim:b,bestFitNameForSq:S}),g=o,p=b):this.logger.debug("square resize(): using to ",{sqDim:p,bestFitNameForSq:S});let e=!1;for(const t of k.ImageSize.sq()){const i=Date.now(),n=p,s=t.outputSize(p??b);if(null==s){this.logger.debug("skipping square output for "+t.max);continue}e||(s.position=E.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:s});const a=this.ap.fileForWidth(t.reducer.name,s.width).wip();t.resize(s,g),p=s,await t.toJpeg({path:a.nativePath,sh:g,outputSize:s}),r.onProgress(),c.push(a),this.logger.debug("resize("+t.name+") "+(0,u.fmtDim)(n)+" -> "+(0,u.fmtDim)(s)+" in "+(Date.now()-i)+" ms")}}try{await(0,C.includePreviewTags_)(e,m).catch((t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})}));const t=new Set(s.map((e=>e.nativePath)));for(const e of c){const i=await e.unwip_();t.delete(i.nativePath)}await(0,P.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,P.unlink)(c),new v.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}},35721:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkDownloadableTitle=t.previewToDownloadable=t.extractPreviewInfo=void 0;const n=i(75761),r=i(33374),s=i(11371),a=i(55835),o=i(31586),l=i(56519),u=i(29882),c=i(50213),d=i(97352),h=i(81168),f=i(89782),m=(0,c.mkLogger)("extractPreviewInfo");function p(e,t,i,n){return`Download ${t} ${e.ext} ${i} (${(0,r.fmtDim)(n)})`}t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),n=(0,o.toInt)(i[0]),r=s.ReducerNames.getCI(i[1]),a=(0,d.extractInt)(i[2]);return(0,o.gt0)(n)?{file:t,assetId:n,reducer:r,width:a}:void m.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:n,reducer:r,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,((i,a)=>(0,l.thenMap)((0,f.dimensions)(t.file),(o=>{const l=(0,r.dimToSize)(o);return{size:l,basename:`${(0,h.stripSuffix)(e,(0,u.extname)(e))}-${l}${t.file.ext}`,title:p(t.file,l,"image",o),description:`Download ${l}`,details:`(${(0,r.fmtDim)(o)} ${t.file.ext})`,href:(0,n.assetImgLink)({assetId:i,reducer:s.ReducerNames.fit,width:a})}}))))},t.mkDownloadableTitle=p},16524:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const a=i(19851),o=i(40958),l=i(75761),u=i(11371),c=i(68708),d=i(39926),h=i(58939),f=i(48884),m=i(50213),p=i(81168),g=i(56519),y=i(38835),v=i(70417),w=i(35721);t.AssetPreviews=class{constructor(e,t){n.add(this),this.previewsRoot=e,this.readInfo=(0,a.lazy)((()=>this.infoJson().readJson("debug"))),this.logger=(0,m.mkLogger)("AssetPreviews(assetId:"+(0,h.id2id)(t)+")"),this.assetId=(0,h.id2id)(t);const i=(0,d.leftPad)(this.assetId,8,"0"),r=(0,p.splitEvery)(i,3);this.basename=r.pop()+"-",this.parent=e.join(...r)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles((e=>e.base.startsWith(this.basename)))??[]}async existingJpgs(){return(await this.existingFiles()).filter((e=>".jpg"===e.ext))}async previewInfos(){return(0,g.sortByAsync)({name:"img.AssetPreviews.previews",arr:s(this,n,"m",r).call(this),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+y.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}writeInfo(e){return this.readInfo.unset(),this.infoJson().writeJson((0,c.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","sha","rotation","fitSizes","fitWidths"))}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter((e=>e.base.startsWith(t)))})}async smallestFileForReducer(e){return(0,f.leastBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async largestFileForReducer(e){return(0,f.greatestBy)(await this.filesForReducer(e),(e=>(0,w.extractPreviewInfo)(this.previewsRoot,e)?.width))}async widths(e){const t=await this.readInfo(),i=e===u.ReducerNames.sq?"sqWidths":"fitWidths",n=t?.[i];if(!(0,o.isEmpty)(n))return n;const r=(0,o.compact)((await this.previewInfos()).filter((t=>t.reducer===e)).map((e=>e.width)));return null!=t&&(t[i]=r,await this.writeInfo(t)),r}async posterLink(){const e=await this.widths(u.ReducerNames.fit);return(0,l.assetImgLink)({assetId:this.assetId,reducer:u.ReducerNames.fit,width:(0,v.max)(e)})}async imgAttrs(e,t=!1,i=!0){if(t||e!==u.ReducerNames.sq){const t=e===u.ReducerNames.fit?await this.readInfo():void 0;return(0,l.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,l.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}},n=new WeakSet,r=async function(){const e=[];for(const t of await this.existingFiles()){const i=(0,w.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}},52086:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const n=i(50989);t.CropStrategies=(0,n.strEnum)("center","entropy","attention")},33106:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.dctPixels=t.dctHashCIELAB=t.dctHash=void 0;const r=n(i(9288)),s=i(96249),a=i(85810),o=32,l=function(e){const t=new Array(32);for(let e=1;e<32;e++)t[e]=1;return t[0]=1/Math.sqrt(2),t}(),u=function(e){const t=new Array(e);for(let i=0;ir?1:0);return s}t.dctHash=async function(e){return c(await e.greyscale().resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer())},t.dctHashCIELAB=async function(e){const t=await e.resize({width:o,height:o,fit:r.default.fit.fill}).raw().toBuffer(),i=(0,a.rgb2labArray)(t);return(0,s.flatten)(i.map(c))},t.dctPixels=c},86580:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validRotations=t.rotateDimensions=t.aspectRatio=t.fitToResolution=t.parseDimensions=t.ltEither=t.lteBoth=t.ltBoth=t.tmegapixels=void 0;const n=i(40958),r=i(33374),s=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){return null!=e&&(0,s.gt0)(e.width)&&(0,s.gt0)(e.height)?(0,s.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3):void 0}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}t.tmegapixels=function(e){return null!=e.dimensions?(0,r.dmegapixels)(e.dimensions):(0,s.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,s.lt)(e.width,t.width)&&(0,s.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,s.lte)(e?.width,t?.width)&&(0,s.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,s.lt)(e.width,t.width)||(0,s.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,n.compact)((0,o.toS)(e).split(/[x×]/).map((e=>(0,s.toInt)(e))));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,n=Math.round(Math.sqrt(t*i));return{width:n,height:Math.round(n/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const n=u(e,i);return null==n?[]:a.Rotations.filter((e=>u(c(t,e),i)===n))}},89782:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=void 0;const n=i(19851),r=i(31586),s=i(50213),a=i(56519),o=i(1078),l=i(5733),u=(0,n.lazy)((()=>(0,s.mkLogger)("img.FileDimensions")));t.dimensions=async function(e){try{if(null==e)return;if((0,l.isSharp)(e)){const t=await e.metadata();return(0,r.map2Numeric)(t.width,t.height,((e,t)=>({width:e,height:t})))}return(0,a.thenMap)((0,o.extractSizeInfoFromFile)(e),(e=>({width:e.ImageWidth,height:e.ImageHeight})))}catch(e){return void u().warn("dimensions() failed",{error:e})}}},29990:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.equivalentFitSizes=t.fitSizes=void 0;const n=i(40958),r=i(33374),s=i(16170),a=i(42725),o=[a.ImageSize.QVGA,a.ImageSize.QQVGA];function l(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}t.fitSizes=function(e,t){const i=a.ImageSize.fit(),n=[];let l=(0,s.isMimeTypeSupportedByBrowser)(t)?e:void 0;for(let t=0;t3||(0,r.dmegapixels)(a)-(0,r.dmegapixels)(l)>2.5)&&(l=a,n.push([a,s])))}return n},t.equivalentFitSizes=function(e,t){return(0,n.includesAll)((0,n.compactBlanks)(e).map(l),(0,n.compactBlanks)(t).map(l))}},277:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2img=t.isHeifSupported=t.extractHeifConvertVersion=t.getHeifSupportDetails=void 0;const n=i(22573),r=i(41400),s=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(28874),g=i(91354),y=i(36192),v=(0,a.lazy)((()=>(0,o.mkLogger)("img.Heif")));function w(e){return(0,s.toS)(e).match(/(?:heif-convert|libheif)\s+version[^\d.]*(?[\d.]{5,})/i)?.groups?.version}async function S(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}t.getHeifSupportDetails=(0,a.lazy)((async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,n.blank)(e))return{path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,n.blank)(e))return void v().warn("Failed to find heif-convert",{heifConvertPath:p.Settings.heifConvertPath.valueOrDefault});{let t="",i=w(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,n.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find((e=>"libheif-examples"===e.pkg))?.version}return(0,n.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{path:e,version:(0,n.toNotBlank)(i)??"(unknown)",isSupportedVersion:!0}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}})),t.extractHeifConvertVersion=w,t.isHeifSupported=S,t.heif2img=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await S()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})},(0,r.later)((()=>(0,d.ee)().on("clearCache",(()=>t.getHeifSupportDetails.unset()))))},91354:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.heif2png_=t.isHeifConvertSupported=t.heifConvertPath=void 0;const n=i(19851),r=i(22573),s=i(42659),a=i(41400),o=i(12168),l=i(50213),u=i(84777),c=i(34102),d=i(8103),h=i(28874),f=i(89782),m=i(13940),p=(0,n.lazy)((()=>(0,l.mkLogger)("img.HeifConvert")));function g(){t.heifConvertPath.unset()}async function y(){return(0,r.notBlank)(await(0,t.heifConvertPath)())}t.heifConvertPath=(0,n.lazy)((async()=>{const e=p().tap({msg:"heifConvertPath",result:await(0,d.pathTo)({tool:"heif-convert",alternativePath:h.Settings.heifConvertPath.valueOrDefault})});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e})),(0,a.later)((()=>{(0,c.ee)().on("clearCache",g),(0,c.ee)().on("clearToolCache",g)})),t.isHeifConvertSupported=y,t.heif2png_=async function(e){if(await y())return null==await(0,f.dimensions)(e)&&p().throw("heif2png_() failed: no dimensions for "+e),(0,m.withImageCache_)(e,"heif",".png",(t=>async function(e,t){try{await(0,u.stdoutResult_)(h.Settings.heifConvertPath.valueOrDefault,[e.nativePath,t.base],{cwd:t.dir,timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await t.clear().isEmptyFile(o.KB)&&p().throw("heif2png_() failed: empty output",{src:e,dest:t})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,t)))}},16047:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHeifMimeType=void 0;const n=i(22573),r=i(54993),s=/^image\/hei[fc]$/i;t.isHeifMimeType=function(e){return!(0,n.blank)(e)&&s.test((0,r.toS)(e))}},13940:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.withImageCache_=t.readableToFile_=t.cachedImageFile_=t.tmpImageFile_=t.rmImageCacheDir=t.imageCacheDir_=t.ImageCacheName=void 0;const n=i(51455),r=i(19851),s=i(42659),a=i(59455),o=i(54993),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(17217),v=i(55222),w=i(63870),S=(0,r.lazy)((()=>(0,l.mkLogger)("img.ImgCache")));t.ImageCacheName="image-cache",t.imageCacheDir_=(0,r.lazy)((()=>(b(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName).mkdirp_())));const b=(0,r.lazy)((()=>{f.cacheDir_.watchLater((()=>t.imageCacheDir_.unset()))}));async function P(e,i,n){const r=await(0,t.imageCacheDir_)();i??(i=e.name),n=(0,c.ensurePrefix)(n??e.ext,".");const s=r.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await s.mkdirp_(),await s.utimes();const a=s.join(i+n);return S().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:n,result:a}),a}t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");for(const e of(0,a.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,n.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0});(0,p.ee)().emit("fileChanged"),(0,p.ee)().emit("clearCache")},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),n=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,y.basename)(e.src.dir).normalize(),e.src.name.normalize(),e.tag+e.ext):i.join("tmp-"+v.TokenRadix.randomChars(2),v.TokenRadix.randomChars(16)+(0,o.toS)(e.ext));return await n.parent().mkdirp_(),n},t.cachedImageFile_=P,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:n}){return(await P(e,t,i)).applyIfEmpty_({fn_:n,timeoutMs:2*s.minuteMs})},t.withImageCache_=async function(e,t,i,n){try{const r=await P(e,t,i);return await r.applyIfEmpty_({fn_:n,skipFsLock:!1,skipWip:!1,timeoutMs:(0,w.commandTimeoutMs)(),minSizeBytes:256,dirty:!0}),r}catch(n){return S().throw("withImgCache_() failed",{error:n,src:e.nativePath,desc:t,ext:i})}}},48368:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.HashDim=t.toImageHash=t.isImageHash=t._imageHash_=t.imageHash_=t.imageHash=t.maxPerBits=void 0;const r=n(i(9288)),s=i(19851),a=i(40958),o=i(22573),l=i(42659),u=i(33374),c=i(56038),d=i(85810),h=i(76490),f=i(40401),m=i(86758),p=i(85434),g=i(96706),y=i(38835),v=i(88561),w=i(95696),S=i(17217),b=i(50213),P=i(23624),M=i(28874),_=i(12089),E=i(16170),x=i(1078),T=i(33106),D=i(86580),k=i(78011),C=i(50961);t.maxPerBits=function(e){return Math.floor(52/e)};const F=(0,s.lazy)((()=>(0,b.mkLogger)("img.ImageHash")));t.imageHash=async function(e){try{return await(0,t.imageHash_)((0,S.toNativePath_)(e))}catch(t){return void F().warn("imageHash() failed for "+e,t)}};const O=(0,s.lazy)((()=>new v.FileCache({name:"img.imageHash",timeoutMs:l.minuteMs})));async function I(e){const t=w.PosixFile.for(e),i=await(0,x.extractSizeInfoFromFile)(t);if(null==i)throw new Error("Failed to read dimensions for "+e+y.NonFatalErrorFlag+y.DoNotSendErrorFlag);const n=(0,D.fitToResolution)(i.dimensions,Math.round(M.Settings.dominantColorPixels.valueOrDefault)),s=await(0,C.sharpReadable_)({src:t,minDim:n});return(0,c.time)("img.imageHash",(()=>async function({file:e,readable:t,sizeInfo:i}){const n=(0,b.mkLogger)("ImageHash("+e+")");if(null==t)return n.throw("Cannot build readable stream");const s=(0,D.fitToResolution)(i.dimensions,M.Settings.dominantColorPixels.valueOrDefault);if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-orig.jpg";await(0,C.toSharp)(t).jpeg().toFile(i),console.log({out:i,readable:t})}let a=(0,C.toSharp)(t).removeAlpha();(0,E.isVideoMimeType)(t.mimetype)||(a=a.rotate(i.rotation)),(0,u.dmegapixels)(i.dimensions)<.1&&(a=a.trim({background:"#000",threshold:0})),a=a.resize({fit:r.default.fit.outside,...s,withoutEnlargement:!0});const{data:o,info:l}=await a.raw().toBuffer({resolveWithObject:!0});if((0,g.isEnvTrue)("DEBUG_IMAGE_HASH")){const i="/tmp/image-hash-"+e.base+"-"+l.width+"w.jpg";await(0,r.default)(o,{raw:{...l,channels:3}}).jpeg().toFile(i),console.log({out:i,rgbInfo:l,readable:t})}const c=(0,d.rgb2labTriplets)(o),h=(0,f.extractDominantColors)(c),p=(0,m.labsAreGreyscale)(c),y=()=>(0,r.default)(o,{raw:{...l,channels:3}}),v=await(p?k.meanDiffHash:k.meanDiffHashCIELAB)(y()),w=await(p?T.dctHash:T.dctHashCIELAB)(y());return{meanHash:(0,P.b64encodeBits)(v.meanHash),diffHash:(0,P.b64encodeBits)(v.diffHash),dctHash:(0,P.b64encodeBits)(w),dominantColors:h.dominantColors,dominantColorsDescription:h.description,dominantColorScore:h.dominantColorScore,isGreyscale:p,mimetype:(0,E.normalizeMimetype)(t.mimetype),...i.dimensions,rotation:i.rotation??0}}({file:t,readable:s,sizeInfo:i})))}function L(e){return null!=e&&(0,o.notBlank)(e.meanHash)&&(0,o.notBlank)(e.mimetype)&&(0,a.isNotEmpty)(e.dominantColors)}t.imageHash_=(0,_.shim1)({name:"img.imageHash",cache:O,impl:I}),t._imageHash_=I,t.isImageHash=L,t.toImageHash=function(e){if(null!=e){if(L(e))return e;if((0,p.isModeData)(e)){const t={...(0,p.omitModeData)(e),dominantColors:h.DominantColor.fromModeData(e)};if(L(t))return t}}},t.HashDim=8},42725:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const a=i(57975),o=i(19851),l=i(33374),u=i(12168),c=i(48884),d=i(28874),h=i(32876),f=i(5733);class m{static sq(){return s(this,n,"f",r).filter((e=>e.reducer===h.Square))}static largestSq(){return(0,c.greatestBy)(this.sq(),(e=>e.megapixels()))}static fit(){const e=d.Settings.previewResolutions.valueOrDefault;return s(this,n,"f",r).filter((t=>t.reducer===h.Fit&&e.includes(t.name)))}static largestFit(){return(0,c.greatestBy)(this.fit(),(e=>e.megapixels()))}static all(){return[...s(this,n,"f",r)]}constructor(e,t,i,a,l=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=a,this.rotational=l,this.megapixels=(0,o.lazy)((()=>(0,u.megapixels)(this.maxWidth*this.maxHeight))),this.max={width:t,height:i},s(n,n,"f",r).push(this)}[a.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(e){return this.reducer.reduce(this.rotational&&(0,l.isPortrait)(e)?(0,l.dimSwap)(this.max):this.max,e)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,l.dmegapixels)(i)<2||d.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,f.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=m,n=m,r={value:[]},m.UHD8k=new n("uhd8k",7680,4320,h.Fit,!1),m.UHD5k=new n("uhd5k",5120,2880,h.Fit,!1),m.UHD=new n("uhd4k",4096,2160,h.Fit),m.QHD=new n("qhd",3120,1440,h.Fit),m.FHD=new n("fhd",1920,1080,h.Fit),m.HD=new n("hd",1280,720,h.Fit),m.WVGA=new n("wvga",720,480,h.Fit),m.QVGA=new n("qvga",320,240,h.Fit),m.QQVGA=new n("qqvga",160,120,h.Fit),m.S480=new n("s480",480,480,h.Square),m.S240=new n("s240",240,240,h.Square),m.S120=new n("s120",120,120,h.Square),m.S60=new n("s60",60,60,h.Square)},4192:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=void 0;const n=i(19851),r=i(40958),s=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(47783),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.includePreviewTags")));t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,r.isEmpty)(t)||(c().info("Re-adding metadata to previews..."),await(0,o.time)("img.includePreviewTags",(async()=>{const i=(0,s.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),n=i?.capturedAt;null!=n&&(delete i.capturedAt,(0,s.assignFields)(i,n.asExifTag()));const r=i?.exposureSettings;null!=r&&(delete i.exposureSettings,i.FocalLength=r.focalLength,i.FNumber=r.aperture,i.ExposureTime=r.shutterSpeed,i.ISO=r.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,s.isEmptyObj)(i)?c().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(c().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map((e=>(0,u.overwriteTags_)(e,i)))))})))}},78011:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.meanDiffHashCIELAB=t.meanDiffHash=t.dhash=t.mhash=void 0;const r=n(i(9288)),s=i(96249),a=i(59455),o=i(85810),l=i(70417),u=i(48368);function c(e){const t=(0,l.avg)(e);return null==t?[]:(0,a.toA)(e).map((e=>e>=t?1:0))}function d(e){const t=(0,a.toA)(e),i=Math.round(Math.sqrt(t.length));return t.map(((t,n)=>t>=(0===n?e[i]:n%i==0?e[n-i]:e[n-1])?1:0))}t.mhash=c,t.dhash=d,t.meanDiffHash=async function(e,t=u.HashDim){const i=await e.greyscale().resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer();return{meanHash:c(i),diffHash:d(i)}},t.meanDiffHashCIELAB=async function(e,t=u.HashDim){const i=await e.resize({fit:r.default.fit.fill,width:t,height:t}).raw().toBuffer(),n=(0,o.rgb2labArray)(i);return{meanHash:(0,s.flatten)(n.map(c)),diffHash:(0,s.flatten)(n.map(d))}}},52121:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._prepFileForBrowser=t.prepFileForBrowser=void 0;const n=i(19851),r=i(78923),s=i(95696),a=i(50213),o=i(28874),l=i(12089),u=i(16170),c=i(13940),d=i(4192),h=i(5733),f=i(50961),m=(0,n.lazy)((()=>(0,a.mkLogger)("img.PrepareFileForBrowser")));async function p(e){try{const t=s.PosixFile.for(e.nativePath);if(await t.notExists())return;const i=e.mimetype??(await(0,r.readFileType_)(t.nativePath))?.mime;return(0,u.isMimeTypeSupportedByBrowser)(i,e.userAgent)?t.nativePath:(m().info("prepFileForBrowser(): non-browser-supported mimetype",{file:t,info:e}),(await(0,c.withImageCache_)(t,"web",".jpg",(async e=>{const i=await(0,f.sharpReadable_)({src:t});if(null==i)throw new Error("prepFileForBrowser(): can't read "+t.nativePath);await(0,f.toSharp)(i).jpeg((0,h.sharpRenderOptions)()).toFile(e.nativePath),o.Settings.includePreviewTags.valueOrDefault&&await(0,d.includePreviewTags_)(t,[e])})))?.nativePath)}catch(e){return void m().warn("prepFileForBrowser() failed",{error:e})}}t.prepFileForBrowser=(0,l.shim1)({name:"img.prepFileForBrowser",impl:p}),t._prepFileForBrowser=p},48604:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const n=i(19851),r=i(55835),s=i(50213),a=i(12089),o=i(87290),l=i(95242),u=i(16524);class c{constructor(e){this.root=e}apb(e,t,i){return new l.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new u.AssetPreviews(this.root,e)}}t.Previews=c,c.instance=(0,n.lazy)((()=>((0,s.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,r.map)((0,o.libraryPreviewsDirPosixFile)(),(e=>new c(e)))))),t.buildAssetPreviews_=(0,a.shim1)({name:"img.buildAssetPreviews",impl:e=>c.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtAspectRatio=t.roundAspectRatio=t.similarRatiosWithRotation=t.similarRatios=t.roundToNearestRatio=t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0;const n=i(40958),r=i(33374),s=i(31586),a=i(34666),o=i(48884),l=i(97352);function u(e,i=2*t.RatioEpsilon){return(0,l.mapGt0f)((0,s.isNumber)(e)?e:((0,s.toGt0)(e.width)??0)/((0,s.toGt0)(e.height)??0),(e=>(0,o.leastBy)(t.StandardAspectRatios,(t=>{const n=Math.abs(e-t);return n>i?void 0:n}))??e))}function c(e,i,n=t.RatioEpsilon){return(0,a.lt)((0,s.absdiff)(u(e),u(i)),n)}function d(e,i){return(0,o.leastByCtx)(t.Ratios,(t=>{const n=Math.abs(t.i-e);return n[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}])),(e=>e.s)),t.StandardAspectRatios=t.Ratios.map((e=>e.i)),t.RatioEpsilon=.045,t.roundToNearestRatio=u,t.similarRatios=c,t.similarRatiosWithRotation=function(e,t,i=.05){return c((0,r.maybeDimSwap)(e.dimensions,e.rotation),(0,r.maybeDimSwap)(t.dimensions,t.rotation),i)},t.roundAspectRatio=function(e,t=.05){return d(e,t)?.result.i??e},t.fmtAspectRatio=function(e,t=.05){return d(e,t)?.result.s??String((0,s.sigFigs)(e,3))}},34943:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawInfoOutput_=t.rawInfo_=t.rawInfo=void 0;const n=i(19851),r=i(31586),s=i(80049),a=i(50213),o=i(45255),l=i(84777),u=i(34102),c=i(41080),d=i(89966),h=(0,n.lazy)((()=>(0,a.mkLogger)("img.RawInfo"))),f=(0,n.lazy)((()=>new s.FifoCacheAsync({maxSize:512,name:"img.RawInfoCache",timeoutMs:o.ShortCommandTimeoutMs})));async function m(e){return f().getOrSetAsync(e.nativePath,(async()=>{const t=await(0,d.rawIdentifyNativePath_)();return p(await(0,l.stdout_)(t,["-s",e.nativePath],{timeoutMs:(0,c.statTimeoutMs)()}))}))}function p(e){const[t,i,n,s,a]=e.split("\t"),o=(0,r.toGt0)(s),l=(0,r.toGt0)(a);return null==o||null==l?h().throw("parseRawInfoOutput_ failed (missing dimensions)",{cause:e}):h().tap({msg:"parseRawInfoOutput()",result:{Filename:t,Make:i,Model:n,ImageSize:{width:o,height:l}},meta:{input:e}})}(0,u.ee)().on("clearCache",(()=>f.prior()?.clear())),(0,u.ee)().on("fileChanged",(e=>null==e?f.prior()?.clear():f.prior()?.delete(e))),t.rawInfo=async function(e){return m(e).catch((t=>{h().warn("rawInfo() failed",{error:t,src:e})}))},t.rawInfo_=m,t.parseRawInfoOutput_=p},32876:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.fitInsideToMaxPixels=t.fitInsideToAspectRatio=t.Square=t.SharpFits=void 0;const n=i(19851),r=i(33374),s=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,n.lazy)((()=>(0,c.mkLogger)("img.Reducers.Square")));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,n){const r=(0,d.lteBoth)(e,n)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:r,meta:{max:e,input:(0,l.pick)(n,"width","height","nativePath")}})}}(h||(t.Square=h={})),t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,r.pixels)(e)(0,c.mkLogger)("img.Reducers.Fit")));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,s.fitInside)(i,e);t().trace(`reduce(): input ${(0,r.fmtDim)(i)} is too small for ${(0,r.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.sharpRenderOptions=t.sharpFromRawBuffer=t.sharpClone=t.isSharp=void 0;const r=n(i(9288)),s=i(19851),a=i(41400),o=i(50213),l=i(28874),u=i(15674),c=(0,s.lazy)((()=>(0,o.mkLogger)("img.Sharp")));function d(e,t){return(0,r.default)(e,{raw:t})}t.isSharp=function(e){return"object"==typeof e&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer},t.sharpClone=async function(e){try{return e.clone()}catch(e){c().info("sharp.clone() failed",e)}try{const{data:t,info:i}=await e.raw().toBuffer({resolveWithObject:!0});return d(t,i)}catch(e){return c().throw("clone via sharp.raw().toBuffer() failed",{error:e})}},t.sharpFromRawBuffer=d,t.sharpRenderOptions=function(){return{quality:l.Settings.previewQuality.valueOrDefault,progressive:l.Settings.previewProgressive.valueOrDefault,mozjpeg:l.Settings.previewMinimized.valueOrDefault}},t.setupSharp=(0,s.lazy)((()=>{r.default.simd(l.Settings.enableSIMD.valueOrDefault),r.default.cache(!!l.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),r.default.concurrency((0,u.sharpThreadsPerProcess)())})),(0,a.later)((()=>{l.Settings.enableSIMD.watchLater((()=>t.setupSharp.refresh())),l.Settings.enableVipsCache.watchLater((()=>t.setupSharp.refresh()))}))},48584:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const n=i(50989);t.SharpFailOns=(0,n.strEnum)("none","truncated","error","warning")},50961:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractImageForThumbs_=t.sharpReadable_=t.toSharp=t.imgFromExif_=t._imgFromExif_=void 0;const r=i(77988),s=n(i(9288)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(51926),p=i(41583),g=i(50213),y=i(97352),v=i(56519),w=i(56038),S=i(57159),b=i(95696),P=i(17217),M=i(28874),_=i(47783),E=i(16170),x=i(95141),T=i(54979),D=i(1078),k=i(63870),C=i(86580),F=i(277),O=i(16047),I=i(13940),L=i(5733),A=i(66106),R=i(19350),N=(0,a.lazy)((()=>(0,g.mkLogger)("img.SharpReadable")));async function B(e,t,i){return i?await(0,_.exiftool)().extractBinaryTagToBuffer(t,e.nativePath):(await j(e,t))?.nativePath}async function z(e,t,i,n,a){const o=t?.[i];if(!(o instanceof r.BinaryField))return;const l=o.bytes(0,_.extractBinaryTag)(t,e.nativePath,i.nativePath),timeoutMs:(0,k.commandTimeoutMs)()})}catch(i){return void N().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}}t._imgFromExif_=B,t.imgFromExif_=z,t.toSharp=function(e){const t=e;if((0,L.isSharp)(t.sharp))return t.sharp;if((0,P.isSimpleFile)(t.file))return(0,s.default)(t.file.nativePath,{failOn:M.Settings.imageFailOn.valueOrDefault});throw new Error("toSharp(): not a Sharp object: "+(0,d.stringify)(e))},t.sharpReadable_=function(e){return(0,w.time)(`img.sharpReadable${e.src.ext.toUpperCase()}`,(()=>async function({src:e,minDim:t,skipEmbedded:i}){const n=N().addParameterContext(e.nativePath);(0,L.setupSharp)();const s=await(0,T.readMimeType)(e);if((0,u.blank)(s))return n.throw(e+" is not supported (missing MIMEType)",{doNotSend:!0});const a=await(0,D.extractSizeInfoFromFile)(e);if(null==a)return void n.warn("Failed to extract size info from "+e);const d=[];function f(e,t){t.desc=e,d.push(t)}const m=a.rotation,g=(0,E.isVideoMimeType)(s),b=(0,E.isLibrawMimeType)(s),P=a.dimensions,k=t??(0,y.map2Gt0)(P.width,P.height,((e,t)=>({width:Math.round(.9*e),height:Math.round(.9*t)})));if(null==k?.width||null==k?.height)return n.throw(e+" is not supported (missing dimensions)",{dim:k,doNotSend:!0,mimetype:s,isRaw:b,isVideo:g});const I=(0,C.aspectRatio)(a.fileDimensions),B=(0,h.lt)(I,1),j=(0,E.isSharpMimeType)(s)&&null==t,V=(0,x.orientationRequiresMirroring)(a.orientation);if(!0===i||g||B||j||V)n.debug("not pulling previews from tags",{isVideo:g,isFilePortrait:B,isSharpMimeAndNoMinDim:j,isMirrorOrientation:V});else{const i=!1,s=await(0,_.readRawTags)(e,i);if(null==s)n.warn("Cannot pull previews from tags: readRawTags() failed");else{const i=[...M.Settings.embeddedPreviews.values];null!=t&&(0,c.dmegapixels)(t)<1&&i.unshift(...M.Settings.embeddedThumbnails.values);const a=k.width*k.height*.2,u=k.width*k.height*.05,d=(0,l.sortBy)(i.filter((e=>s[e]instanceof r.BinaryField)),(e=>{const t=s[e]?.bytes;return(0,h.gt)(t,u)?Math.abs(t-a):void 0}));if(!(0,o.isEmpty)(d)){n.debug("checking previews from tags",{sizeSortedTagNames:d});for(const t of d)f("imgFromExif."+t,(()=>z(e,s,t,k,I)))}}}(0,E.isSharpMimeType)(s)&&f("sharp",(async()=>({file:e}))),(0,O.isHeifMimeType)(s)&&await(0,F.isHeifSupported)()&&f("heif",(()=>(0,v.thenMap)((0,F.heif2img)(e),(e=>({file:e}))))),b&&f("raw2tiff",(()=>(0,v.thenMap)((0,R.raw2tiff_)(e),(e=>({file:e}))))),g&&f("extractVideoFrame",(async()=>{if(await(0,A.isVideoSupported)())try{return await(0,v.thenMap)((0,A.extractVideoFrame_)(e),(e=>({file:e})))}catch(t){throw new S.WrappedError("Failed to extract video frame for "+e,t)}else n.warn("video file, but video support is missing",{src:e.nativePath,mimetype:s,minDim:t})}));const W=[];for(const i of d)try{const r=await(0,w.time)("img.read."+i.desc,i);if(null!=r)return n.debug(i.desc+" strategy succeeded",{src:e,minDim:t,rot:m,img:r.file?.nativePath}),{desc:i.desc,rot:m,mimetype:s,...r};n.debug(i.desc+" returned null",{src:e,minDim:t,rot:m})}catch(e){n.warn(i.desc+" failed",e),W.push((0,p.toErr)(e))}throw new S.WrappedError("Failed to render "+e,{causes:W,path:String(e),fatal:!1,doNotSend:!0,retriable:!1})}(e)))},t.extractImageForThumbs_=j},181:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=t.clearInvalidFileCache=t.throwIfInvalidFile_=t.isValidFile=void 0;const r=n(i(9288)),s=i(19851),a=i(22573),o=i(42659),l=i(98553),u=i(50213),c=i(12089),d=i(81168),h=i(57159),f=i(88561),m=i(95696),p=i(17217),g=i(28874),y=i(16170),v=i(54979),w=i(63870),S=i(5733),b=i(50961),P=i(66106),M=i(51210),_=(0,s.lazy)((()=>(0,u.mkLogger)("img.ValidFile")));t.isValidFile=async function(e){return(0,a.blank)(await(0,t.whyInvalidFile)((0,p.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!g.Settings.validateJpegImages.valueOrDefault&&!g.Settings.validateRawImages.valueOrDefault&&!g.Settings.validateVideos.valueOrDefault)return void _().debug("file validation is disabled for "+e,{validateJpegImages:g.Settings.validateJpegImages.valueOrDefault,validateRawImages:g.Settings.validateRawImages.valueOrDefault,validateVideos:g.Settings.validateVideos.valueOrDefault});const i=(0,p.toNativePath_)(e),n=_().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,a.notBlank)(n)&&_().throw(n,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})};const E=(0,s.lazy)((()=>new f.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(o.minuteMs,g.Settings.validateVideos.valueOrDefault?5*o.minuteMs:(0,w.commandTimeoutMs)())})));t.clearInvalidFileCache=function(){return E().clear()},t.whyInvalidFile=(0,c.shim1)({name:"img.whyInvalidFile",cache:E,toKey:p.toNativePath_,impl:async e=>{const t=m.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmpty())return t+" is empty";try{const e=await(0,v.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,y.isVideoMimeType)(e))g.Settings.validateVideos.valueOrDefault&&(_().debug("validating "+t),await(0,P.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,l.stringify)(e));if("image/jpeg"===e)g.Settings.validateJpegImages.valueOrDefault&&await(0,M.validJpeg_)(t);else if(g.Settings.validateRawImages.valueOrDefault)if((0,d.includesIgnoreCase)(g.Settings.validateMimetypeSkiplist.values,e))_().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await(0,b.sharpReadable_)({src:t,skipEmbedded:!0}),i=await async function(e,t=g.Settings.imageFailOn.valueOrDefault){const i=e;if((0,p.isSimpleFile)(i.file))return(0,r.default)(i.file.nativePath,{failOn:t});if((0,S.isSharp)(i.sharp)){const{data:e,info:t}=await i.sharp.raw().toBuffer({resolveWithObject:!0});return(0,r.default)(e,{...t,failOnError:!0})}throw new Error("Cannot read input "+e?.desc)}(e);await i.tiff().toBuffer()}}return""}catch(t){return new h.WrappedError("Failed to validate",{cause:t,path:e,doNotSend:!0}).toS()}}})},19769:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIgnorableValidationError=void 0;const n=i(19851),r=i(40958),s=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(28874),c=(0,n.lazy)((()=>(0,a.mkLogger)("img.ValidationError")));t.isIgnorableValidationError=function(e){const t=(0,l.errorToS)(e);return c().tap({msg:"isIgnorableValidationError",level:"info",result:h().test(t)||!d().test(t),meta:{err:e,allow:h().test(t),block:d().test(t),validationErrorAllowlist:h().source,validationErrorBlocklist:d().source}})};const d=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorBlocklist.values),"i"))),h=(0,n.lazy)((()=>(0,o.orRegExpPatterns)((0,r.compactBlanks)(u.Settings.validationErrorAllowlist.values),"i")));(0,s.later)((()=>{u.Settings.validationErrorBlocklist.watchLater((()=>d.unset())),u.Settings.validationErrorAllowlist.watchLater((()=>h.unset()))}))},66106:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validVideo_=t.guessExpectedSize=t.transcode_=t.needsTranscoding=t.isVideoTranscodingSupported=t.__extractVideoFrame_=t._extractVideoFrame_=t.extractVideoFrame_=t.bitrateKps=t.isVideoSupported=t.getVideoToolDetails_=void 0;const n=i(19851),r=i(40958),s=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(31586),c=i(34666),d=i(50213),h=i(7282),f=i(97352),m=i(12089),p=i(81168),g=i(75387),y=i(22911),v=i(56038),w=i(31562),S=i(98314),b=i(34102),P=i(88561),M=i(95696),_=i(17217),E=i(74128),x=i(31843),T=i(70417),D=i(33847),k=i(28874),C=i(94678),F=i(43207),O=i(47783),I=i(16170),L=i(95141),A=i(1078),R=i(63870),N=i(89782),B=i(13940),z=i(34592),j=(0,n.lazy)((()=>(0,d.mkLogger)("img.Video")));function V(e,t){return(0,d.mkLogger)("img/Video."+e+"("+t+")")}async function W(e){return(0,h.isProd)()&&(e=void 0),(0,s.isTrue)(e?.ignoreffmpeg)?void 0:await(0,z.ffmpegVersion_)()}t.getVideoToolDetails_=W,t.isVideoSupported=(0,n.lazy)((async()=>{try{return!0===(await W())?.isSupportedVersion}catch(e){return j().warn("isVideoSupported",{error:e}),!1}})),(0,o.later)((()=>(0,b.ee)().on("clearCache",(()=>t.isVideoSupported.unset())))),t.bitrateKps=e=>(0,u.sigFigs)((0,x.lerp2d)(e,{x:76800,y:k.Settings.transcodeBitrateQVGA.valueOrDefault},{x:8294400,y:k.Settings.transcodeBitrateUHD.valueOrDefault}),2);const H=(0,n.lazy)((()=>new P.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs})));async function U(e){return await(0,t.isVideoSupported)()?M.PosixFile.for(await(0,t._extractVideoFrame_)((0,_.toNativePath_)(e))):void 0}async function q(e,t){const i=V("extractVideoFrame",e),n=M.PosixFile.for(e);if(!(0,s.isTrue)(t?.useFfmpeg)&&!await(0,z.isFFmpegSupported)())return i.throw("no video implementation");const r=await(0,B.cachedImageFile_)(n,"frame",".jpg");i.debug("extractVideoFrame("+r+")");const o=await n.mtimeMs();if(null==o)return i.throw("null mtime");const l=await(0,O.readRawTags)(n,!1);if(null==l)return i.throw("no tags");const u=(0,L.extractRotation)(l);i.debug("video orientation:"+u);const c=(0,A.extractSizeInfoFromTags)(l,u)?.dimensions,d=await r.stat(),h=null==d?void 0:await(0,N.dimensions)(r);if(null!=d&&d.mtimeMs>o&&null!=h&&(null==c||h.height===c.height&&h.width===c.width))return i.debug("prior dest, "+r+" seems reasonable",{srcDim:c,destDim:h}),r.nativePath;const f=(0,F.extractDurationSec)(l),m=Math.min(f??0,k.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:m,duration:f}),await r.applyIfEmpty_({fn_:async e=>{const t={src:n,dest:e,startAtSec:m,...c};await(0,z.ffmpegFrame_)(t),!1===await(0,w.untilTrue)((async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()})),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,O.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),r.nativePath}async function G(){return k.Settings.transcodeVideos.valueOrDefault&&await(0,z.isFFmpegSupported)()}async function $(e){const t=V("needsTranscoding",e);if(!await G())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,O.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const n=i.MIMEType;if(!(0,I.isVideoMimeType)(n))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:n}});const s=(0,F.extractDurationSec)(i);if(!(0,c.gt)(s,k.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const a=(0,r.compactBlanks)([i.AudioFormat]),o=a.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeAudioCodecs.values,e))),l=(0,r.compactBlanks)([i.VideoCodec,i.CompressorID,i.CompressorName]),u=l.some((e=>(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeVideoCodecs.values,e))),d=(0,p.includesIgnoreCase)(k.Settings.doNotTranscodeMimeTypes.values,n);return t.tap({level:"info",msg:"result",result:!(o&&u&&d),meta:{mimetype:n,isSafeMimeType:d,audioCodecs:a,isSafeAudioCodec:o,videoCodecs:l,isSafeVideoCodec:u}})}t.extractVideoFrame_=U,t._extractVideoFrame_=(0,m.shim1)({name:"img.extractVideoFrame",cache:H,impl:e=>q(e)}),t.__extractVideoFrame_=q,t.isVideoTranscodingSupported=G,t.needsTranscoding=$;const J=new g.TTLMap(a.hourMs);function K(e,t,i){return Math.min(e,(i??10)*(t??1e3))}t.transcode_=async function(e,i,n){if(!await G())return;const s=Date.now(),a=V("transcode",e);{!function(){for(const[e,t]of J.entries())t.isSettled&&J.delete(e)}();const t=J.get(e.nativePath)??J.get(i.nativePath);if(null!=t)return a.info("already transcoding",{dest:i,elapsedMs:t.elapsedMs,priorSrc:t.name}),t}if(!1===await $(e))return void a.info("no transcoding needed");const o=await e.size();if(!(0,u.gt0)(o))return a.throw("source is empty or cannot read");const d=await(0,O.readTags)(e),h=(0,A.extractSizeInfoFromTags)(d),m=(0,F.extractDurationSec)(d);if(null==d||null==h||null==m)return a.throw("failed: missing video metadata",{sizeInfo:h,durationSec:m});{const e=J.get(i.nativePath);if(null!=e)return a.info("already transcoding",{dest:i,elapsedMs:e.elapsedMs,priorSrc:e.name}),e}const p=new y.Deferred("transcode "+e);if(J.set(e.nativePath,p),J.set(i.nativePath,p),!0===n?.force)await i.unlink();else if(await async function(e,t){const i=await(0,O.readRawTags)(t),n=await(0,O.readRawTags)(e),r=(0,F.extractDurationSec)(n),s=(0,F.extractDurationSec)(i);return j().tap({msg:"isTranscodeOf()",result:(0,u.closeTo)(r,s,1.5),meta:{srcDurationSec:r,destDurationSec:s,src:e.nativePath,dest:t.nativePath}})}(e,i))return a.info("no-op, dest duration looks reasonable",{dest:i}),i;const g=function(e,i){const n=V("extractMaxBitrate",e),r=k.Settings.minVideoDimension.valueOrDefault,s=i.ImageWidth;if(null!=s&&!(0,u.gte)(s,r))return n.throw("invalid width: "+s,{ignorable:!0});const a=i.ImageHeight;if(null!=a&&!(0,u.gte)(a,r))return n.throw("invalid height: "+a,{ignorable:!0});const o=(0,C.extractBitrateKbps)(i)??k.Settings.transcodeBitrateUHD.valueOrDefault,l=(0,f.mapGt0)(s,(e=>(0,f.mapGt0)(a,(i=>(0,u.clamp)(0,o,(0,t.bitrateKps)(e*i)))))),c={width:s,height:a,videoBitrateKbps:l};return n.debug("dim()",{src:e,result:c}),c}(e,d);return await p.observe((0,v.time)("video.transcode:"+e,(async()=>{const t=K(o,g.videoBitrateKbps,m);return await i.applyWip_({fn_:o=>async function(o){a.info("starting...",{destWip:o});const h=new D.PullProgressObserver({path:e.nativePath,op:"Transcoding video"},t,(async()=>await i.clear().size()??0)),f={src:e,dest:o,halt:n.halt,...g},m=k.Settings.transcodeMaxDim.valueOrDefault,p=(0,T.max)([d.dimensions.height,d.dimensions.width]);if((0,u.gt0)(m)&&(0,c.gt)(p,m)){const e=(0,l.fitInside)(d.dimensions,{width:m,height:m});null==e?a.warn("Cannot downsample transcoded video: fitInside() returned null",{input:d.dimensions,maxPixels:m}):(f.width=(0,u.roundEven)(e.width),f.height=(0,u.roundEven)(e.height),a.info("Downsampling transcoded video",{original:d.dimensions,output:e}))}try{const t=await h.observe((0,z.ffmpegTranscode_)(f));0!==t.code&&a.throw((0,r.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,E.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"note",details:"Transcode complete",elapsedMs:Date.now()-s})}catch(t){throw(0,E.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",state:"failed",details:"Transcode failed: "+(0,S.errorToS)(t),elapsedMs:Date.now()-s}),a.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),i}))),a.info("transcode complete",{src:e,dest:i,elapsedMs:p.elapsedMs}),i},t.guessExpectedSize=K,t.validVideo_=async function(e){return null==await U(e)&&V("validVideo",e).throw("Could not extract a video frame"),(0,z.ffmpegValidVideo_)(e)}},34592:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegValidVideo_=t.ffmpegTranscode_=t.avcArgs=t.ffmpegFrame_=t.isFFmpegSupported=t.ffmpegVersion_=t.ffmpegVersionDescription=t.ffmpegNativePath=void 0;const n=i(40958),r=i(22573),s=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(56519),f=i(31562),m=i(84777),p=i(98314),g=i(34102),y=i(8103),v=i(84258),w=i(28874),S=i(76280),b=i(63870),P=i(19769),M=(0,u.lazy)((()=>(0,c.mkLogger)("img.ffmpeg")));function _(){return(0,y.pathTo)({tool:"ffmpeg",alternativePath:w.Settings.ffmpegPath.valueOrDefault})}t.ffmpegNativePath=_;const E=/ffmpeg version n?(?\S+)/i,x=(0,u.lazy)((async()=>{const e=await _();if(null==e)return void M().info("failed to find ffmpeg in $PATH",{ffmpegPath:w.Settings.ffmpegPath.valueOrDefault});const t=await(0,m.stdoutResult_)(e,["-version"],{timeoutMs:(0,b.commandTimeoutMs)(),ignoreStderr:!0}),i=E.exec(t.result)?.[1];return M().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{path:e,version:i??"(unknown)",isSupportedVersion:(0,S.semverSatisfies)(i,">=3.2")}}));function T(){x.unset(),t.ffmpegVersionDescription.unset()}function D(e){const t=e?.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault;return(0,r.blank)(t)||(0,s.isDisabled)(t)?[]:["-hwaccel",t]}function k(e){const t=[...w.Settings.ffmpegAvcTranscodeArgs.values];if(!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(w.Settings.transcodeMaxDim.valueOrDefault))return t;const i=(0,l.roundEven)(e.width),n=(0,l.roundEven)(e.height);return t.unshift("-s",i+"x"+n),t}function C(e){if(!(0,l.gt0)(e))return[];const t=(0,l.sigFigs)(e,2);return["-b:v",t+"k","-maxrate",t+"k","-bufsize",(0,l.sigFigs)(t/2,2)+"k"]}function F(e){const t=w.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",Math.round(t)]}t.ffmpegVersionDescription=(0,u.lazy)((()=>(0,h.thenMapOr)(x(),(e=>"version "+e),(()=>"(not found)")))),(0,o.later)((()=>{(0,g.ee)().on("clearCache",T),(0,g.ee)().on("clearToolCache",T)})),t.ffmpegVersion_=async function(){return await x.prior()??x.refresh()},t.isFFmpegSupported=async function(){return null!=await x()},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,n.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,(e=>["-ss",e.toFixed(1)]))??[],"-vframes","1","-y",e.dest.nativePath]),{timeoutMs:a.minuteMs,isIgnorableError:P.isIgnorableValidationError}),!await(0,f.untilTrue)((()=>e.dest.clear().isNonEmptyFile()),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.avcArgs=k,t.ffmpegTranscode_=async function e(t){try{return await t.dest.parent().mkdirp_(),await(0,m.stdoutResult_)(await _(),(0,n.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...k(t),...F(t),...D(t),"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),...C(t.videoBitrateKbps),t.dest.nativePath]),{halt:t.halt,timeoutMs:t.timeoutMs??0,isIgnorableError:P.isIgnorableValidationError})}catch(i){M().warn("ffmpegTranscode_() failed",{args:t,error:i}),await(0,v.unlink)(t.dest,"debug");const n=(0,p.errorToS)(i,{maxLen:1024});if(!(0,s.isDisabled)(t.ffmpegHwaccel??w.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(n))return M().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:i}),e({...t,ffmpegHwaccel:"disabled"});throw i}},t.ffmpegValidVideo_=async function(e){return M().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,m.stdoutResult_)(await _(),["-v","error","-nostats","-i",e.nativePath,"-threads",String(w.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timeoutMs:0,isIgnorableError:P.isIgnorableValidationError,ignoreExitCode:!0,quiet:!1})})}},51210:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotate_=t.rotateInPlace_=t.validJpeg_=t.jpegtranVersion_=void 0;const n=i(19851),r=i(42659),s=i(21605),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(63870),f=i(19769),m=d.isWin?"NUL":"/dev/null",p=(0,n.lazy)((()=>(0,a.mkLogger)("img.jpegtran")));async function g(e,t,i){const n=await(0,c.jpegtranNativePath_)();if(!(0,s.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(n,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timeoutMs:r.minuteMs}),t.clear()}t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{quiet:!0,timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",m,t.nativePath],{timeoutMs:(0,h.commandTimeoutMs)(),isIgnorableError:f.isIgnorableValidationError,ignoreExitCode:!0})}catch(e){throw p().warn("validJpeg caught invalid file",{src:t,cause:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){p().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>g(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:r.minuteMs})},t.rotate_=g},19350:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dcraw_emu_=t.raw2tiff_=t.librawSupported=void 0;const n=i(19851),r=i(40958),s=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),v=i(89782),w=i(13940),S=i(42725),b=i(19769),P=(0,n.lazy)((()=>(0,u.mkLogger)("img.libraw")));t.librawSupported=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e.nativePath))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,w.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>T(e,t)})};const M=["-T"],_=["-Z","-"],E=["-o","1"],x=["-t","0","-j"];async function T(e,t){const i=await(0,v.dimensions)(e);if(null==i)return P().throw("Cannot decode RAW "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const n=S.ImageSize.largestFit().outputSize(i),u=[];null!=n&&4*(0,s.dmegapixels)(n)<(0,s.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[...M,..._,...E,...u,...x,...p.Settings.dcrawEmuArgs.values,e.nativePath],w={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:w});const T=(0,c.execFile)(g,y,void 0,w),D=[];function k(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,b.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{src:e,msg:i});else{P().warn("dcraw_emu(): error",{src:e,msg:i});const n=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});D.push(n)}}if(T.on("error",k),T.stderr.on("data",k),await t.writeStream_(T.stdout),(0,r.isNotEmpty)(D))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:D,path:e.nativePath});(0,c.endProcess)(T)}t.dcraw_emu_=T},36192:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sips2jpeg_=t.sipsPath=void 0;const n=i(19851),r=i(84777),s=i(8103),a=i(43334),o=i(28874),l=i(63870),u=i(13940);t.sipsPath=(0,n.lazy)((async()=>a.isMac?(0,s.pathTo)({tool:"sips"}):void 0)),t.sips2jpeg_=async function(e){return(0,u.withImageCache_)(e,"heif",".jpeg",(t=>(0,r.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{cwd:t.dir,timeoutMs:(0,l.commandTimeoutMs)()})))}},49794:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=t.colorProcessName=void 0;const n=i(57975),r=i(19851),s=i(40958),a=i(22573),o=i(54993),l=i(37975),u=i(7282),c=i(23560),d=i(28874),h=i(66184),f=i(93475),m=(0,r.lazy)((()=>[{re:/billing|worker/,f:l.cyan},{re:/sync/,f:l.blue},{re:/web/,f:l.green},{re:/main/,f:l.yellow},{re:/info/,f:l.blueBright},{re:/test|log/,f:l.magenta}]));function p(e){if((0,a.blank)(e))return"";const t=m().find((t=>e.match(t.re)));return null!=t?(0,l.bgBlack)(t.f(e)):e}t.colorProcessName=p,t.ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.logLevels={trace:"trace",debug:(0,l.darkGrey)("debug"),info:(0,l.cyan)("info_"),warn:(0,l.yellowBright)("warn_"),error:(0,l.redBright)("error_"),fatal:(0,l.bgRedBright)((0,l.black)("fatal"))},this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:d.Settings.logContextLimit.valueOrDefault+3,processName:c.processName,...this._inspectOptions},(0,u.isTest)()&&(this.inspectOptions.breakLength=255),d.Settings.logContextLimit.watchLater((e=>{this.inspectOptions.maxArrayLength=e+1})),this.inspectOptions.processName.watch((e=>this.defaultProcessName=p(e)))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,n.inspect)(t,this.inspectOptions)}formatLogEntry(e){const t=(0,h.logFilter)().highlight(e.ctx)?l.yellow:l.blue;return(0,s.compactBlanks)([(0,l.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],t(e.ctx),e.msg,this.formatMeta(e.meta)]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,c.processName)(),ctx:t,msg:i,meta:n})}}},32105:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const n=i(19851),r=i(23560),s=i(66184),a=i(72210);class o{log(e,t,i,n){this.enabled(e,t)&&(0,a.pushLogEntries)({ts:Date.now(),l:e,from:(0,r.processName)(),ctx:t,msg:i,meta:n})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=o,o.instance=(0,n.lazy)((()=>new o))},14593:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const n=i(57975),r=i(22573),s=i(26905),a=i(55835),o=i(68708),l=i(13538),u=i(50213),c=i(97352),d=i(45255),h=i(76740),f=i(57159),m=i(57902),p=/logger|lazy/i;class g{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,r.toNotBlank)(e)??(0,s.shortStack)().find((e=>!p.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[n.inspect.custom](){return this.toLogJSON()}addContext(e){return new g(this.context+e,this.loggers)}addParameterContext(e){return new g(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const i=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,o.omit)(t,"error")});throw Error.captureStackTrace?.(i),this.log(!0===i.ignorable?"warn":"error",".throw() "+i.message,{stack:i.stack,...t}),i}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let i;try{i=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const n=e.result(),r=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:n,meta:{...e.meta,elapsedMs:r}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,o.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const i of this.loggers())if(i.enabled(e,t??this.context))return!0;return!1}log(e,t,i){for(const n of this.loggers())n.log(e,this.context,t,i)}elapsed(e,t,i){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...i})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=g},89179:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.currentFileLogger=void 0;const n=i(50213),r=i(43705);t.currentFileLogger=function(){return(0,n.rootLoggers)().find((e=>e instanceof r.LogWriter))}},28981:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const n=i(19851),r=i(51879);t.DefaultLogFormatter=(0,n.lazy)((()=>new r.PlaintextLogFormatter))},31256:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,n.lazy)((()=>({_service:(0,h.serviceName)(),_pid:process.pid})));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)((()=>h.serviceName.watchLater((()=>y.unset())))),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map((([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)])))})}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}}},51576:function(e,t,i){var n,r=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.logBroadcaster=void 0;const s=i(77030),a=i(19851),o=i(22573),l=i(42659),u=i(41400),c=i(98553),d=i(56409),h=i(31586),f=i(25764),m=i(38836),p=i(50213),g=i(409),y=i(28874),v=i(31256),w=i(28538),S=(0,a.lazy)((()=>(0,p.mkConsoleLogger)("log.LogBroadcaster"))),b=String.fromCharCode(0);t.logBroadcaster=(0,a.lazy)((()=>{const e=function(){const[e,t]=(y.Settings.logServer.valueOrDefault??"").split(":"),i=(0,h.toInt)(t);return(0,o.blank)(e)||!(0,h.gt0)(i)?void 0:{host:e,port:i}}();return null==e?void(y.Settings.logServer.hasValue()&&S().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,c.stringify)(y.Settings.logServer.valueOrDefault)})`)):new P(e.host,e.port)})),(0,u.later)((()=>y.Settings.logServer.watchLater((()=>t.logBroadcaster.unset()))));class P extends m.EndableWrapper{constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",(()=>this.socket?.end()),f.EndableRanks.logtail),this.host=e,this.port=t,this.logFormatter=new v.GelfLogFormatter,this.logFilter=new w.LogFilterImpl(y.Settings.logServerLevel),n.set(this,(0,g.rateLimited)({f:async()=>{try{const e=this.socket=(0,s.createConnection)({host:this.host,port:this.port});e.on("close",(()=>{this.socket=void 0})),e.on("error",(t=>{S().warn("Error from logging server",t);try{e.end()}catch{}}))}catch(e){S().warn("Failed to connect to the log server",e)}},minCallDelayMs:l.minuteMs,name:"#mkSocket"})),r(this,n,"f").call(this)}enabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,s){if(this.enabled(e,t))try{const a=this.socket;null==a?r(this,n,"f").call(this):a.write(this.logFormatter.format(e,t,i,s)+b)}catch(n){S().warn("Failed to write log entry to socket",{level:e,context:t,msg:i,meta:s,error:n})}}flush(){const e=new d.Latch;return this.socket?.write("",(()=>e.resolve())),e.promise}}n=new WeakMap},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=void 0;const n=i(76760),r=i(42659),s=i(28874);t.datedLogDir=function(e,t){return(0,n.join)(e??s.Settings.logDir.valueOrDefault,(0,r.fmtIsoDate)(t??new Date))}},4904:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const n=i(76790),r=i(31586),s=i(51926),a=i(57902);t.isLogEntry=function(e){return null!=e&&(0,r.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&a.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,n.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const n=i(19851),r=i(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,r.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,r.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,n.lazy)((()=>new s(r.LogLevels.warn))),t.defaultLogLevel=(0,n.lazy)((()=>r.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,r.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)}},28538:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const l=i(19851),u=i(40958),c=i(22573),d=i(54993),h=i(28874),f=i(66184),m=i(57902);t.LogFilterImpl=class{constructor(e=h.Settings.logLevel){n.add(this),this.setting=e,this.silent=!1,r.set(this,[]),s.set(this,(0,l.lazy)((()=>{o(this,r,"f").length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=m.LogLevels.indexOf(e)??m.LogLevels.indexOf(this.setting.defaultValue)??m.LogLevels.indexOf(m.LogLevels.warn);const t=(0,u.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=f.LogLevelRe.exec(i.trim());if(null==t)console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,d.toS)(t[1]).toLowerCase(),i=(0,m.levelIndex)(t[2]);(0,c.blank)(e)?this.defaultLevelIndex=i:o(this,r,"f").push({prefix:e,levelIndex:i})}}}))),e.watch((()=>o(this,s,"f").refresh()))}enabled(e,t){if(this.silent)return!1;const i=(0,m.levelIndex)(e);if(null!=t){const e=o(this,n,"m",a).call(this,t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=o(this,n,"m",a).call(this,e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}},r=new WeakMap,s=new WeakMap,n=new WeakSet,a=function(e){if(null==e||0===o(this,r,"f").length||(0,c.blank)(e))return;const t=(0,d.toS)(e).toLowerCase();return o(this,r,"f").find((e=>t.startsWith(e.prefix)))}},57902:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const n=i(31586),r=i(50989),s=i(28874);t.LogLevels=(0,r.strEnum)("fatal","error","warn","info","debug","trace");const a=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??a},t.levelGte=function(e,i){return(0,n.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(i))};const o=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return o.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},93475:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.prepMeta=t.PromisePlaceholder=void 0;const n=i(40958),r=i(68708),s=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)",t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,n=Math.floor(t/2);return i.length<=t?i:[...i.slice(0,n).map((t=>e(t,h-1))),`… (${i.length} total entries)`,...i.slice(-n).map((t=>e(t,h-1)))]}if("object"==typeof i||"function"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,s.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,((t,i)=>e(i,h-1)),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,r.keys)(i),(0,r.keys)(o));return(0,n.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i}},24068:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=t.DefaultLogEntryWriter=void 0;const n=i(73024),r=i(76760),s=i(1708),a=i(87997),o=i(19851),l=i(22573),u=i(42659),c=i(49769),d=i(55835),h=i(34666),f=i(20214),m=i(7282),p=i(23560),g=i(54826),y=i(82328),v=i(22277),w=i(25764),S=i(38836),b=i(99331),P=i(42638),M=i(76596),_=i(98314),E=i(89968),x=i(29882),T=i(28874),D=i(28981),k=i(20839),C=i(21727),F=i(66184),O=i(57902),I=i(72210),L=i(98192);function A(e){const t=(0,D.DefaultLogFormatter)();for(const i of e)(0,g.consoleLog)(t.formatLogEntry(i))}t.DefaultLogEntryWriter=A;class R extends S.EndableWrapper{constructor(e=void 0,t=A){super("LogTail",(()=>this.close()),w.EndableRanks.logtail),this.rootNativePath=e,this.writer=t,this.watchers=new Map,this.filenameMutexes=new P.Promises("log.LogTail",(()=>8)),this.file2pos=new Map,this.lastReadFiles=new v.TTLSet(5*u.secondMs),this.setup=(0,o.lazy)((async()=>{const e=(0,l.notBlankOr)(this.rootNativePath,T.Settings.logDir.valueOrDefault);(0,m.isTest)()&&(0,g.consoleLog)("tailing "+e+"..."),await(0,x.mkdirp_)(e),this.root=await E.DirectoryEntry.for(e),await this.scan(!0)})),this.ignorableFilename=r.sep+(0,p.serviceName)()+"-"+s.pid+"-",s.stdout.writableFinished||((0,I.setLogTailEnabled)(!0),this.flushTimeout=(0,a.setInterval)((()=>this.flush()),k.DefaultLogFlushMs/2),this.scanTimeout=(0,a.setInterval)((()=>this.scan()),u.minuteMs),s.stdout.on("end",(()=>this.end())),this.setup())}async flush(){this.writer((0,I.popExpiredLogEntries)())}readable(e){return e.endsWith(".log")&&!e.includes(this.ignorableFilename)}watchDir(e){(0,b.ending)()||this.ended||(0,c.getOrSet)(this.watchers,e,(()=>{(0,F.ifLog)(O.LogLevels.debug,(()=>(0,g.consoleLog)("LogTail(): watching "+e)));try{return(0,n.watch)(e,((t,i)=>{(0,l.notBlank)(i)&&this.watchListener(t,(0,r.join)(e,i))}))}catch(t){return void(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): failed to read "+e+": "+(0,_.errorToS)(t))))}}))}async scan(e=!1){if((0,b.ending)()||this.ended)return;if(await this.root.visitDescendants((async t=>{this.readable(t.nativePath)&&(e&&await(0,f.thenMap)(t.size(),(e=>this.file2pos.set(t.nativePath,e))),(0,M.nowish)(t.mtimeMs(),5*u.minuteMs)&&this.watchDir(t.dir))})),(0,b.ending)()||this.ended)return;const t=(0,C.datedLogDir)(this.root.nativePath);try{await(0,x.mkdirp_)(t),this.watchDir(t)}catch(e){(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("LogTail(): Failed to list or mkdir -p "+t+": there may be permission issues: "+(0,_.errorToS)(e))))}(0,b.ending)()||this.ended||e&&(0,g.consoleLog)("LogTail(): Tailing "+this.root+"/**/*.log...")}async close(){(0,I.setLogTailEnabled)(!1),(0,d.map)(this.flushTimeout,a.clearInterval),this.flushTimeout=void 0,(0,d.map)(this.scanTimeout,a.clearInterval),this.scanTimeout=void 0;for(const e of this.watchers.values())e.close();this.watchers.clear();for(const e of this.lastReadFiles)await this.watchListener("onEnd",e);try{this.writer((0,I.popExpiredLogEntries)(-1))}catch(e){console.warn("failed to flush last log entries",e)}}async watchListener(e,t){this.readable(t)&&"rename"!==e&&await this.filenameMutexes.serial(t,(async()=>{try{const e=await E.DirectoryEntry.for(t);if(null==e)return;const i=e.size();if(null==i||i<=0)return;const n=this.file2pos.get(e.nativePath)??0;if((0,h.gte)(n,i))return;await(0,f.thenMap)((0,L.readLogEntries)(e,{start:n,end:i}),(e=>(0,I.pushLogEntries)(...e))),this.lastReadFiles.add(e.nativePath),this.file2pos.set(e.nativePath,i)}catch(e){(0,F.ifLog)(O.LogLevels.warn,(()=>(0,g.consoleError)("Failed to read "+t+": "+(0,_.errorToS)(e))))}}))}}t.LogTail=R,R.instance=(0,o.lazy)((()=>(0,y.stdoutEnded)()?void 0:new R))},72210:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const n=i(92322),r=i(82328),s=i(28981),a=i(20839),o=i(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new n.SortedSet(o.logEntrySorter),t.pushLogEntries=function(...e){for(const i of e)l?t.logEntries.add(i):(0,r.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(i))},t.popExpiredLogEntries=function(e=2*a.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},43705:function(e,t,i){var n,r,s,a,o,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},d=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.CaptureLogger=void 0;const h=d(i(73024)),f=i(76760),m=i(19851),p=i(42659),g=i(41400),y=i(98553),v=i(31586),w=i(409),S=i(23560),b=i(81168),P=i(78406),M=i(25764),_=i(20197),E=i(14977),x=i(36868),T=i(28874),D=i(32105),k=i(20839),C=i(21727),F=i(66184),O=i(93475),I=i(22662);t.CaptureLogger=class{constructor(){this.logEntries=[]}log(e,t,i,n){this.logEntries.push({ts:Date.now(),l:e,ctx:t,msg:i,meta:n})}enabled(){return!0}end(){}async flush(){}};class L extends P.EndableInterval{constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.flush(),intervalMs:Math.round(t.flushEveryMs??1.25*k.DefaultLogFlushMs),rank:M.EndableRanks.logger,unref:!0,onEnd:()=>c(this,r,"f").call(this)}),n.add(this),this.logDir=e,this.pendingWrites=[],this._linesSinceRotate=0,this._nextForcedRotateTs=(0,p.nextMidnightTs)(),this._startIndex=0,this.endTimeoutMs=15*p.secondMs,r.set(this,(0,m.lazy)((async()=>(await this.flush.force(),c(this,n,"m",u).call(this))))),this.logOpts={maxLinesPerFile:25e4,errorLogger:D.ConsoleLogger.instance(),flushEveryMs:k.DefaultLogFlushMs,processName:S.processName,logFilter:F.logFilter,...t},this.setIntervalMs(this.logOpts.flushEveryMs),this.flush=(0,w.rateLimited)({name:"LogWriter.flush()",minCallDelayMs:this.logOpts.flushEveryMs,f:()=>c(this,n,"m",s).call(this)})}toJSON(){return{_ctor:"LogWriter",logDir:this.logDir}}enabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,n){if(this.enabled(e,t))if(this.ended&&"error"===e)this.logOpts.errorLogger.log(e,t,i,n);else{const r={ts:Date.now(),l:e,ctx:t,msg:i};null!=n&&(r.meta=(0,O.prepMeta)(n)),"error"===e&&this.writeRecentLogEntries(),this.pendingWrites.push(r)}}writeRecentLogEntries(){this.pendingWrites.push(...(0,I.recentLogEntries)()),(0,I.clearRecentLogEntries)()}shouldRotate(){return null==this._logfile||this._linesSinceRotate>=this.logOpts.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}}t.LogWriter=L,r=new WeakMap,n=new WeakSet,s=async function(){const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.shouldRotate()&&await c(this,n,"m",l).call(this);const t=this._logfile?.stream;if(null==t)return void this.logOpts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const i=(0,v.clamp)(0,e.length,this.logOpts.maxLinesPerFile-this._linesSinceRotate),r=e.splice(0,i);this._linesSinceRotate+=r.length,t.write(r.map((e=>(0,y.stringify)(e)+"\n")).join(""))}},a=function(e,t){this.logOpts.errorLogger.log("error","Caught error from "+e,t)},o=function(e){return t=>(c(this,n,"m",a).call(this,e,t),c(this,n,"m",u).call(this))},l=async function(){await c(this,n,"m",u).call(this);const e=(0,b.stripAnsiEsc)(this.logOpts.processName()),t=await(0,_.ensureNewNativePath_)({nativePath:(0,f.join)((0,C.datedLogDir)(this.logDir),e+".log"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=h.default.createWriteStream(t).on("error",c(this,n,"m",o).call(this,"file write stream"));this._logfile={stream:i,nativePath:t},this._nextForcedRotateTs=(0,p.nextMidnightTs)()},u=async function(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,x.endStream)(e.stream),T.Settings.logCompression.valueOrDefault&&(await(0,g.delay)(this.logOpts.flushEveryMs),await(0,E.gzip_)(e.nativePath))}catch(e){c(this,n,"m",a).call(this,"_closeCurrent()",e)}}},51879:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const n=i(57975),r=i(40958),s=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,r.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,n.inspect)(e,this.inspectOptions)))]).map((e=>(0,o.toS)(e))).join(" ")}format(e,t,i,n){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:n})}}},98192:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.chunkToLogEntry=t.readLogEntries=void 0;const n=i(22573),r=i(84542),s=i(4001),a=i(13047),o=i(4904);function l(e){if(!(0,n.blank)(e))try{const t=JSON.parse(e);return(0,o.isLogEntry)(t)?t:void 0}catch(e){return}}t.readLogEntries=async function(e,t){const i=(0,s.stripCopySuffixFromName)(e.name),n=[],o=await(0,a.zcat)(e.nativePath,t);if(null!=o)for(const e of(0,r.splitLines)(o)){const t=l(e);null!=t&&n.push({...t,from:i})}return n},t.chunkToLogEntry=l},22662:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.recentLogEntries=t.addRecentLogEntry=t.clearRecentLogEntries=t.SentLogLevels=void 0;const n=i(19851),r=i(76790),s=i(68708),a=i(89788),o=i(57902);t.SentLogLevels=(0,n.lazy)((()=>o.LogLevels.values.filter((e=>e!==o.LogLevels.trace))));const l=(0,n.lazy)((()=>(0,s.fromEntries)((0,t.SentLogLevels)().map((e=>[e,new a.BoundedList(48)])))));t.clearRecentLogEntries=function(){(0,s.values)(l()).forEach((e=>e.clear()))},t.addRecentLogEntry=function(e){l()[e.l]?.push(e)},t.recentLogEntries=function(){const e=[];for(const t of(0,s.values)(l()))e.push(...t.toA());return(0,r.sortBy)(e,(e=>e.ts))}},17181:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogFormatter=t.setupLogger=void 0;const n=i(76760),r=i(41400),s=i(55835),a=i(37975),o=i(50213),l=i(27395),u=i(46296),c=i(96706),d=i(73428),h=i(28874),f=i(49794),m=i(32105),p=i(89179),g=i(28981),y=i(51576),v=i(66184),w=i(28538),S=i(24068),b=i(43705),P=i(51879);function M(){(0,v.logFilter)()instanceof w.LogFilterImpl||v.logFilter.set(new w.LogFilterImpl),_();const e=(0,u.logDir)();let t=(0,p.currentFileLogger)();null!=t&&t.logDir===e||((0,l.end)(t),(0,d.writeTextfile_)((0,n.join)(e,"README.txt"),'PhotoStructure writes logfiles to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge,\nchronologically sort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch((()=>null)),t=new b.LogWriter(e));const i=[t];((0,c.isEnvTrue)("logStdout")||h.Settings.logStdout.valueOrDefault||h.Settings.tailLogs.valueOrDefault)&&i.push(m.ConsoleLogger.instance()),(0,s.map)((0,y.logBroadcaster)(),(e=>i.push(e))),o.rootLoggers.set(i),h.Settings.tailLogs.valueOrDefault&&S.LogTail.instance()}function _(){const e=h.Settings.logColor.valueOrDefault;(0,a.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new f.ColoredLogFormatter:new P.PlaintextLogFormatter)}t.setupLogger=M,t.setupLogFormatter=_,(0,r.later)((()=>{h.Settings.logStdout.watchLater(M),h.Settings.logDir.watchLater(M),h.Settings.tailLogs.watchLater(M),h.Settings.logColor.watchLater(_),h.Settings.logLevel.watchLater((()=>v.defaultLogLevel.unset()))}))},82647:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const a=i(57975),o=i(40958),l=i(96249),u=i(55835),c=i(31586),d=i(68708),h=i(59455),f=i(48884),m=i(89788),p=i(22454),g=i(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const i=t.clone();return i.pushAll(e.samples),i}if(t.n<=t.maxSamples){const i=e.clone();return i.pushAll(t.samples),i}{const i=new y(Math.max(e.maxSamples,t.maxSamples));i._n=e.n+t.n,i._min=Math.min(e._min,t._min),i._max=Math.max(e._max,t._max),i._m=e._m*e.n/i.n+t._m*t.n/i.n,i._s=e._s*e.n/i.n+t._s*t.n/i.n;const n=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return i._samples.push(...n),i._weightedTotalAvg=(0,g.weightedAvg)([i._m,...n]),i}}constructor(e=20){n.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(n=new WeakSet,a.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,g.min)([this._min,e.min]),this._max=(0,g.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),i={};return i.k=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min)),i}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,n,"m",r).call(this,-1)}get p29(){return s(this,n,"m",r).call(this,-.5)}get p38(){return s(this,n,"m",r).call(this,-.25)}get p69(){return s(this,n,"m",r).call(this,.5)}get p84(){return s(this,n,"m",r).call(this,1)}get p98(){return s(this,n,"m",r).call(this,2)}get p99(){return s(this,n,"m",r).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new p.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,o.mapNotEmpty)(this._samples,g.variance)}get sampleStdDev(){return(0,o.mapNotEmpty)(this._samples,g.stdDev)}get sampleAvg(){return(0,o.mapNotEmpty)(this._samples,g.avg)}get sampleSlope(){return(0,g.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,g.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,r=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const n=i(40958),r=i(55835),s=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),n=[];for(;e>0;)n.unshift(e%i),e=Math.floor(e/i);return n}t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce(((e,t)=>e*i+(0,s.clamp)(0,i,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,r.map2)(e,t,((e,t)=>(0,n.sum)((0,o.zip)(u(e,i),u(t,i)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,a.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max)),r=this.clampValue(e);let s=0;for(let e=0;ea?(s+=1,i[t]=a):n[t]=a}return s}unzip(e,t){const i=this.dims.map((e=>e.min)),n=this.dims.map((e=>e.max));for(let r=0;r(i[e]+n[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let i=0;is?(t+=1,r.min=s):r.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,n.sum)(e,((i,n)=>t(i,n)?Math.pow(2,e.length-n-1):0))}},44983:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.kmeans=void 0;const n=i(76790),r=i(93973);t.kmeans=function(e,t,i){const s=r(e,t,i);return{...s,centroids:(0,n.sortBy)(s.centroids.filter((e=>e.size>0)),(e=>-e.size))}}},31843:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lerp2d_=t.lerp2d=t.lerp=void 0;const n=i(76790);function r(e,t,i=.5){return(1-i)*e+i*t}t.lerp=r,t.lerp2d=function(e,...t){const i=(0,n.sortBy)(t,(t=>Math.abs(e-t.x))).slice(0,2),[s,a]=(0,n.sortBy)(i,(e=>e.x)),o=a.x-s.x,l=(e-s.x)/o;return r(s.y,a.y,l)},t.lerp2d_=function(e,t,i){return(t.y*(i.x-e)+i.y*(e-t.x))/(i.x-t.x)}},75503:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.modeReduce=t.submatrixCollect=t.greatestHalf=t.leastVariantQuarter=t.leastMagQuarter=t.submatrixMode=t.submatrixStdDev=t.submatrixMagnitude=t.submatrixForEach=t.index1D=t.slice=t.matXvec=t.vecXvec=void 0;const n=i(40958),r=i(31586),s=i(48884),a=i(82647),o=i(70417);function l(e,t,i,n){const r=Math.floor(Math.max(0,t.row)),s=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=r;t(0,r.mapFinite)(e[t],(e=>s+=e*e)))),Math.sqrt(s)}function c(e,t,i,n){const s=new a.Average;return l(t,i,n,(t=>(0,r.mapFinite)(e[t],(e=>s.push(e))))),s.stdDev}function d(e,t,i,n){const s=[];return l(t,i,n,(t=>(0,r.mapFinite)(e[t],(e=>s.push(e))))),(0,o.mode)(s)}t.vecXvec=function(e,t){return e.map(((e,i)=>e*t[i]))},t.matXvec=function(e,t){return e.map(((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,((e,i)=>e*t[i]))}))},t.slice=function(e,t,i){const r=Math.max(0,t.row),s=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,n.range)(r,s,(t=>e[t].slice(a,o)))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,n=t.row,r=[u(e,t,{col:i/2,row:0},{col:i,row:n/2}),u(e,t,{col:0,row:0},{col:i/2,row:n/2}),u(e,t,{col:0,row:n/2},{col:i/2,row:n}),u(e,t,{col:i/2,row:n/2},{col:i,row:n})];return(0,s.leastIndex)(r)},t.leastVariantQuarter=function(e,t){const i=t.col,n=t.row;return(0,s.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:n/2}),c(e,t,{col:0,row:0},{col:i/2,row:n/2}),c(e,t,{col:0,row:n/2},{col:i/2,row:n}),c(e,t,{col:i/2,row:n/2},{col:i,row:n})])},t.greatestHalf=function(e,t){const i=t.col,n=t.row,r=[d(e,t,{col:0,row:0},{col:i,row:n/2}),d(e,t,{col:0,row:0},{col:i/2,row:n}),d(e,t,{col:0,row:n/2},{col:i,row:n}),d(e,t,{col:i/2,row:0},{col:i,row:n})];return(0,s.greatestIndex)(r)},t.submatrixCollect=function(e,t,i){const n=[];return l(e,t,i,(e=>n.push(e))),n},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,s.concat)(...(0,n.stepRange)(0,t.row,u,(i=>(0,n.stepRange)(0,t.col,o,(n=>(c.clear(),l(t,{col:n,row:i},{col:n+o,row:i+u},(t=>(0,r.mapFinite)(e[t],(e=>c.push(e))))),c.sampleMode))))))}},55222:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const n=i(77598),r=i(22573),s=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const n=[];if(0===t)n.unshift(0);else for(;t>0;)n.unshift(t%e),t=Math.floor(t/e);for(;n.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let n=e;for(;n>u;)t.push(Number(n%i)),n/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach(((e,n)=>{i+=e<<8,t[n]=i%this.base,i=Math.floor(i/this.base)}));i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,r.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let n=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;n=n*i+BigInt(e)}return t?BigInt(-1)*n:n}randomChars(e){return this.encodeBuffer((0,n.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const n=this.normalizeToken(e),r=this.normalizeToken(t);return n.length>=i&&n===r}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const n=i(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,n.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},56946:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intToRoman=t.romanToInt=t.RomanNumerals=void 0;const n=i(31586),r=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"],t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,n.toInt)(e)]??(0,r.toS)(e)}},17921:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UUIDRegExp=t.safeUUID=t.uuid=void 0;const n=i(77598),r=i(65713);function s(){const e=(0,n.randomBytes)(16);e[6]=15&e[6]|64;const t=e.toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}t.uuid=s,t.safeUUID=function(){return(0,r.decuss)(s)},t.UUIDRegExp=/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/},70417:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},a=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const o=i(40958),l=i(55835),u=i(31586),c=i(59455),d=i(22454),h=i(77377),f=i(82647);function m(e){let t;for(const i of e)null!=i&&(null==t||it)&&(t=i);return t}function y(e,t){const i=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function v(e,t){let i=0,n=0;for(const r of e){if(null!=r){const e=t(r,i);(0,u.isNumber)(e)&&(n+=e)}i++}return n}t.min=m,t.max=g,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,i)=>e-t[i]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const i of e)(0,u.isNumber)(i)&&(t+=i);return t},t.sumf=v;class w{constructor(){n.set(this,0),r.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(a(this,r,null==s(this,r,"f")?e:s(this,r,"f")*s(this,n,"f")/(s(this,n,"f")+1)+e/(s(this,n,"f")+1),"f"),a(this,n,(t=s(this,n,"f"),++t),"f"))}get mean(){return s(this,r,"f")}}function S(e){const t=new w;for(const i of e)t.push(i);return t.mean}function b(e){const t=S(e);if(null==t)return;let i=0,n=0;for(const r of e)(0,u.isNumber)(r)&&(n++,i+=(r-t)*(r-t));return i/n}function P(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function M(e,t){let i=0;for(let n=0;n(1-t)*e+t*(i+a*(e-r)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),i=S(t);if(null!=i){const e=(t.length-1)/2,n=v(t,((t,n)=>(t-i)*(n-e))),r=v(t,(e=>(e-i)**2));return 0===r?0:n/r}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let i;t=(0,u.clamp)(0,1,t);for(const n of e)i=null==i?n:i*t+n*(1-t);return i},t.centroid=function(e){const t=e[0].length,i=[];for(let n=0;ne[n]))));return i},t.l2norm=P,t.dot=M,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(M(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,o.isEmpty)(e)&&(0,o.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},23624:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.b64encodeBits=t.b64hammRatio=t.gz64decodeString=t.d=t.gz64encodeString=t.b64decode=t.b64encode=t.hex2b64=void 0;const n=i(38522),r=i(22573),s=i(97352);function a(e){const t=e.toString(16),i=t.length%2==0?"":"0";return Buffer.from(i+t,"hex").toString("base64")}function o(e){return BigInt("0x0"+Buffer.from(e,"base64").toString("hex"))}function l(e){return(0,n.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.hex2b64=function(e){return Buffer.from(e,"hex").toString("base64")},t.b64encode=a,t.b64decode=o,t.gz64encodeString=function(e){return(0,n.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=l,t.gz64decodeString=l,t.b64hammRatio=function(e,t){return(0,r.mapNotBlank)(e,(e=>(0,r.mapNotBlank)(t,(t=>(0,s.hammRatioBigInt)(o(e),o(t))))))},t.b64encodeBits=function(e){return a(BigInt("0b0"+e.map((e=>1===e?"1":"0")).join("")))}},49076:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fsSafeHostname=t.cleanHostname=t.hostname=void 0;const r=n(i(48161)),s=i(19851),a=i(22573),o=i(41400),l=i(81168),u=i(28874);t.hostname=(0,s.lazy)((()=>u.Settings.hostname.value??r.default.hostname())),(0,o.later)((()=>u.Settings.hostname.watchLater((()=>t.hostname.unset())))),t.cleanHostname=function(e){return(0,a.blank)(e)&&!(0,a.blank)(u.Settings.hostname.value)?u.Settings.hostname.value:(e??r.default.hostname()).replace(/\.local$/,"").replace(/-?\d+$/,"")},t.fsSafeHostname=function(e=(0,t.hostname)()){return(0,l.stripDiacritics)(e).replace(/[^a-z\d\s-]/gi,"").trim().replace(/\s+/g,"-").toLowerCase()}},96128:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEquivalentHost=t.nslookup=t.resolve4=t.octets=t.isLoopback=t.friendlyname=void 0;const n=i(40610),r=i(19851),s=i(22573),a=i(42659),o=i(41400),l=i(31586),u=i(13538),c=i(83104),d=i(54993),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(1728),y=i(56519),v=i(34102),w=i(26293),S=new RegExp("^"+w.ipv4Re.source+"$");t.friendlyname=(0,g.memoizeAsync)((async e=>{const i=null==S.exec(e)?e:await(0,t.nslookup)(e);return(0,d.toS)(i).toLowerCase().normalize()}),{name:"net.nslookup.friendlyname",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const b=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function P(e){return null!=b.exec(e)}function M(e){const t=e.split(".").map((e=>(0,l.toInt)(e))).filter((e=>(0,f.within)(0,255,e)));return 4===t.length?t:void 0}t.isLoopback=P,t.octets=M,t.resolve4=(0,g.memoizeAsync)((async e=>{if(!(0,s.blank)(e)){if(null!=M(e))return[e];try{return await n.promises.resolve4(e)}catch(t){return void _().warn("No name found for "+e)}}}),{name:"net.nslookup.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const _=(0,r.lazy)((()=>(0,h.mkLogger)("net.nslookup")));(0,o.later)((()=>(0,v.ee)().on("clearCache",(()=>t.nslookup.clear())))),t.nslookup=(0,g.memoizeAsync)((async e=>{try{const t=await(0,u.thenOrTimeout)(P(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=M(e)?n.promises.reverse(e):n.promises.resolve4(e),5*a.secondMs);if(t===c.Timeout)return _().info("nslookup("+e+"): timeout"),e;const i=t.find(s.notBlank);return null==i?(_().warn("No name found for "+e),e):i}catch(t){return _().warn("Failed to look up "+e+", using name.",t),e}}),{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs}),t.isEquivalentHost=async function(e,i){return!(0,s.blank)(e)&&!(0,s.blank)(i)&&(!!(0,p.equalsIgnoreCase)(e,i)||!(!P(e)||!P(i))||(0,y.thenMap2Or)((0,t.resolve4)(e),(0,t.resolve4)(i),((e,t)=>e.some((e=>t.includes(e)))),(()=>!1)))}},26293:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const n=i(22573),r=i(42659),s=i(31586),a=i(97790),o=i(54993),l=i(1728),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoizeAsync)((async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*r.secondMs})}),{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,s.times)(4,(()=>"[0-9]{1,3}")).join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoizeAsync)((async e=>(0,a.opt)(await(0,t.ping)(e).catch((e=>{console.warn("failed to ping: "+e)}))).filter(n.notBlank).flatMap((e=>t.ipv4Re.exec((0,o.toS)(e)))).map((e=>e[0])).get()),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*r.minuteMs})},78330:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aptCachePolicyVersion=t.aptInstalledVersion=void 0;const n=i(40958),r=i(22573),s=i(45599),a=i(59455),o=i(50213),l=i(96175),u=i(84777),c=i(84542),d=i(76280),h=i(63870),f=(0,s.defer)((()=>(0,o.mkLogger)("platform.Apt")));t.aptInstalledVersion=async function(e){if(!(0,l.hasApt)())return;const t=[];for(const i of(0,a.toA)(await async function(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return f().debug("dpkg -S",{nativePath:e,result:t}),0!==t.code?void 0:(0,n.uniq)((0,c.splitLines)(t.result).map((e=>m.exec(e)?.[0])))}(e))){const e=await p(i);t.push({pkg:i,version:e,semver:(0,d.debianVersionToSemver)(e)})}return t};const m=/^[a-z][a-z\d+\-.]+/;async function p(e){if(!(0,l.hasApt)()||(0,r.blank)(e))return;const t=await(0,u.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(f().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,c.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}t.aptCachePolicyVersion=p},45969:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const n=i(73024),r=i(38639),s=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,s.lazy)((()=>o.isLinux&&((0,r.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,n.existsSync)("/.running-in-container"))))},29325:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const n=i(76760),r=i(19851),s=i(54993);t.isPacked=(0,r.lazy)((()=>!(0,s.toS)(__filename).includes((0,n.join)("core","platform","IsPacked"))))},46305:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pacmanInstalledVersion=t.hasPacman=void 0;const n=i(45599),r=i(50213),s=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,n.defer)((()=>(0,r.mkLogger)("platform.Pacman")));t.hasPacman=(0,n.defer)((()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf")));const c=/is owned by (?\S+) (?\S+)/i;t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=await(0,s.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}});return u().tap({msg:"pacman -Qo",result:t.result.match(c)?.groups,meta:{nativePathOrBasename:e,result:t}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}}},43334:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const r=n(i(48161)),s=n(i(1708)),a=i(22573),o=i(38639),l=i(59958),u=r.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,o.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,a.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===r.default.arch(),t.isArm=null!=/^arm\b/i.exec(r.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,a.notBlank)(s.default.env.APPIMAGE)||(0,a.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,a.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,o.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const r=n(i(73024)),s=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=r.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=o,t.isRaspberryPi=(0,s.lazy)((()=>a.isLinux_arm&&o())),t.procDeviceModel=(0,s.lazy)((()=>{try{return a.isLinux?r.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},94137:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=void 0;const n=i(22573),r=i(51926),s=i(83556);t.negateFilterName=function(e){if((0,n.blank)(e))return;const t=/\s/.test(e)?e:(0,s.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,r.stripPrefix)(t,"is ")}},78984:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const n=i(19851),r=i(40958),s=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,n.lazy)((()=>(0,o.mkLogger)("predicates.Predicates")));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,s.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],n=[],r=[];for(const o of t)for(const[t,l]of(0,s.entries)(o)){const s=await l(e);!0===s?i.push(t):!1===s||(0,a.isString)(s)?n.push(t):r.push(t)}return{accepted:i,rejected:n,notApplicable:r}}static async whyRejected(e,...t){for(const i of t)for(const[t,n]of(0,s.entries)(i))try{const i=await n(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:n}){const{accepted:s,rejected:a}=await c.explain(e,...n);return t.tap({msg:i,result:(0,r.isEmpty)(a),meta:{a:e,accepted:s,rejected:a}})}}t.Predicates=c},33995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const n=i(68708),r=i(94137);class s{static firstFalse(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))if(!1===r(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))if(!0===r(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i)){const i=r(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==s.firstFalse(e,...t)}static whyRejected(e,...t){return(0,r.negateFilterName)(s.firstFalse(e,...t))}}t.SyncPredicates=s},45643:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const n=i(58587),r=i(59455),s=i(31562);t.existingPids=function(e){return(0,r.toA)(e).filter(n.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,n.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,i){var n,r,s,a,o=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,i):r?r.value=i:t.set(e,i),i},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=i(58587),d=u(i(31421)),h=u(i(1708)),f=i(40958),m=i(22573),p=i(42659),g=i(55835),y=i(31586),v=i(97790),w=i(59455),S=i(54993),b=i(54557),P=i(19851),M=i(50213),_=i(88158),E=i(409),x=i(78406),T=i(25764),D=i(99331),k=i(56519),C=i(46292),F=i(8769),O=i(83278),I=i(32144),L=i(29882),A=i(43334),R=i(24399),N=i(58261),B=(0,P.lazy)((()=>(0,M.mkLogger)("proc.Pids"))),z=10*p.secondMs;function j(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,g.map)(t.start,(e=>e.getTime())),n=e.startTime;return(0,y.gt0)(i)&&(0,y.gt0)(n)&&Math.abs(i-n){const e=Date.now()-2*p.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,I.isJsonExt)(t)&&(0,L.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))B().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,E.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:p.minuteMs,f:async(e={})=>{B().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??A.isWin,n=await this.pidfiles(),r=await this.pids(n??[]);if((0,f.isEmpty)(r))return B().info("killOldProcs(): no pidfiles"),[];const s=[],a=[],o=await(0,N.pidInfos)(r);if(null!=o){for(const r of n){const n=await r.readJson();if(null==n){B().warn("killOldProcs(): failed to read pidfile "+r.base),await r.unlink("debug");continue}const l=n.pid;if(!(0,y.gt0)(l)){B().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+r.base,{json:n,pid:l}),await r.unlink("debug");continue}const u=o.find((e=>e.pid===l));if(null==u||!j(n,u)){B().debug("killOldProcs(): pid no longer present: unlinking "+r.base,{json:n,pidEntry:u}),await r.unlink("debug"),s.push(n);continue}const c=(0,y.gt0)(n.timeoutMs)?n.startTime+n.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(n.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(B().info("killOldProcs(): killing",{reason:d,json:n}),a.push(W(l,i,!1)),s.push({...n,...u}))}return a.length>0&&await Promise.allSettled(a),s}(0,F.onError)("Pids.killOldProcs(): failed to get process information")}}),a.set(this,void 0)}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const a=e.pid;if(!(0,y.gt0)(a))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(a)?(i&&o(this,r,"f").delete(l),o(this,r,"f").getOrSet(l,(async()=>{const i=o(this,n,"m",s).call(this,e.pid),r=(0,v.opt)((0,_.Try)((()=>(0,L.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),a=t.getTime(),l={...e,cmd:r,startTime:a};return await i.writeJson_(l),B().debug("addPid() wrote "+i,l),i}))):(o(this,r,"f").delete(l),void B().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=o(this,n,"m",s).call(this,e);return(0,k.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,p.ago)(p.minuteMs),!0).catch((t=>{B().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==o(this,a,"f")||o(this,a,"f").ended)&&l(this,a,new x.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*p.minuteMs,rank:T.EndableRanks.first}),"f"),o(this,a,"f")}cancelInterval(){o(this,a,"f")?.end(),l(this,a,void 0,"f")}}t.Pids=H,r=new WeakMap,a=new WeakMap,n=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},H.instance=(0,P.lazy)((()=>(0,g.map)((0,C.configDir)(),(e=>new H(O.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return H.instance()?.addPid_(e,t)}},58261:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const r=i(31421),s=i(48161),a=n(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(31586),d=i(68708),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84968),w=i(48963),S=i(56519),b=i(84777),P=i(8103),M=i(45879),_=i(43334),E=i(24399),x=i(45643),T=(0,g.lazy)((()=>(0,y.mkLogger)("proc.ps")));function D(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function k(e){if(_.isLinux)return async function(e){const t=[];for(const i of e)t.push(V(await(0,M.readFileMaybe)("/proc/"+i+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,o.compact)(t)})}(e);const t=(0,x.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,_.isWin?I:N)).filter((e=>D(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}t.isProcEntry=D,t.pidInfo=async function(e){return(0,S.thenMap)(k([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,o.isEmpty)(e)?[]:(0,S.thenMap)((0,x.existingPids)(e),(t=>{const i=[a.default.pid,...t];return e.filter((e=>!i.includes(e)))}))},t.pidInfos=k;const C="Get-Process",F="| Select-Object -Property Id,ProcessName,StartTime";function O(e){return(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).join(",")}async function I(e){if(E.PowerShell.instance().ended)return R(e);const t=[C,"-Id",O(e),"-ErrorAction SilentlyContinue",F].join(" ");return(0,S.thenMap)(E.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const L={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},A=["CommandLine","CreationDate","ProcessId"];async function R(e){const t=["process"];if((0,o.isNotEmpty)(e)){const i=(0,o.uniq)([...e.filter(c.gt0),a.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",i)}t.push("get",A.join(","));const i=await(0,b.stdoutResult_)((0,P.wmic)(),t,L),n=(0,d.onlyReqValued)((0,p.parseFixed)(A,i.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return n.find((e=>e.pid===a.default.pid))||n.push({pid:a.default.pid,start:new Date(v.StartTs),cmd:"node "+a.default.title}),n}async function N(e){return t=(await(0,b.stdoutResult_)("ps",["-p",O(e),"-wwwo","pid,lstart,command"],{...L,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=R;const B=(0,g.lazy)((()=>{try{if(_.isLinux)return(0,c.toGt0)((0,r.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){T().warn("clk_tck failed",{error:e})}return 100})),z=(0,g.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),j=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function V(e){const t=j.exec((0,f.toS)(e))?.groups,i=(0,c.toInt)(t?.pid),n=t?.comm,r=(0,c.toInt)(t?.starttime);return(0,c.gt0)(i)&&!(0,l.blank)(n)&&(0,c.gt0)(r)?{pid:i,cmd:n,start:new Date(z()+r/B()*u.secondMs),state:t?.state}:void 0}},87445:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isProgressEvt=t.progressEvtToS=void 0;const n=i(40958),r=i(22573),s=i(31586),a=i(29882),o=i(97352);t.progressEvtToS=function(e){const t=(0,r.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,n.compactBlanks)([t,e.op,!0===e.done?"done":(0,s.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,r.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)}},41944:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onProgressEvt=t.emitProgressEvt=t.recentDone=t.recentProgress=t.DefaultThrottleMs=void 0;const n=i(19851),r=i(42659),s=i(31586),a=i(12089),o=i(75387),l=i(34102),u=i(87445);t.DefaultThrottleMs=500,t.recentProgress=(0,n.lazy)((()=>new o.TTLMap(15*r.secondMs))),t.recentDone=(0,n.lazy)((()=>new o.TTLMap(2*r.minuteMs))),t.emitProgressEvt=function(e){if((0,u.isProgressEvt)(e)){const i=!0===e.done;i&&null!=e.path&&(0,t.recentDone)().set(e.path,e),!i&&null!=e.path&&(0,s.gte)((0,t.recentProgress)().lastSetOrGetTs(e.path),Date.now()-t.DefaultThrottleMs)||((0,t.onProgressEvt)(e),null!=e.path&&(0,t.recentProgress)().set(e.path,e))}},t.onProgressEvt=(0,a.shim1)({name:"onProgressEvt",impl:async e=>{(0,l.ee)().emit("progress",e)}})},33847:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const n=i(98553),r=i(31586),s=i(409),a=i(78406),o=i(25764),l=i(99331),u=i(56519),c=i(98314),d=i(41944);class h extends a.EndableInterval{constructor(e,t,i,r=d.DefaultThrottleMs){super({name:"PullProgressObserver("+(0,n.stringify)(e)+")",callback:()=>this.onInterval(),intervalMs:r,rank:o.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=r,this.start=Date.now(),this.onInterval=(0,s.rateLimited)({name:"PullProgressObserver.onInterval",f:()=>(0,l.ending)()?this.end():(0,u.thenMap)(this.progress(),(e=>this.emit(e))),minCallDelayMs:this.throttleMs})}observe(e){return e.then((()=>this.completed()),(e=>{throw this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,c.errorToS)(e)+")",this.end(),e})),e}emit(e){(0,r.gt0)(e)&&(0,d.emitProgressEvt)({...this.ctx,pct:(0,r.pct)(e,this.total),elapsedMs:Date.now()-this.start,done:this.done})}completed(){this.done=!0,this.ended||(this.emit(this.total),this.end())}}t.PullProgressObserver=h},38156:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const n=i(31586),r=i(41944);t.PushProgressObserver=class{constructor(e,t){this.context=e,this.total=t,this.start=Date.now()}toJSON(){}incrProgress(e=1){this.onProgress(e+(this.current??0))}onProgress(e){this.current=(e??this.current??0)+1,(0,n.gte)(this.current,this.total)&&(this.done=!0),this.emit()}completed(){this.done=!0,this.current=this.total,this.emit()}emit(){(0,r.emitProgressEvt)({...this.context,pct:(0,n.pct)(this.current,this.total),elapsedMs:Date.now()-this.start,done:this.done})}}},24399:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const n=i(58587),r=i(19851),s=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),w=i(56519),S=i(31562),b=i(84777),P=i(34102),M=i(43334),_=i(28874),E=i(63870),x="{ready}",T=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=D,(0,o.later)((()=>(0,P.ee)().on("clearCache",(()=>k.instance.prior()?.clearMockResults()))));class k extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),g.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new n.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",_.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${x}"}`,...(0,s.mapNotBlankOr)(_.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:x,fail:"Error",exitCommand:"exit",maxProcs:_.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,E.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),_.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(_.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new n.Task(e,((i,n,r)=>t((0,l.map)(i,(t=>(0,p.stripPrefix)(t,e))),n,r)))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,T),((e,t,i)=>({stdout:e,stderr:t,passed:i})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=k,k.instance=(0,r.lazy)((()=>{if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return new k})),t.checkPowerShell_=async function(){const e=k.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,E.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const n=i(50989);t.AggregateTypes=(0,n.strEnum)("union","intersection")},71988:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const n=i(50989);t.AssetFileSortCriteria=(0,n.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const n=i(22573),r=i(38639),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toBoolean})}}t.BooleanSetting=a},90536:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const n=i(22573),r=i(31586),s=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const n=i(22573),r=i(31586),s=i(97790),a=i(83179);class o extends a.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(n.notBlank).flatMap(r.toInt).map((t=>(0,r.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,r.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},10546:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const n=i(50989);t.ColorDistanceFunctions=(0,n.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const n=i(36507),r=i(22573),s=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,s.defer)((()=>(0,a.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,r.blank)(t)||(0,n.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,r.blank)(t)?void 0:(0,n.Cron)(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const n=i(70488),r=i(91655),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration})}get valueOrDefault(){return(0,n.decodeDuration)(super.valueOrDefault)}get value(){return(0,n.decodeDuration)(super.value)}set value(e){super.userValue=(0,n.decodeDuration)(e)}get humanValue(){return(0,r.fmtFullDuration)(this.value)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,n.decodeDuration)(e)}}t.DurationSetting=a;class o extends s.Setting{constructor(e){super({...e,toEnv:n.encodeDuration,fromEnv:n.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,n.decodeDuration)(this.defaultValue)}get fileValue(){return(0,n.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},9945:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const n=i(22573),r=i(31586),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.FloatSetting=a},69589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.forceContextOrSetting=t.pickForceContext=void 0;const n=i(38639),r=i(68708),s=i(50989),a=i(76740),o=i(28874),l=(0,s.strEnum)("forceSync","forceFilters","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair");t.pickForceContext=function(e){return(0,r.pick)(e,...l.values)},t.forceContextOrSetting=function(e){const t={...(0,r.pick)(e??{},"retries","halt","path"),...(0,r.fromEntries)(l.values.map((t=>[t,e?.[t]??(0,n.isTrue)(o.Settings[t]?.valueOrDefault)])))};return t.retries??(t.retries=0),t.halt??(t.halt=new a.Abortable),t}},74589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const n=i(22573),r=i(31586),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt})}}t.IntegerSetting=a},4175:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disableExternalNetworkRequests=t.setQuickSyncMode=t.setStrictDeduping=t.disableAllFilters=t.handleDeprecatedSettings=t.handleMetaSettings=void 0;const n=i(19851),r=i(22573),s=i(38639),a=i(42659),o=i(68708),l=i(51926),u=i(50213),c=i(55939),d=i(10546),h=i(67958),f=i(55948),m=i(28874),p=i(80496),g=(0,n.lazy)((()=>(0,u.mkLogger)("settings.MetaSettings")));function y(e,t){return m.Settings[e].value??t.find((t=>t.name===e))?.value??m.Settings[e].defaultValue}function v(){m.Settings.respectFileExtensions.envValue=!1,m.Settings.requireMakeModel.envValue=!1,m.Settings.rejectRatingsLessThan.envValue=-100,m.Settings.minImageDimension.envValue=0,m.Settings.minVideoDimension.envValue=0,m.Settings.minVideoDurationSec.envValue=0,m.Settings.maxVideoDurationSec.envValue=0,m.Settings.minAssetFileSizeBytes.envValue=0,m.Settings.maxAssetFileSizeBytes.envValue=0,m.Settings.validateJpegImages.envValue=!1,m.Settings.validateRawImages.envValue=!1,m.Settings.validateVideos.envValue=!1}function w(){m.Settings.strictDeduping.envValue=!0,m.Settings.useImageHashes.envValue=!0,m.Settings.minExposureSettingsCoeffPct.envValue=98,m.Settings.minImageCoeffPct.envValue=95,m.Settings.imageHashFuzzyDateDelta.envValue=1,m.Settings.imageHashDifferentMimetypesDelta.envValue=-10,m.Settings.imageHashGreyscaleDelta.envValue=1}t.handleMetaSettings=function(e){M(m.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&v(),y("strictDeduping",e)&&w(),(y("optOut",e)||y("noNetwork",e))&&_()},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(m.Settings.scanMyPictures.value)){m.Settings.scanMyPictures.unset();const e=await(0,c.picturesDir)();g().info("Upgrading setting scanMyPictures to scanPaths",{priorValues:m.Settings.scanPaths.values,newPath:e}),m.Settings.scanPaths.push(e)}{const e=m.Settings.assetSubdirectoryDatestampFormat.value;if(m.Settings.assetSubdirectoryDatestampFormat.unset(),(0,r.blank)(m.Settings.assetPathnameFormat.value)&&(0,r.notBlank)(e)){const t=(0,l.ensureSuffix)(e,"/")+"BASE";g().info("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),m.Settings.assetPathnameFormat.value=t}}if(m.Settings.dbBackupIntervalMinutes.hasValue()&&!m.Settings.dbBackupIntervalMs.hasValue()){const e=m.Settings.dbBackupIntervalMinutes.valueOrDefault*a.minuteMs;g().info("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:e}),m.Settings.dbBackupIntervalMs.value=e}if(m.Settings.siblingInferenceBasenameCoeff.hasValue()&&!m.Settings.siblingInferenceBasenameCoeffPct.hasValue()){const e=Math.round(100*m.Settings.siblingInferenceBasenameCoeff.valueOrDefault);g().info("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:e}),m.Settings.siblingInferenceBasenameCoeffPct.value=e}if(m.Settings.enableSiblingInference.hasValue()&&!m.Settings.siblingInference.hasValue()){const e=m.Settings.enableSiblingInference.valueOrDefault?m.Settings.siblingInference.valueOrDefault:p.TagInferenceSettingValues.never;g().info("Upgrading setting enableSiblingInference to siblingInference",{newValue:e}),m.Settings.siblingInference.value=e}},t.disableAllFilters=v,t.setStrictDeduping=w;const S=[m.Settings.validateJpegImages,m.Settings.validateRawImages,m.Settings.validateVideos,m.Settings.transcodeVideos,m.Settings.previewMinimized,m.Settings.previewProgressive,m.Settings.previewSharpen,m.Settings.useImageHashes,m.Settings.enableSiblingInference],b={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},P={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function M(e){for(const t of S)e?t.tmpValueIfUnset=!1:t.tmpValue=void 0;const t=e?P:b;for(const[e,i]of(0,o.entries)(t))m.Settings[e].defaultValue=i;m.Settings.dominantColorPixels.defaultValue=e?256:f.DominantColorPixelsDefault,m.Settings.dominantColorKmeansRuns.defaultValue=e?0:h.DominantColorKmeansRunsDefault,m.Settings.dominantColorDeltaE.defaultValue=e?d.ColorDistanceFunctions.cie76:d.ColorDistanceFunctions.ciede2000}function _(){m.Settings.autoUpdateCheck.defaultValue=!1,m.Settings.allowUserAgent.defaultValue=!1,m.Settings.reportErrors.defaultValue=!1,m.Settings.autoRefreshLicense.defaultValue=!1,m.Settings.noNetwork.defaultValue=!0}t.setQuickSyncMode=M,t.disableExternalNetworkRequests=_},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const n=i(22573),r=i(53265),s=i(87652);class a extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,n.blank)(e)?void 0:(0,r.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=a},23561:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const n=i(22573),r=i(31586),s=i(83179);class a extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:n.notBlankToS,fromEnv:r.toFloat})}}t.OptionalFloatSetting=a},69005:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const n=i(22573),r=i(31586),s=i(83179);class a extends s.Setting{constructor(e){super({...e,toEnv:n.notBlankToS,fromEnv:r.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const n=i(83179);class r extends n.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=r},28283:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const n=i(51926),r=i(83556);t.nameFromEnv=function(e){return(0,r.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,n.ensurePrefix)((0,r.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,i){var n,r,s=this&&this.__classPrivateFieldGet||function(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const a=i(19851),o=i(40958),l=i(79666),u=i(50357),c=i(57924),d=i(98553),h=i(55835),f=i(68708),m=i(39926),p=i(46891),g=i(42279),y=i(59455),v=i(40583),w=i(81168),S=i(44198),b=i(96706),P=i(34102),M=i(28283),_=i(81075),E=i(98778),x=i(10357);t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t},t.Setting=class{constructor(e){n.add(this),this.opts=e,this._envValue=(0,a.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,n,"m",r).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?s(this,n,"m",r).call(this,e??t)+": "+i:null==this.fromEnv(e)?s(this,n,"m",r).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const i=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=i)return i}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,o.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const i=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,o.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,M.envFromName)(e),this._keys=(0,o.uniq)([...this._names.map(M.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return _.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,g.tot)(this.optsOverrides.defaultValue)??(0,g.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,g.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??(0,S.env)(),n=t??this.value;return null!=n&&(i[this.key]=this.toEnv(n)),null==e&&b.caseInsensitiveEnv.unset(),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??(0,S.env)(),n=this.toEnvValue(t);return null!=n&&(i[this.key]=n,null==e&&b.caseInsensitiveEnv.unset()),i}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const i of t.delete(e)??[])delete process.env[i];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],x.WrapComments);function i(e,i){(0,o.isEmpty)(i)||t.push(...(0,w.wrap)(["",(1===i.length?e:(0,p.pluralize)(e))+": "+(0,c.orList)(i.map((e=>(0,d.stringify)(e))))],x.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,f.entries)(this.addToJSON())){const n=Array.isArray(i)?(0,c.orList)(i.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(i);t.push(...(0,w.wrap)(["",e+": "+n],x.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,E.wrapTomlToLines)({lines:e,wrap:x.WrapComments,prepend:["Example value:"],key:this.name,value:(0,g.tot)(this.exampleValue)}),(0,E.wrapTomlToLines)({lines:e,wrap:x.WrapComments,prepend:["Default value:"],key:this.name,value:(0,g.tot)(this.defaultValue)}),(0,E.wrapTomlToLines)({lines:e,key:this.name,value:(0,g.tot)(this.fileValue)}),e}},n=new WeakSet,r=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const n=i(50989);t.SettingCategories=(0,n.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const n=i(58587),r=i(51168),s=i(76760),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(42659),d=i(73722),h=i(68708),f=i(50989),m=i(12168),p=i(54993),g=i(37975),y=i(9092),v=i(40583),w=i(79840),S=i(7282),b=i(12801),P=i(4328),M=i(70488),_=i(84248),E=i(5531),x=i(99315),T=i(34365),D=i(34580),k=i(96706),C=i(50274),F=i(33866),O=i(52086),I=i(48584),L=i(45969),A=i(43334),R=i(24540),N=i(70379),B=i(71300),z=i(33209),j=i(48987),V=i(68268),W=i(61208),H=i(99023),U=i(30577),q=i(1485),G=i(19861),$=i(55111),J=i(30933),K=i(22859),Z=i(71988),X=i(38483),Y=i(90536),Q=i(75164),ee=i(10546),te=i(90967),ie=i(67958),ne=i(55948),re=i(57039),se=i(9945),ae=i(74589),oe=i(844),le=i(96093),ue=i(23561),ce=i(69005),de=i(87652),he=i(81075),fe=i(58305),me=i(57571),pe=i(72564),ge=i(80372),ye=i(80496);t.isProd=(0,a.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new X.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new ge.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new X.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new X.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new ge.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new re.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new re.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new re.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new ae.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new ge.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new ge.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new X.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,g.noColor)()}),logContextLimit:new ae.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new X.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new ge.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new re.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new re.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>G.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>q.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:q.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>q.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new X.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new re.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>A.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new X.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new re.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new ge.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new ae.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new X.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new ge.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new X.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,L.isDocker)()}),cspReportOnly:new X.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new X.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new pe.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:$.HelmetPlugins}),shortProcessNames:new X.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!A.isElectron}),minDelayBetweenSpawnMs:new re.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,M.encodeDuration)((new n.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new re.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new re.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new re.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>A.isMac?"100ms":A.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new re.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new ge.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new re.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new ae.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new ae.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new ae.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new X.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:_.AutoVacuumModes,defaultValue:_.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:E.CheckpointTypes,defaultValue:E.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:x.RepairModes,defaultValue:x.RepairModes.dump}),maxBusyDbMs:new re.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new re.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new Y.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new ae.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new X.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new X.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new X.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,L.isDocker)()}),skipHealthCheckIds:new pe.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:F.HealthCheckIds}),ffmpegHwaccel:new ge.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new X.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new ae.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new X.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new X.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>A.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new ge.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new ge.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new ae.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new X.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new X.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:U.UpdateChannels}),autoUpdateCheck:new X.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new X.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new X.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,D.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new X.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new ae.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new ae.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new ae.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new X.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new X.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new ge.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,R.isRaspberryPi)()}),taskTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new X.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new X.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new ge.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new ge.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":r.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new X.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new X.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new X.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new ae.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,J.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new X.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:C.SidecarExts,defaultValue:C.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new X.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:K.AggregateTypes.intersection,strEnum:K.AggregateTypes}),useImageHashes:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new X.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new ge.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new ae.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ne.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:ie.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new X.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new X.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,J.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:O.CropStrategies.attention,strEnum:O.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new X.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,o.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new ae.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(A.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new X.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new pe.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Z.AssetFileSortCriteria}),variantSortCriteriaPower:new Y.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new X.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>z.DefaultIncludedPreviewTags}),disableAllFilters:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new X.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new ae.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new ae.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new ae.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:I.SharpFailOns.truncated,strEnum:I.SharpFailOns}),validateRawImages:new X.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new X.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.DefaultCapturedAtTagsConst}),useMWG:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:B.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>j.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new ae.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:oe.MinValidYear}),maxValidFutureMs:new re.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new X.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:N.DateTagFormats.ym,strEnum:N.DateTagFormats}),tagDateFromStat:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:V.KeywordReparentingStrategies.move,strEnum:V.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new X.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:H.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new ge.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,L.isDocker)()}),tagDisplayNameFSLabels:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new X.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new re.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new X.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new X.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,i]of(0,h.entries)(t.Settings))i._setName(e);function be(e){const i=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,L.isDocker)()&&i.unshift("/opt/photostructure/tools/bin"),i.push(...t.Settings.toolPaths.valueOrDefault),(0,o.uniq)(i).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,a.lazy)((()=>be((0,k.getEnv)("PATH")))),t.allSettings=(0,a.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,a.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,a.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const Me=(0,a.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e}));t.getSettingByNameOrKey=function(e){return Me().get((0,p.toS)(e).toLowerCase())},t.ciSettings=(0,a.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const n=i(19851),r=i(31586),s=i(7282),a=i(49776),o=i(46292),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(96706),f=i(83278),m=i(92234),p=i(45969),g=i(60865),y=i(30933),v=i(15674),w=i(28874);t.setSettingsDefaults=(0,n.lazy)((()=>{w.Settings.configDir.opts.defaultValue=o.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=a.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,p.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=g.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,r.sigFigs)(50/(0,y.cpuCount)(),2)}))},2858:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeEnv=t.nukeSettings=t.clearSettings=t.clearLibraryDirSetting=t.importFileSettings_=t._readSettings=t.writeLibrarySettings_=t.readLibrarySettings=t.writeAllSettings_=t.writeSystemSettings_=t.versionForSettings=t._libraryHasSettings=t.libraryHasSettings=t.maybeUpgradeLibrarySettings=t.maybeUpgradeSystemSettings=t.librarySettingsVersion=t.systemSettingsVersion=t.savedLibraryDir=t.envOrSavedLibraryDir=t.readSystemSettings=t.readSettings=t.librarySettingsFile=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(22573),o=i(42659),l=i(41400),u=i(50357),c=i(26905),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),w=i(50213),S=i(81168),b=i(83556),P=i(87290),M=i(98314),_=i(34102),E=i(83278),x=i(95696),T=i(60865),D=i(4175),k=i(83179),C=i(81075),F=i(28874),O=i(41692),I=i(84438),L=i(32707),A=i(6707),R=i(98778),N=i(55018),B=i(10357),z=(0,n.lazy)((()=>(0,w.mkLogger)("settings.SettingsIO")));function j(e){return(0,P.libraryDataDirPosixFile)(e)?.join(I.SettingsToml)}async function V(e=(0,L.systemSettingsFile)()){if(null!=e)return Y(E.BaseFile.for(e))}async function W(){try{return(0,a.toNotBlank)((await(0,A.readTomlFile_)((0,L.systemSettingsFile)()))?.[F.Settings.libraryDir.name])}catch{return}}function H(e){return(0,A.readTomlFile_)(e).then((e=>e?.version),(()=>{}))}function U(){return H((0,L.systemSettingsFile)())}function q(e){return H(j(e))}function G(){t.libraryHasSettings.refresh()}function $(e){const t=j(e);return z().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,level:"info",meta:{libraryDir:e,settings:F.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function J(e,i){if(null==e)return void z().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const n=await e.clear().isNonEmpty(),r=n?e.wip():e;if(await async function(e,i){const n=[(0,g.padding)("#",80)];n.push(...ie("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),n.push(...(0,R.stringifyToml)({version:(0,t.versionForSettings)()})),n.push("","");let r="";for(const e of i){const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==r&&(r=t,n.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#","","")),n.push(...e.toTomlLines()),n.push("","")}await e.writeText_("\n"+n.map(y.trimRight).join("\n")+"\n\n"),(0,_.ee)().emitDebounced("settingsChanged")}(r,i),z().info("writeToml(): wrote settings",{dest:r,file:e,nonDefaults:(0,k.settingsToObj)(i),wip:n}),n){const t=await(0,A.readTomlFile_)(r),i=await(0,A.readTomlFile_)(e);(0,u.eql)(t,i)?(z().info("Equivalent contents",{dest:r,file:e,a:t,b:i}),await r.unlink()):(z().info("Archiving prior, different contents",{dest:r,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await r.unwip_())}}async function K(e=(0,L.systemSettingsFile)()){const t=x.PosixFile.forMaybe(e);return null!=t&&await J(t,(0,F.persistedSystemSettings)()),t}function Z(e){return Y(j(e))}async function X(e){await(0,P.setupLibraryDataDir_)((0,a.firstNotBlank)(e,F.Settings.libraryDir.value));const i=j(e);return z().info("writeLibrarySettings()",{file:i}),null!=i&&(await J(i,(0,F.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function Y(e){if(null==e)return[];const t=z().addContext(".importFileSettings("+e?.nativePath+")");try{const i=await Q(e);return(0,r.isNotEmpty)(i.warnings)&&t.warn("Problems during import",i.warnings),i.settings}catch(e){return t.error("Cannot read: "+(0,M.errorToS)(e)),[]}}async function Q(e){const t=z().addContext(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const n=await(0,A.readTomlFile_)(e);if(null==n)return{settings:[],warnings:["No settings found"]};const s=[],a=(0,r.compact)((0,p.entries)(n).map((([e,t])=>{if("version"===e)return;const i=(0,F.getSettingByNameOrKey)(e);if(null==i)s.push(`Failed to import "${e}"${(0,m.mapOr)((0,F.ciSettings)().lookupNearest(e),(e=>`: did you mean "${e.key}"?`),"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;s.push(e)}})));return t.info("loaded",{settings:(0,k.settingsToObj)(a),warnings:(0,r.toNotEmpty)(s)}),await(0,D.handleDeprecatedSettings)(),(0,D.handleMetaSettings)(a),{settings:a,warnings:s}}t.librarySettingsFile=j,t.readSettings=(0,n.lazy)((async()=>{await V(),(0,t.libraryHasSettings)()&&await Z()}),o.minuteMs),t.readSystemSettings=V,t.envOrSavedLibraryDir=async function(){return F.Settings.libraryDir.valueOrDefault??W()},t.savedLibraryDir=W,t.systemSettingsVersion=U,t.librarySettingsVersion=q,t.maybeUpgradeSystemSettings=async function(){(0,t.versionForSettings)()!==await U()&&await K()},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await q()&&await X()},t.libraryHasSettings=(0,n.lazy)((()=>$())),t.libraryHasSettings.unset=()=>{z().error("libraryHasSettings.unset() is invalid",(0,c.shortStack)())},(0,l.later)((()=>{(0,_.ee)().on("clearCache",G),(0,_.ee)().on("settingsChanged",G),F.Settings.libraryDir.watchLater(G)})),t._libraryHasSettings=$,t.versionForSettings=(0,n.lazy)((()=>(0,T.baseVersion)())),t.writeSystemSettings_=K,t.writeAllSettings_=function(e){return J(x.PosixFile.for(e),(0,F.persistedSettings)())},t.readLibrarySettings=Z,t.writeLibrarySettings_=X,t._readSettings=Y,t.importFileSettings_=Q;const ee=(0,n.lazy)((()=>new Set([F.Settings.noNetwork,F.Settings.httpPort,F.Settings.license,F.Settings.logStdout,F.Settings.logLevel].map((e=>e.key)))));function te(){for(const e of(0,p.values)(F.Settings))ee().has(e.key)||e.unset();(0,_.ee)().emit("settingsChanged")}function ie(...e){return(0,d.flatten)(e.map((e=>(0,S.wrap)(e,B.WrapComments))))}t.clearLibraryDirSetting=async function(){await V(),F.Settings.libraryDir.unset(),await K()},t.clearSettings=te,t.nukeSettings=async function(){te(),await(x.PosixFile.forMaybe((0,L.systemSettingsFile)())?.unlink("trace")),await(x.PosixFile.forMaybe(j())?.unlink("trace")),(0,_.ee)().emit("clearCache"),O.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...ie("",`Welcome to PhotoStructure! These are the settings for version ${T.versionMajorMinor}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure, but requires extra configuration. See https://photostructure.com/faq/environment-variables/#PS_ENV_FILE for details.')),i.push("",""),i.push(...ie("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...C.SystemCategories]).map((e=>"* System."+e)),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...C.LibraryCategories]).map((e=>"* Library."+e)),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...ie("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory.","","This is an advanced setting--we recommend using the default value, if possible.","","If the PS_CONFIG_DIR environment variable is not set, the default is specific to your operating system:","",'- On Docker: "/ps/config" if that bind-mount exists, otherwise "/ps/library/.photostructure/docker-config".',"",'- On Linux: firstNonBlank([$XDG_DATA_HOME, $XDG_CONFIG_HOME, "$HOME/.config"]) + "/PhotoStructure"',"",'- On macOS: "$HOME/Library/Application Support/PhotoStructure"',"",'- On Windows: "$APPDATA/PhotoStructure" ($APPDATA is normally set to $HOME/AppData/Roaming)')),i.push("",""),i.push(...ie("-----------","PS_ENV_FILE","-----------","","If set, PhotoStructure will attempt to read the .env file specified by this environment variable.","","This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","See https://photostructure.com/faq/environment-variables/#alternative-coming-in-v21-support-for-env-files for details.")),i.push("","");let n="";t.forEach((e=>{const t=`${(0,S.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;t!==n&&(n=t,i.push("",(0,g.padding)("#",78),"#","# Settings for "+t+":","#",""));const s=`${e.key} or ${e.name}`,a={...e.addToJSON()};(0,r.mapNotEmpty)(e.altKeys,(e=>a.aliases=(0,h.orList)(e)));const o=(0,p.entries)(a).map((([e,t])=>`${(0,S.capitalize)((0,b.camel2snake)(e)).replace(/_+/g," ")}: ${(0,N.valueToS)(t)}`));(0,r.isNotEmpty)(o)&&o.push(""),i.push(...ie((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.","\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")})),await e.writeText_(i.map((e=>(0,y.trimRight)(e))).join("\n"))}},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const n=i(76760),r=i(40958),s=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}t._join=d;function h(e){return(0,o.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,r.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",n.delimiter])if(t.includes(e))return(0,r.compactBlankish)(t.split(e));return[t]}}(e),r.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,r.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,r.isEmpty)(e)||(this.value=this.toValidValues((0,r.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,r.isEmpty)(this.values)}isNotEmpty(){return(0,r.isNotEmpty)(this.values)}toNotEmpty(){return(0,r.toNotEmpty)((0,r.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const n=i(83179);class r extends n.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=r},72564:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const n=i(40958),r=i(98553),s=i(55835),a=i(58305);class o extends a.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,r.stringify)((0,n.uniq)(e)))),fromEnv:t=>{return i=t,r=e.strEnum,(0,n.compact)((0,a.splitStringArray)(i)?.map((e=>r.getCI(e))));var i,r},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=o},80372:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const n=i(22573),r=i(81168),s=i(83179);class a extends s.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,n.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,r.trimQuotes)(e)}t.StringSetting=a},32707:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const n=i(76760),r=i(55835),s=i(46292),a=i(84438);t.systemSettingsFile=function(){return(0,r.map)((0,s.configDir)(),(e=>(0,n.join)(e,a.SettingsToml)))}},80496:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const n=i(50989);t.TagInferenceSettingValues=(0,n.strEnum)("never","always","auto")},6707:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const n=i(90858),r=i(44652),s=i(22573),a=i(76850),o=i(50213),l=i(81168),u=i(84542),c=i(17217),d=i(68284),h=i(98778);function f(e){return t=(0,a.debom)(e),(0,s.blank)(t)?void 0:(0,n.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,r.readFileSync)(t)):void 0}catch(e){return void(0,o.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,r.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,r.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const n=i(22573),r=i(96249),s=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,n.blank)(e))throw new Error("kvToToml(): Blank key");const r=e+" = "+(0,s.stringifyPretty)(t);return(0,n.blank)(i?.prefix)?[r]:(0,o.wrap)(r.split("\n"),i)}t.stringifyToml=function(e){return(0,r.flatten)((0,a.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,n.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},55018:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=void 0;const n=i(98553);t.valueToS=function(e){return(0,n.stringify)(e,void 0,2)}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},94678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractBitrateKbps=void 0;const n=i(54993),r=i(97352);t.extractBitrateKbps=function(e){for(const t of["AvgBitrate","MaxDataRate"]){const i=a(e[t]);if(null!=i)return i}};const s=[{pat:"mb/s",fac:1024},{pat:"mbps",fac:1024},{pat:"kb/s",fac:1},{pat:"kbps",fac:1}];function a(e){const t=(0,r.extractFloat)(e);if(null==t)return;const i=(0,n.toS)(e).toLowerCase();for(const e of s)if(i.includes(e.pat))return t*e.fac}},65162:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const n=i(4001),r=i(81168);t.bname=function(e,t=!0){let i=(0,r.isString)(e)?e:e.name;return t&&(i=(0,n.stripCopySuffixFromName)(i)),i=(0,r.trimLeftPadding)((0,n.stripDSC)(i)),i.toLowerCase().normalize()}},28544:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.capturedAtFromStat=t.capturedAtFromPath=t.capturedAtFromBasename=t.capturedAtFromTags=t.extractCapturedAt=t.bestCapturedAt=t.CapturedAt=t.isCapturedAtJson=t.capturedAtSrcFromStat=t.capturedAtSrcFromTags=void 0;const n=i(77988),r=i(19851),s=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(54993),p=i(48884),g=i(50213),y=i(7282),v=i(81168),w=i(76596),S=i(79842),b=i(66649),P=i(21330),M=i(98725),_=i(928),E=i(54261),x=i(89724),T=i(17415),D=i(88600),k=i(51275),C=i(29882),F=i(17217),O=i(68284),I=i(57902),L=i(28874),A=i(65162),R=i(71300),N=i(14036),B=i(61424),z=(0,r.lazy)((()=>(0,g.mkLogger)("tags.CapturedAt")));function j(e){return(0,m.toS)(e).toLowerCase().includes("tags")}function V(e){return(e=(0,m.toS)(e).toLowerCase()).includes("stat")&&!e.includes("+")}function W(e){return null!=e&&(0,f.isObject)(e)&&(0,o.notBlank)(e.nativePath)&&(0,S.isDated)(e.date)&&(0,o.notBlank)(e.src)}t.capturedAtSrcFromTags=j,t.capturedAtSrcFromStat=V,t.isCapturedAtJson=W;class H{static fromAssetFile(e){return(0,d.map)((0,x.localToDateTime)(e.capturedAtLocal,e.capturedAtOffset),(t=>H.for({nativePath:e.nativePath,date:t,src:e.capturedAtSrc,mtime:e.mtime,precisionMs:e.capturedAtPrecisionMs,offset:e.capturedAtOffset,local:e.capturedAtLocal})))}static for(e){return e instanceof H?e:W(e)?new H(e):void 0}constructor(e){var t;this.nativePath=(0,F.toNativePath_)(e.nativePath),this.date=e.date,this.src=(t=e.src,(0,y.isTest)()?t.replace(/SubSec/,"").replace(/ \(.+\)/,""):t),this.local=(0,h.toGt0)(e.local)??(0,x.datedToLocal)(this.date),this.offset=e.offset??(0,P.datedToOffsetMinutes)(this.date);let i=(0===e.precisionMs?void 0:e.precisionMs)??(0,S.datedToPrecisionMs)(this.date);V(this.src)&&(i=Math.max(L.Settings.minCapturedAtPrecisionStat.valueOrDefault,i)),this.precisionMs=i,this.mtime=(0,b.datedToMillis)(e.mtime)??(0,O.statSync)(this.nativePath)?.mtimeMs}toJSON(){return{_ctor:H.name,...(0,f.pick)(this,"nativePath","date","src","local","offset","precisionMs","mtime")}}static fromJSON(e){const t=(0,M.parseDated)({input:e.date,defaultZone:(0,d.map)(e.offset,T.fmtOffsetMinutes)});return null==t?void 0:new H({...e,date:t})}spread(e){return new H({...this.toJSON(),...e})}toISOString(){return(0,P.datedToISO)(this.date)}toExifString(){return(0,P.datedToEXIF)(this.date)}exifOffsetMinutes(){return null==this.offset?void 0:(0,T.fmtOffsetMinutes)(this.offset)}get isFromTags(){return j(this.src)}get isInferred(){return!j(this.src)&&!V(this.src)}get isFuzzy(){const e=this.local;return!this.isFromTags||(0,x.localIsFuzzy)(e)}get rawValue(){return this.date?.rawValue}get localSec(){return Math.floor(this.local/100)}toString(){return(0,c.stringify)({nativePath:this.nativePath,date:this.toISOString(),src:this.src})}toISOStringWithPrecision(){return(0,P.datedToISO)(this.date,!0,this.precisionMs)+(null==this.precisionMs?"":" (±"+(0,w.fmtMs)(this.precisionMs)+")")}hasTz(){return(0,k.hasZone)(this.date)||null!=this.offset}isUTC(){return 0===this.offset}hasTime(){return(0,E.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,_.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}get isValid(){return(0,D.isValidDate)(this.date)}get zoneName(){return(0,n.offsetMinutesToZoneName)(this.offset)??(0,k.getZoneName)(this.date)}toAssetFileFields(){const e=this.local;return null==e||null==this.mtime?void 0:{nativePath:this.nativePath,mtime:this.mtime,capturedAtLocal:e,capturedAtOffset:this.offset,capturedAtPrecisionMs:this.precisionMs,capturedAtSrc:this.src}}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,OffsetTime:(0,d.map)(this.offset,T.fmtOffsetMinutes)}}fuzzyPrecisionMs(){return(this.isFuzzy?L.Settings.fuzzyDatePrecisionCoeff.valueOrDefault:1)*(this.precisionMs??l.secondMs)}localBoundaries(e){const t=(e?.delta??0)+this.fuzzyPrecisionMs(),i=(0,S.datedToStartDateTime)(this.date)??(0,S.datedToDateTime)(this.date);if(null!=i)return{start:(0,x.datedToLocal)(i.minus(t)),end:(0,x.datedToLocal)(i.plus(t))};z().warn("localBoundaries() failed",{date:this.date,args:e,d:i,path:this.nativePath})}overlaps(e){if(null==e)return!1;if(this.local===e.local)return!0;const t=(0,N.extMimetype)(this.nativePath)===(0,N.extMimetype)(e.nativePath)?0:L.Settings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),n=Math.max(t,e.fuzzyPrecisionMs());return z().tap({level:"trace",msg:"overlaps()",result:this.local===e.local||(0,S.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:n}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:n}})}}function U(e,t){if(null==e)return;const i=(0,s.compact)([e.capturedAt,e?.inferred?.capturedAt].map((e=>H.for(e))));for(const n of t){let t=e[n],r=n;if((0,D.isValidDate)(t)){if((0,T.isValidZone)(e.tz)&&(!(0,k.hasZone)(t)||R.OverrideUTCZoneTags.includes(r))){t=(0,P.setZone)(t,e.tz)??t;const i=(0,o.blank)(e.tzSource)?"":" from "+(0,v.stripPrefix)(e.tzSource,"from ");r+=` (TZ ${e.tz}${i})`}i.push({localSec:(0,x.datedToLocalSec)(t),date:t,src:r,precisionMs:(0,S.datedToPrecisionMs)(t),rawValue:e[n]?.rawValue})}}const n=(0,p.leastBy)(i,(e=>(0,S.datedToStartTs)(e.date)));if(null==n)return;const r=i.filter((e=>(0,u.eql)(e.date,n.date)||e.precisionMs<=n.precisionMs&&(0,S.datedOverlap)({a:e.date,b:n.date,aPrecisionMs:e.precisionMs,bPrecisionMs:n.precisionMs}))),a=(0,p.leastBy)(r,(e=>[Math.floor(e.localSec/1e6),(0,k.hasZone)(e.date)?0:1,e.precisionMs,-1*(e.rawValue?.length??0),e.src]));return z().debug("capturedAtFromTags()",{least:n,overlapsWithLeast:r,earliest:a}),a}function q(e,t){if(L.Settings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.uniq)([(0,A.bname)(e,!0),(0,A.bname)(e,!1)])){const e=(0,M.parseDated)({input:i,defaultZone:t?.tz});if(null!=e)return{date:e,precisionMs:(0,p.max)([(0,S.datedToPrecisionMs)(e),l.secondMs])}}}function G(e){if(L.Settings.usePathsToInferDates.valueOrDefault)return{date:(0,M.extractDateFromPath)(e.pathsForDateParsing)}}async function $(e){if(L.Settings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=H,t.bestCapturedAt=function(e){const t=(0,a.sortBy)(e,(e=>-(e?.mtime??0)));return t.find((e=>e.src.includes("tags")))??t.find((e=>e.src.includes("stat+bname")))??t.find((e=>e.src.includes("stat+path")))??t.find((e=>e.src.includes("bname")))??t.find((e=>e.src.includes("path")))??t.find((e=>e.src.includes("siblings")))??t.find((e=>e.src.includes("stat")))??t[0]},t.extractCapturedAt=async function(e,t,i=!1){const n=await e.mtimeMs();function r(t,i){return W(i)?H.for(i):null!=i&&null!=i.date&&(0,D.isValidDate)(i.date)?H.for({nativePath:e.nativePath,date:i.date,local:(0,x.datedToLocal)(i.date),src:(0,v.uniqPath)([t,i.src]),mtime:n,precisionMs:i.precisionMs,offset:(0,P.datedToOffsetMinutes)(i.date)}):void 0}const s=function(e,t){return null==e||t||!L.Settings.usePathsToInferDates.valueOrDefault||!L.Settings.useLibraryDirsToInferDates.valueOrDefault&&(0,C.containedByNativePath)({ancestor:L.Settings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(e,i),a=r("tags",U(t,L.Settings.capturedAtTags.values))??(i?void 0:r("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??r("tags",U(t,L.Settings.capturedAtTagsFallback.values))??(s?void 0:r("stat+bname",await(0,B.extractStatBname)(e)))??(s?void 0:r("stat+path",await(0,B.extractStatPathTime)(e)))??(i?void 0:r("siblings",await(0,B.inferCapturedAtFromSiblings)(e)))??(s?void 0:r("bname",q(e,t)))??(s?void 0:r("path",G(e)))??(L.Settings.useStatToInferDates.valueOrDefault?r("stat",await $(e)):void 0);return z().tap({level:I.LogLevels.debug,msg:"extractCapturedAt()",result:a})},t.capturedAtFromTags=function(e){return U(e,L.Settings.capturedAtTags.values)},t.capturedAtFromBasename=q,t.capturedAtFromPath=G,t.capturedAtFromStat=$},70379:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const n=i(50989);t.DateTagFormats=(0,n.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extactDuration=t.extractDurationMs=t.extractDurationSec=void 0;const n=i(31586),r=i(97352),s=i(95696),a=i(47783),o=i(16170);function l(e){if(null!=e&&(0,o.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,n.toGt0f)(e[t]);if(null!=i)return i}}t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,r.mapGt0f)(l(e),(e=>Math.round(1e3*e)))},t.extactDuration=async function(e){if(null==e)return;const t=s.PosixFile.for(e);return l(await(0,a.readRawTags)(t,!1))}},72180:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=void 0,t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseTags=t._readRawTags=t.readRawTags=t.writeTags_=t.writeTagDest=t.writeTagArgs=t.deleteAllTags_=t.overwriteTags_=t.moveOriginal=t.readRotation=t.readRawField=t.readCapturedAt=t.cachedTags=t._readTags=t.readTags=t.sidecarEql=t.IgnoredSidecarFields=t.IgnoredTypedFields=t.clearTagsCache=t.rawTagsCache=t.tagsCache=t.extractBinaryTag=t.shutdownExiftool=t.exiftoolVersionMaybe=t.exiftoolVersion_=t.exiftool=t.setExifToolProcs=t.addInstanceIdsToTags=void 0;const r=i(77988),s=n(i(76760)),a=n(i(1708)),o=i(19851),l=i(40958),u=i(22573),c=i(42659),d=i(55835),h=i(23838),f=i(68708),m=i(34666),p=i(51926),g=i(59455),y=i(54993),v=i(12168),w=i(56038),S=i(4867),b=i(36557),P=i(98247),M=i(21330),_=i(98725),E=i(23467),x=i(88561),T=i(95696),D=i(17217),k=i(16287),C=i(50213),F=i(17921),O=i(7282),I=i(88158),L=i(23560),A=i(28874),R=i(12089),N=i(81168),B=i(63870),z=i(15674),j=i(28544),V=i(43207),W=i(72180),H=i(75767),U=i(12788),q=i(80495),G=i(14036),$=i(67083),J=i(3432),K=i(28630),Z=i(15912),X=i(30748),Y=i(16170),Q=i(95141),ee=i(7330),te=i(54979),ie=i(1078),ne=i(61424),re=i(8791),se=(0,o.lazy)((()=>(0,C.mkLogger)("exiftool.ExifTool")));let ae=!1;t.addInstanceIdsToTags=function(e){ae=e},t.setExifToolProcs=function(e){return A.Settings.exiftoolProcsPerChild.envValue=e,ue()};const oe=(0,o.lazy)((()=>new b.BatchClusterObserver("ExifTool",new r.ExifTool({useMWG:A.Settings.useMWG.valueOrDefault,backfillTimezones:!1,ignoreZeroZeroLatLon:!1,inferTimezoneFromDatestamps:!1,defaultVideosToUTC:A.Settings.defaultVideosToUTC.valueOrDefault,geoTz:()=>{},...(0,b.batchClusterOptions)((0,O.isTest)()?8:(0,L.isSyncService)()?A.Settings.exiftoolProcsPerChild.value??(0,z.maxConcurrentImports)():2,"exiftool.ExifTool")})).t));function le(){const e=oe();return e.ended?oe.refresh():e}function ue(e=!1){return(0,d.map)(oe.clear(),(t=>t.end(e)))}t.exiftool=le,t.exiftoolVersion_=async function(){return(0,S.thenOrTimeoutError)({p:le().version(),timeoutMs:A.Settings.statTimeoutMs.valueOrDefault})},t.exiftoolVersionMaybe=function(){return(0,d.map)(oe.prior(),(e=>e.ended?void 0:(0,S.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,B.commandTimeoutMs)()})))},t.shutdownExiftool=ue,t.extractBinaryTag=function(e,t,i){return le().extractBinaryTag(e,t,i)},t.tagsCache=(0,o.lazy)((()=>new x.FileCache({name:"exiftool.parsed",maxSize:256,timeoutMs:c.minuteMs}))),t.rawTagsCache=(0,o.lazy)((()=>new x.FileCache({name:"exiftool.raw",maxSize:256,timeoutMs:c.minuteMs}))),t.clearTagsCache=function(){t.tagsCache.prior()?.clear(),t.rawTagsCache.prior()?.clear(),te.mimetypeCache.prior()?.clear()};async function ce(e){return(0,f.omit)(await pe(e,!1),...t.IgnoredSidecarFields)}function de(e){return null==e?void 0:(0,t._readTags)((0,D.toNativePath_)(e))}async function he(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function fe(e){const t=[];return A.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,m.gt)(await e.size(),2*v.GB)&&t.push("-api LargeFileSupport=1"),t}async function me(e,t,i){if((0,N.includesIgnoreCase)(A.Settings.sidecarTagBlocklist.values,(0,p.stripSuffix)(t,"#")))return se().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const n=i??await(0,te.readMimeType)(e),r=await e.sidecar(),s=(0,Y.isImageMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,Y.isVideoMimeType)(n)&&A.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=A.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await r.exists(),l=s||a||o;return se().tap({msg:"writeTagDest()",result:l?r:e,meta:{src:e,tagName:t,mimetype:n,writeMetadataToSidecarsIfImage:s,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}async function pe(e,i=!0){const n=T.PosixFile.for(e);if(n.isSidecar()&&(i=!1),!await n.isNonEmptyFile(128))return(0,t.rawTagsCache)().delete(n.nativePath),void se().debug("readRawTags("+n+"): invalid file, returning null.");const r=await(0,t._readRawTags)(n.nativePath);if(null==r||!i)return r;se().trace("readRawTags()",{pf:n,pickedFileTags:(0,f.pick)(r,"tz","tzSource",...A.Settings.capturedAtTags.values)});const s=[];for(const e of await n.jsonSidecars())s.push([e,(0,K.readJsonSidecar)(e,r.tz)]);for(const e of await n.existingExifSidecars())s.push([e,(0,t._readRawTags)(e.nativePath)]);const a={original:{},MIMEType:(0,u.mapNotBlank)(r.MIMEType,Y.normalizeMimetype),...r},o=[];for(const[e,i]of s){if(null==i)continue;const n=await i;if(null==n)continue;const r=(0,f.omit)(n,...t.IgnoredSidecarFields);(0,l.isNotEmpty)((0,f.values)(r))?((a.sidecars??(a.sidecars=[])).push(e.base),o.push(...(0,g.toA)(n.History)),(0,I.assignNullishFields)(a.original,(0,f.pick)(a,...(0,f.keys)(r))),(0,f.assignFields)(a,r),se().debug("readRawTags() sidecar had values",{sidecar:e.base})):se().debug("readRawTags() sidecar was empty",{sidecar:e.base})}return a.inferred=(0,$.getInferredHistoricValues)(o,e),(0,I.assignNullishFields)(a,a.inferred),a.Rotation=(0,Q.orientationToRotation)(a.Rotation),se().debug("readRawTags() final",{pf:n,inferred:a.inferred,pickedResult:(0,f.pick)(a,"tz","tzSource",...A.Settings.capturedAtTags.values)}),a}async function ge(e,t){return null==t?void 0:(0,w.time)("exiftool.parseTags:"+e,(()=>async function(e,t){try{const i=e.nativePath,n=t.MIMEType=(0,u.mapNotBlank)(t.MIMEType,Y.normalizeMimetype);if((0,u.blank)(n))return void se().debug("No mimetype for "+i);const s={...t.inferred??{},...t};if(s.inferred??(s.inferred={}),s.original??(s.original={}),A.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values]){const t=s[e];if((0,p.isString)(t)){const i=(0,_.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=i&&(se().debug("parseTags() fuzzy date",{fuzzy:i,k:e,v:t}),s[e]=i)}}const o=!await(0,ne.canInferForDir)(e.parent()),l=await(0,J.maybeInferTimezone)(e,s,o);if(se().debug("parseTags()",{tzMeta:l,skipSiblingInference:o}),null!=l?.tz){const e=s.tzSource!==r.defaultVideosToUTC&&void 0;for(const t of[...A.Settings.capturedAtTags.values,...A.Settings.capturedAtTagsFallback.values])if(!(0,W.isUtcTagName)(t)){const i=s[t];i instanceof r.ExifDateTime&&(s[t]=(0,M.setZone)(i,l.tz,{keepLocalTime:e})??i)}(0,f.assignUndefinedFields)(s.original,s,"tz","tzSource"),(0,f.assignFields)(s,l)}const c=o?(0,X.extractMakeAndModel)(s):await(0,ne.inferMakeAndModel)(e,s);c.Make!==(0,X.make)(s.Make)&&(s.original.Make=s.Make,s.inferred.Make=c.Make),c.Model!==(0,X.model)(c.Make,s.Model)&&(s.original.Model=s.Model,s.inferred.Model=c.Model),!(0,u.blank)(A.Settings.defaultCopyright.valueOrDefault)&&(0,U.isExifUnset)(s.Copyright)&&(s.Copyright=A.Settings.defaultCopyright.valueOrDefault);const d=(0,Z.extractLensMakeModel)(s),h=await(0,j.extractCapturedAt)(e,s,o);if(null==h)return void se().info("No capturedAt for "+e);!o&&h.isInferred&&(s.inferred.capturedAt=h);const m=(0,q.extractExposureSettings)(s),g=await(0,ie.extractSizeInfoFromFile)(e,s);if(null==g)return void se().info("No size info for "+i);const y={...c,mimetype:n,capturedAt:h,exposureSettings:m,...(0,re.extractTitleDescription)(s),...d,cameraId:(0,H.cameraIdFromTags)(s),imageId:(0,H.imageIdFromTags)(s),lensId:(0,H.lensIdFromLensInfo)({...d,...(0,f.pick)(s,"LensSerialNumber")}),...g,duration:(0,V.extractDurationSec)(s),tz:s.tz,rating:(0,ee.extractRating)(s)};(0,O.isTest)()&&(y.__parsedBy__=a.default.pid);const v={...s,...y};return se().debug("parsedTags",{nativePath:i,skipInference:o,...y,inferred:s.inferred,original:s.original,pickedResult:(0,f.pick)(v,"capturedAt","tz","tzSource","Make","Model")}),(0,f.definedValues)(v)}catch(e){return void se().warn("parseTags() failed",{error:e})}}(e,t)))}t.IgnoredTypedFields={Duration:void 0,MediaDuration:void 0,TrackDuration:void 0,FileFormat:void 0,FileIndex:void 0,FileName:void 0,FileNumber:void 0,FileNumberMemory:void 0,FileNumberSequence:void 0,FileSize:void 0,FileType:void 0,FileTypeExtension:void 0,FileVersion:void 0,MIMEType:void 0,SourceFile:void 0},t.IgnoredSidecarFields=["errors",...(0,f.keys)({ExifToolVersion:void 0,RAFVersion:void 0,Directory:void 0,ExifByteOrder:void 0,FileAccessDate:void 0,FileCreateDate:void 0,FileIndex2:void 0,FileInfoVersion:void 0,FileInodeChangeDate:void 0,FileModifyDate:void 0,FilePermissions:void 0}),...(0,f.keys)(t.IgnoredTypedFields)],t.sidecarEql=async function(e,t){return await(0,E.eqlAsync)(e.sha(),t.sha())||await(0,E.eqlAsync)(ce(e),ce(t))},t.readTags=de,t._readTags=(0,R.shim1)({name:"exiftool.readTags",impl:async e=>{const t=T.PosixFile.for(e);return ge(t,await pe(t))},cache:t.tagsCache}),t.cachedTags=async function(e){return(0,t.tagsCache)().get((0,D.toNativePath_)(e))},t.readCapturedAt=async function(e){return(await de(e))?.capturedAt},t.readRawField=async function(e,t){try{const i=await le().readRaw((0,D.toNativePath_)(e),["-"+t]);return(0,I.pluckCaseInsensitive)(i,t)}catch(e){return void se().info("readRawField failed",e)}},t.readRotation=async function(e){return(0,Q.extractRotation)(await pe(e,!0))},t.moveOriginal=he,t.overwriteTags_=async function(e,t){try{await(0,w.time)("exiftool.overwriteTags:"+e,(async()=>{await le().write(e.nativePath,t,await fe(e)),e.clearThisAndParent()}))}catch(i){se().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,w.time)("exiftool.deleteAllTags:"+e,(async()=>{const i=["-all="];e.eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await le().write(e.nativePath,{},i),t.clear()}))},t.writeTagArgs=fe,t.writeTagDest=me,t.writeTags_=function(e,t,i){return(0,w.time)("exiftool.writeTags:"+e,(async()=>{const n=new h.MultiMap;for(const[r,s]of(0,f.entries)(t)){const t=await me(e,r,i);n.add(t.nativePath,[r,s])}for(const[t,i]of n.entriesArray()){const n=T.PosixFile.for(t),r=(0,f.fromEntries)(i);se().info("writeTags()",{src:e,dest:t,t:r}),await le().write(n.nativePath,r,await fe(n)),A.Settings.overwriteOriginal.valueOrDefault||await he(n),n.clearThisAndParent()}}))},t.readRawTags=pe,t._readRawTags=(0,R.shim1)({name:"exiftool.readRawTags",cache:t.rawTagsCache,impl:async e=>{if(!await(0,k.nativePathIsFile)(e))return se().debug("_readRawTags(): !nativePathIsFile(), returning null.",{nativePath:e}),void(0,t.rawTagsCache)().delete(e);se().debug("_readRawTags() not cached, reading now.",{nativePath:e});const i=[...A.Settings.tagGeo.valueOrDefault?["-api","geolocation"]:[],...(0,G.isVideoExt)(s.default.extname(e))?[]:["-fast"]],n=await(0,w.time)("exiftool.read()",(()=>le().read(e,i).catch((t=>{se().warn("ExifTool failed to read",{nativePath:e,error:t})}))));if(null==n)return;se().debug("_readRawTags()",{nativePath:e,pickedTags:(0,f.pick)(n,"tz","tzSource",...A.Settings.capturedAtTags.values)}),n.MIMEType=(0,u.mapNotBlank)(n.MIMEType,Y.normalizeMimetype),n.GPSDateTime??(n.GPSDateTime=(0,P.concatDateTime)(n.GPSDateStamp,n.GPSTimeStamp));for(const e of(0,f.keys)(n)){const t=n[e];"string"==typeof t&&("0000:00:00"!==t&&"0000:00:00 00:00:00"!==t||delete n[e])}const r=(0,l.compactBlanks)([n.Error,...n.errors??[],n.Warning].map(y.toS));return(0,l.isNotEmpty)(r)&&(n.problems=r),ae&&(n.__instance=(0,F.safeUUID)()),n}}),t.parseTags=ge},75767:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uidGeoHash=t.imageIdFromTags=t.lensIdFromLensInfo=t.lensIdFromTags=t.cameraIdFromTags=t.whyExposureSettingsNotSimilar=t.findInequalFields=t.decodeExifUid=t.renderExifUidId=t.stringifyExifUid=t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(42279),h=i(54993),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const w=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function S(e){const t=null==e?[]:e.filter((([,e])=>!(0,s.blank)(e)));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function b(e){return(0,h.toS)(e).trim().replace(/\s+/g," ")}function P(e){const i=new o.MultiMap,n=[];for(const a of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(null==(r=e[a])||(0,s.blankish)(r)||(0,l.isNumber)(r)&&(0===r||1===r)||null!=t.zeroesRe.exec((0,h.toS)(r)))continue;const o=e[a],u=b(e[a]),c=(0,t.Tag2SynonymGroup)().get(a);if(null!=c){if(i.includes(c,o)||i.includes(c,u))continue;i.add(c,o)}n.push([a,(0,l.gt0)(o)?o:u])}var r;return S(n)}function M(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,s.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([M(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(M)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:n,parser:r}){const s=r(e[i]),a=r(t[i]),o=y.Settings.minExposureSettingsCoeffPct.valueOrDefault/100;return null==s||null==a||(0,l.approximates)(s,a,o)?void 0:"Different "+n+": "+e[i]+" ≠ "+t[i]}function x(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,s.blank)(e.lensMake)||(0,s.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),P(t)}t.Tag2SynonymGroup=(0,n.lazy)((()=>{const e=new Map;for(const t of w){const i=t[0];for(const n of t)e.set(n,i)}return e})),t.Tag2Synonyms=(0,n.lazy)((()=>{const e=new Map;for(const t of w)for(const i of t)e.set(i,t);return e})),t.zeroesRe=/^[\s0]*1?$/,t.stringifyExifUid=S,t.renderExifUidId=P,t.decodeExifUid=_,t.findInequalFields=function(e,i){const n=_(e),s=_(i);if(null==n||null==s||e===i)return;const a=(0,f.intersection)((0,u.keys)(n),(0,u.keys)(s)).filter((e=>!(0,t.Tag2SynonymGroup)().has(e)));for(const e of a){const t=n[e],i=s[e];if(b(t)!==b(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of w){const t=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(s,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(h.toS),o=(0,u.values)(i).map(h.toS);if((0,r.includesAny)(a,o))continue;const l=(0,f.least)((0,u.keys)(t)),c=(0,f.least)((0,u.keys)(i));return{aKey:l,aValue:n[l],bKey:c,bValue:s[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return(0,d.firstDefinedThunk)([()=>E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat}),()=>E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat}),()=>E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction}),()=>E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})])},t.cameraIdFromTags=function(e){return P((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return x({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=x,t.imageIdFromTags=function(e){return P((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))}},12788:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toExifDefined=t.isExifUnset=void 0;const n=i(22573),r=i(54993),s=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,n.blank)(e)||s.test((0,r.toS)(e))}t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e}},80495:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.focalLengthToInt=t.exposureTimeToFloat=t.extractExposureSettings=void 0;const n=i(19851),r=i(22573),s=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,n.lazy)((()=>(0,l.mkLogger)("tags.ExposureSettings")));t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,r.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,s.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map((e=>(0,s.toInt)(e)));return(0,s.gt0)(t)&&(0,s.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,s.toFloat)(e);return(0,s.gt0)(t)?Math.round(t):void 0}},88840:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const n=i(50989);t.ExtTypes=(0,n.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","AssetFile","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripExt=t.isSupportedByOldBrowserExt=t.isSupportedByCurrentBrowserExt=t.isExifExt=t.isAssetFileExt=t.isVideoExt=t.isSharpExt=t.isRawImageExt=t.mimeRootType=t.isExtType=t.extTypes=t.equivalentExts=t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.getExtAliases=t.mimetypeExt=t.extMimetype=t.AssetFileExts=t.AllFileExts=t.ExifFiletypes=t.AssetFiletypes=t.AllFiletypes=t.VideoFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0;const n=i(19851),r=i(40958),s=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(32144),d=i(49047),h=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":d.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef","dng"],"image/x-raw":["raw"],"image/x-samsung-srw":["srw"],"image/x-sony-arw":["arw"],"image/x-sony-sr2":["sr2"],"image/x-sony-srf":["srf"]},t.VideoFiletypes={"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/mp2t":["mts","ts"],"video/mp4":["mp4","insv"],"video/mpeg":["m2v","mpeg","mpg"],"video/quicktime":["mov","qt"],"video/webm":["webm"],"video/x-m4v":["m4v"],"video/x-mng":["mng"],"video/x-ms-asf":["asf"],"video/x-msvideo":["avi"],"video/x-ms-wmv":["wmv"]},t.AllFiletypes={...t.BrowserFiletypes,...c.SidecarFiletypes,...t.SharpImageFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.AssetFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.AssetFiletypes,...c.SidecarFiletypes};const f=(0,n.lazy)((()=>{const e={};for(const[i,n]of(0,o.entries)(t.AllFiletypes))for(const t of n)e[t]=i;return e})),m=(0,n.lazy)((()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e}));function p(e){return m()[(0,c.normalizeExt)(e)??""]}t.AllFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AllFiletypes))))),t.AssetFileExts=(0,n.lazy)((()=>(0,r.uniq)((0,s.flatten)((0,o.values)(t.AssetFiletypes))))),t.extMimetype=function(e){return f()[(0,c.normalizeExt)(e)??""]},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=p,t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const g=(0,n.lazy)((()=>{const e=new a.MultiMap;for(const{exts:i,type:n}of[{exts:t.SharpImageFiletypes,type:h.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:h.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:h.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:h.ExtTypes.Video},{exts:c.SidecarFiletypes,type:h.ExtTypes.Sidecar},{exts:t.AssetFiletypes,type:h.ExtTypes.AssetFile},{exts:t.ExifFiletypes,type:h.ExtTypes.Exif}])for(const t of(0,s.flatten)((0,o.values)(i)))e.add(t,n);for(const i of t.OldBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const n of t.AllFiletypes[i]??[])e.add(n,h.ExtTypes.SupportedByCurrentBrowser);return e}));function y(e){const t=(0,c.normalizeExt)(e);return null==t?void 0:g().get(t)}function v(e,t){return y(e)?.includes(t)??!1}t.equivalentExts=function(e,t){const i=(0,c.normalizeExt)(e),n=(0,c.normalizeExt)(t);return null!=i&&null!=n&&(i===n||(p(i)?.includes(n)??!1))},t.extTypes=y,t.isExtType=v,t.mimeRootType=function(e){const t=y(e);return null==t?void 0:t.includes(h.ExtTypes.Sharp)||t.includes(h.ExtTypes.RawImage)?"image":t.includes(h.ExtTypes.Video)?"video":void 0},t.isRawImageExt=function(e){return v(e,h.ExtTypes.RawImage)},t.isSharpExt=function(e){return v(e,h.ExtTypes.Sharp)},t.isVideoExt=function(e){return v(e,h.ExtTypes.Video)},t.isAssetFileExt=function(e){return v(e,h.ExtTypes.AssetFile)},t.isExifExt=function(e){return v(e,h.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return v(e,h.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,t=h.ExtTypes.AssetFile){const i=(0,l.splitLast)(e,".");return v(i,t)?e.slice(0,-(i.length+1)):e}},14245:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitInvalidGeolocationTags=t.geolocationToXmp=t.pickGeoTags=t.GeolocationFields=void 0;const n=i(22573),r=i(45599),s=i(68708),a=i(50213),o=(0,r.defer)((()=>(0,a.mkLogger)("tags.Geolocation")));t.GeolocationFields=["GeolocationBearing","GeolocationCity","GeolocationCountry","GeolocationCountryCode","GeolocationDistance","GeolocationPopulation","GeolocationPosition","GeolocationSubRegion","GeolocationRegion","GeolocationTimeZone"],t.pickGeoTags=function(e){return(0,s.pick)(e,...t.GeolocationFields)},t.geolocationToXmp=function(e){const t=e;for(const{xmp:i,gl:r}of[{xmp:"Country",gl:"GeolocationCountry"},{xmp:"State",gl:"GeolocationRegion"},{xmp:"State",gl:"GeolocationSubRegion"},{xmp:"City",gl:"GeolocationCity"}])(0,n.blank)(e[i])&&!(0,n.blank)(t[r])&&(t[i]=t[r]);return e},t.omitInvalidGeolocationTags=function(e){if(0===e.GPSLatitude&&0===e.GPSLongitude){o().info("omitInvalidGeolocationTags: lat/lon == (0,0): stripping off GPS and Geolocation metadata",(0,s.pick)(e,"Directory","FileName"));for(const t of(0,s.keys)(e))(t.startsWith("GPS")||t.startsWith("Geolocation"))&&delete e[t]}return e}},67083:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ensureHistoryRecords=t.ensureInferredHistoryRecords=t.inferredToTags=t.valueFromResourceEvent=t.getInferredHistoricValues=t.tagsContainHistory=t.InferAction=t.mkHistoryRecord=t.mkHistoryRecords=t.Actions=void 0;const n=i(77988),r=i(19851),s=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(80875),v=i(50213),w=i(81168),S=i(66649),b=i(17415),P=i(29882),M=i(95696),_=i(17217),E=i(28874),x=i(47783);function T(e,t){return(0,d.entries)(t??{}).map((([t,i])=>D({action:e,key:t,value:i})))}function D({action:e,key:t,value:i,ts:r}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)((0,d.maybeCall)(i,"toJSON")??i),When:n.ExifDateTime.fromMillis(r??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.mkHistoryRecords=T,t.mkHistoryRecord=D,t.InferAction="infer";const k=(0,r.lazy)((()=>(0,v.mkLogger)("tags.History")));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function F(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,y.parseJSON)(e.Parameters)??(0,u.revive)(e.Parameters)}function O(e){if(null==e)return;const t={};for(const[i,n]of(0,d.entries)(e))(0,w.isFirstCharAZ)(i)&&(t[i]=n);"duration"in e&&(t.Duration=e.duration),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,b.luxonTzOffsetToOffsetMinutes)(e.tz??e.capturedAt?.zoneName,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function I(e,i,n){if(null==e||(0,o.blank)(e))return void k().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const r=(0,_.toNativePath_)(e),a=await(0,x._readRawTags)(r),u=(0,m.toA)(i).filter((e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,(e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters"))))})),c={...n??{}};if((0,s.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void k().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:n,tagsToWrite:c});k().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:n});const h=M.PosixFile.for(e);return await(0,x.overwriteTags_)(h,c),h.clearThisAndParent(),u}t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const r=(0,m.toA)(e);if((0,s.isEmpty)(r))return{};const l=(0,a.sortBy)(r.filter((e=>(0,w.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer)),(e=>(0,S.datedToMillis)((0,o.mapNotBlank)(e.When,(e=>n.ExifDateTime.from(e))))??0)),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const n=F(e);(0,o.blank)(n.nativePath)||(0,P.eqlNameWithoutExt)(n.nativePath,i)?u[t]=n:k().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=F,t.inferredToTags=O,t.ensureInferredHistoryRecords=async function(e,i,n){const r=T(t.Actions.infer,n),s=(E.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?O(n):void 0)??{};return E.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(s.Source=e.nativePath),k().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:r,additionalTags:s}),I(i,r,s)},t.ensureHistoryRecords=I},3432:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.inferTzOffsetMinutesFromFilename=t.zoneFromLatLon=t.maybeInferTimezone=void 0;const r=n(i(53705)),s=i(77988),a=i(19851),o=i(40958),l=i(50357),u=i(79842),c=i(21330),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),w=i(14245),S=i(61424),b=(0,a.lazy)((()=>(0,p.mkLogger)("tags.InferTimezone")));async function P(e,t,i){(0,w.omitInvalidGeolocationTags)(t);{const e=M(t);if(null!=e){const i={tz:e.name,tzSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.tz)||t.tzSource===s.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,o.compactBlanks)([...g.Settings.capturedAtTags.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof s.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{tz:i.zone,tzSource:"infer:tag."+e+".zone"}}if(!i){const i=_(e,t);if(null!=i)return i}if(!i){const t=await(0,S.nearestSiblingTzOffset)(e);if(null!=t)return{tz:t.zoneName,tzSource:"infer:nearestSibling:"+t.base}}}}function M(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return b().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,r.default)(t,i);return b().tap({msg:"zoneFromLatLon()",result:(0,h.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return b().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function _(e,t){const i=(0,d.parseDateTime)([(0,y.bname)(e.name,!0),(0,y.bname)(e.name,!1)]);if(null!=i&&(0,f.isValidDate)(i))for(const n of g.Settings.capturedAtTags.values){const r=(0,u.toDated)(t[n]);if(null==r||(0,f.isValidDate)(r))continue;const s=Math.round(15*i.diff(r,"minutes").as("minutes")/15),a=(0,h.normalizeZoneOffsetMinutes)(s),o=0===a?void 0:(0,h.normalizeZone)(a);if(null!=o)return b().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{tz:o.name,tzSource:"infer:filename (diff with "+n+")"},meta:{dt:(0,c.datedToISO)(r),rawTzoffsetMinutes:s,normalizedOffsetMinutes:a}})}}t.maybeInferTimezone=async function(e,t,i){return b().tap({msg:"maybeInferTimezone()",result:await P(e,t,i)})},t.zoneFromLatLon=M,t.inferTzOffsetMinutesFromFilename=_},28630:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=void 0;const n=i(77988),r=i(40958),s=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(20214),d=i(59455),h=i(48884),f=i(73168),m=i(98725),p=i(17415);function g(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const r=(0,p.normalizeZone)(e?.formatted),s=n.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:r??t??n.UnsetZone});if(!0===s?.isValid)return s}return(0,m.parseDated)({input:e.formatted,defaultZone:t})}t.readJsonSidecar=async function(e,t){return(0,c.thenMap)(e.readJson("info"),(e=>(0,u.compactValues)({Title:(0,s.toNotBlank)(e.title),Description:(0,s.toNotBlank)(e.description),GPSLatitude:(0,h.first)([e.geoData?.latitude,e.geoDataExif?.latitude],(e=>(0,f.validLat)(e)?e:void 0)),GPSLongitude:(0,h.first)([e.geoData?.longitude,e.geoDataExif?.longitude],(e=>(0,f.validLon)(e)?e:void 0)),GPSAltitude:(0,h.first)([e.geoData?.altitude,e.geoDataExif?.altitude],(e=>(0,l.isNumber)(e)?e:void 0)),favorited:(0,o.map)(e.favorited,a.isTrue),peopleNames:(0,r.mapNotEmpty)([...(0,d.toA)(e.people),...(0,d.toA)(e.person)],(e=>(0,r.compactBlanks)(e.map((e=>e.name))))),creationTime:g(e.creationTime,t),modificationTime:g(e.modificationTime,t),photoTakenTime:g(e.photoTakenTime,t),imageViews:(0,l.mapInt)(e.imageViews,(e=>e)),googlePhotosOrigin:!0})))}},68268:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const n=i(50989);t.KeywordReparentingStrategies=(0,n.strEnum)("move","copy","retain")},97573:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rawTagKeywords=t.parseKeywordStruct=t.isKeywordStruct=t.parseCategories=t.splitKeywords=t.splitKeyword=t.delimRe=t.keywordToPath=void 0;const n=i(77988),r=i(66150),s=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,s.lazy)((()=>(0,f.mkLogger)("tags.KeywordTags"))),v=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")))));function w(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function S(e){return null==e||e instanceof n.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(S)):w(e))}function b(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(b).map((t=>t.map((t=>(0,a.compact)([e._,...t]))))))}(0,l.later)((()=>{g.Settings.keywordPathSeparators.watchLater((()=>v.unset()))})),t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.delimRe=(0,s.lazy)((()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,(e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))))),g.Settings.keywordDelimiters.watchLater((()=>t.delimRe.unset())),t.splitKeyword=w,t.splitKeywords=S;const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new r.XMLParser({textNodeName:"_"}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(b))}catch(t){return void y().warn("parseCategories() failed:",{err:t,s:e})}}function _(e){return Array.isArray(e)&&e.every(_)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(_))}function E(e){if(null==e)return[];if(Array.isArray(e)&&e.every(_))return(0,h.flatMap)(e,E);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,E).map((t=>[e.Keyword,...t]))}t.parseCategories=M,t.isKeywordStruct=_,t.parseKeywordStruct=E,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const n=M(e.Categories);null!=n&&t.push(...n)}for(const n of i){const i=(0,c.pluckDeep)(e,n)?.value;(0,o.blank)(i)||(_(i)?t.push(...E(i)):t.push(...Array.isArray(i)?i:S(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})}},15912:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeLensModel=t.cleanBogusPrecision=t.justLengthAndAperture=t.extractLensMakeModel=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,n.lazy)((()=>(0,d.mkLogger)("tags.LensMakeModel"))),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?[\d.]+)\/(?[\d.]+)(?.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),n=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],S),u=(0,r.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&n.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==S(e))continue;(0,s.notBlank)(t)&&n.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&n.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,r.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&n.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&n.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of n){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=b(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,b)}return(0,c.greatestBy)(n,(e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length]))};const v=/([\d. -]+)\s?mm\b/i,w=/\bf\/?([\d.\-]+)/i;function S(e){if((0,s.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=w.exec(e)?.[1];return y(t)&&y(i)?b(`${t}mm f/${i}`):void 0}function b(e,t=3){return e.replace(/\d+\.\d+/g,(e=>(0,a.mapOr)((0,o.toFloat)(e),(e=>String((0,o.sigFigs)(e,t))),e))).replace(/\s+/g," ").trim()}t.justLengthAndAperture=S,t.cleanBogusPrecision=b,t.normalizeLensModel=function(e){return b(e).replace(/(\d) - (\d)/g,((e,t,i)=>`${t}-${i}`)).replace(/(\d)\s+mm\b/,((e,t)=>t+"mm")).replace(/\s+f\/?(\d)/i,((e,t)=>" f/"+t))}},30748:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.model=t.makeFromSoftware=t.make=t.extractMakeAndModel=t.companyCased=void 0;const n=i(19851),r=i(22573),s=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const n=e.replace(t,i);return n===e?e:h(n,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map((e=>[e.toLowerCase(),e])));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,(e=>e.toUpperCase()))}t.companyCased=m;class p{constructor(){this.ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|"),this.ignorableSep="[\\s\\.,_-]*",this.IgnorableMakePatterns=new RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,"i"),this.IgnorableModelPatterns=[/[\da-f]{24,}$/i,/\(v\d(?:\d?[^\d\n\r\u2028\u2029]\d+|\d{2,}(?:[^\d\n\r\u2028\u2029]\d+)?)\)\w?$/i,/digital camera$/i,/zoom camera$/i],this.samsungPatterns=[[/^PL150 /,"PL150"],[/^SCH-I545|SHV-E300|SGH-I337|SGH-M919|SPH-L720|SCH-R970|SGH-N045|GT-I950/i,"Galaxy S4"],[/^SGH-i537|GT-I9295/,"Galaxy S4 Active"],[/^GT-S50\S+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]],this.lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]],this.onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]],this.CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}}const g=(0,n.lazy)((()=>new p)),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??S(e.Software)??S(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModelName)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v;const w={Acer:/^Acer\b/i,Canon:/^(Canon|CanoScan)\b/i,Daisy:/^Exif Daisy\b/i,Fujifilm:/Digital Camera FinePix\b/i,GE:/Digital Camera GE\b/i,Kodak:/\bKodak\b/i,Kyocera:/^Kyocera|SAMURAI\b/i,LG:/^(LGE_SW|LG Electronics)\b/i,Minolta:/^(Minolta|DiMAGE|DYNAX|MAXXUM|ALPHA SWEET)\b/i,Nikon:/^(Nikon|COOLPIX)\b/i,Olympus:/^OLYMPUS\b/i,OnePlus:/^OnePlus/i,Pentax:/^(Optio|PENTAX)\b/i,Ricoh:/^RICOH\b/i,RIM:/^(Rim Exif Version|BlackBerry)/i};function S(e){if(!(0,r.blank)(e))for(const[t,i]of(0,a.entries)(w))if(i.test(e))return t}t.makeFromSoftware=S;const b=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=b.exec(i);null!=e&&(i=e[1].trim())}const n=(0,s.map)(g().CommonNamesByMake[e],(e=>e.find((([e])=>null!=i.match(e)))));if(null!=n)return n[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,s.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),(e=>`${e[1]} Mark ${e[2]}`),(()=>i))),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}t.model=P},16170:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isMimeTypeIncluded=t.isAssetFileMimeType=t.isFileMimeTypeIncluded=t.isLibrawMimeType=t.isSharpMimeType=t.normalizeMimetype=t.isVideoMimeType=t.isImageMimeType=t.isMimeTypeSupportedByBrowser=void 0;const n=i(22573),r=i(54993),s=i(2322),a=i(277),o=i(16047),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,n.notBlank)(e)&&(e.startsWith("video/")||"application/mp4"===e||"application/ogg"===e)}function f(e){const t=(0,r.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,s.isChrome)(t)||(0,s.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,r.toS)(e))},t.isImageMimeType=function(e){return(0,r.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,n.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,n.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,o.isHeifMimeType)(t)?await(0,a.isHeifSupported)():t in u.AssetFiletypes)},t.isMimeTypeIncluded=m},61208:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const n=i(50989);t.NameTagFormats=(0,n.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const n=i(50989);t.NameTagOrders=(0,n.strEnum)("western","eastern")},95141:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rotationToWriteTag=t.rotationToExifOrientation=t.orientationToRotation=t.orientationRequiresMirroring=t.extractRotation=void 0;const n=i(21605),r=i(54993),s=i(16170);t.extractRotation=function(e){return null==e?void 0:((0,s.isVideoMimeType)(e.MIMEType)?(0,n.normalizeRotation)(e.Rotation):void 0)??o(e.Orientation)};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function o(e){return(0,n.isRotation)(e)?e:null!=e?a.get(e):void 0}t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,r.toS)(e).startsWith("Mirror")},t.orientationToRotation=o;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);t.rotationToExifOrientation=function(e){return l.get((0,n.normalizeRotation)(e))},t.rotationToWriteTag=function(e){const t=(0,n.normalizeRotation)(e);return null==t?void 0:{"Orientation#":l.get(t),Rotation:t}}},7330:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractLiked=t.extractRating=t.clampRating=void 0;const n=i(55835),r=i(31586),s=i(28874);function a(e){const t=(0,r.toInt)(e);return null==t?void 0:(0,r.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,r.mapNumeric)((0,r.toInt)(e?.RatingPercent),(e=>Math.ceil(5*e/100)))??(0,n.map)(e?.favorited,(e=>!0===e?s.Settings.likeRating.valueOrDefault:void 0))}t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=s.Settings.likeRating.valueOrDefault}},54979:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readMimeType=t.mimetypeCache=void 0;const n=i(19851),r=i(22573),s=i(55835),a=i(88561),o=i(78923),l=i(95696),u=i(63870),c=i(47783),d=i(16170);t.mimetypeCache=(0,n.lazy)((()=>new a.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,u.commandTimeoutMs)()}))),t.readMimeType=async function(e){if((0,r.blank)(e))return;const i=l.PosixFile.for(e);return(0,t.mimetypeCache)().getOrSetAsync(i.nativePath,(async()=>(0,s.map)((0,c.rawTagsCache)().get(i.nativePath)?.MIMEType??(await(0,c.cachedTags)(i))?.MIMEType??(await(0,o.readFileType_)(i.nativePath).catch((()=>{})))?.mime,d.normalizeMimetype)))}},79915:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultSidecarExt=t.existingSidecars=t.AllowedUncommonSuffixRe=t.isSidecarOf=void 0;const n=i(16928),r=i(40958),s=i(22573),a=i(81168),o=i(56519),l=i(35280),u=i(32144),c=i(4001),d=i(28874),h=i(14036);function f(e,t,{ignoreCase:i}){return i?(0,a.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function m(e,i){if(!(0,u.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const o=(0,u.isJsonExt)(i.ext),l=o||d.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(f(e.base,i.name,{ignoreCase:l}))return!0;if(f(e.name,i.name,{ignoreCase:l}))return!0;if((0,u.normalizeExt)(e)===(0,u.normalizeExt)(i.name)){const t=(0,n.parse)(i.name).name;if(f(e.name,t,{ignoreCase:l}))return!0}const m=o||d.Settings.matchSidecarsFuzzily.valueOrDefault;if(m)for(const t of(0,r.uniq)([e.base,e.name,(0,h.stripExt)(e.base)]))for(const e of(0,r.uniq)([i.name,i.name,(0,h.stripExt)(i.name)]))if(f((0,c.stripCopySuffixFromName)(t),(0,c.stripCopySuffixFromName)(e),{ignoreCase:m}))return!0;return o&&function(e,i){const n=(0,a.commonPrefixIgnoreCase)(e,i);if(n.length<8)return!1;function r(e){return(0,s.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const o=r(e.slice(n.length)),l=r(i.slice(n.length));return o&&l}(e.name,i.name)}t.isSidecarOf=m,t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.existingSidecars=async function(e){return t=e,(0,u.isSidecarExt)(t.ext)||(0,l.inHiddenPhotoStructureDir)(t)?[]:(0,o.sortByAsync)({name:"_existingSidecars",arr:e.siblings((t=>m(e,t))),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,a.ensurePrefix)(d.Settings.defaultSidecarType.valueOrDefault,".")}},1078:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractSizeInfoFromTags=t.extractSizeInfoFromFile=void 0;const n=i(19851),r=i(22573),s=i(42659),a=i(33374),o=i(48884),l=i(50213),u=i(88561),c=i(95696),d=i(86580),h=i(34943),f=i(66106),m=i(43207),p=i(47783),g=i(16170),y=i(95141),v=(0,n.lazy)((()=>(0,l.mkLogger)("tags.SizeInfo"))),w=(0,n.lazy)((()=>new u.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:s.minuteMs})));async function S(e,t){if(null==e)return;const i=null==t||(0,r.blank)(t.ImageHeight)?await(0,p.readRawTags)(e):t;if(null==i)return;const n=(0,y.extractRotation)(t)??(0,y.extractRotation)(i);if((0,g.isLibrawMimeType)(i.MIMEType))return b(i,n,await(0,h.rawInfo)(e));const s=b(i,n);if(null!=s)return s;if((0,g.isVideoMimeType)(i.MIMEType)){const t=await S(await(0,f.extractVideoFrame_)(e),i);if(null!=t)return{...t,durationMs:(0,m.extractDurationMs)(i)}}}function b(e,t,i){t??(t=(0,y.extractRotation)(e));const n=(0,o.first)([i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}],(e=>(0,a.isDimensions)(e)?e:void 0));if(null==n)return v().tap({msg:"extractSizeInfo("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo,fileDimensions:n}});const r=(0,a.maybeDimSwap)(n,t);return v().tap({msg:"extractSizeInfo("+e?.FileName+")",result:{ImageHeight:r.height,ImageWidth:r.width,aspectRatio:(0,d.aspectRatio)(r),dimensions:r,rotation:t,fileDimensions:n,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,rawInfo:h.rawInfo}})}t.extractSizeInfoFromFile=async function(e,t){if(null==e)return;const i=c.PosixFile.for(e);return w().getOrSetAsync(i.nativePath,(()=>S(i,t)))},t.extractSizeInfoFromTags=b},61424:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractStatPathTime=t.extractStatBname=t.nearestSiblingTzOffset=t.nearestSiblings=t.beforeAfterCapturedAt=t.inferCapturedAtFromSiblings=t.inferMakeAndModel=t.canInferForDir=void 0;const n=i(77988),r=i(51168),s=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(42659),c=i(55835),d=i(59455),h=i(48884),f=i(23467),m=i(50213),p=i(96859),g=i(56038),y=i(24689),v=i(79842),w=i(21330),S=i(98725),b=i(51275),P=i(35280),M=i(19748),_=i(88561),E=i(95696),x=i(65238),T=i(17217),D=i(57902),k=i(28874),C=i(80496),F=i(65162),O=i(28544),I=i(47783),L=i(88840),A=i(30748),R=i(16170),N=(0,s.lazy)((()=>(0,m.mkLogger)("tags.TagInference"))),B=7;async function z(e){return k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.never?(N().debug("canInferForDir("+e+"): disabled: "+k.Settings.siblingInference.toEnvLine()),!1):!0===(0,P.inHiddenPhotoStructureDir)(e)?(N().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):!(k.Settings.siblingInference.valueOrDefault===C.TagInferenceSettingValues.auto&&await(0,x.isSlowDir)(e.nativePath)&&!await(0,x.isCachedDir)(e.nativePath)&&(N().debug("canInferForDir("+e+"): disabled (slow uncached directory)"),1))}async function j(e){e=(0,d.toA)(e);for(let t=0;te.base)));for(const t of n){const n=(0,A.extractMakeAndModel)(await(0,I.readRawTags)(t));if((0,f.definedAndNotEql)(n.Make,i.Make))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:i,fromSibling:n});else if((0,f.definedAndNotEql)(n.Model,i.Model))N().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:i,fromSibling:n});else if(null!=n.Make&&null!=n.Model)return N().tap({msg:"inferMakeAndModel("+e+")",level:D.LogLevels.info,result:n,meta:{sibling:t.base}})}return i},t.inferCapturedAtFromSiblings=async function(e){if(!await z(e.parent()))return;const t=await W(e);return null!=t&&(0,w.closeTo)(t.before.date,t.after.date,2*u.dayMs)?(0,c.map)(y.DateInterval.for((0,w.toExifDateTime)(t.before.date,(0,b.getZoneName)(t.before.date)),(0,w.toExifDateTime)(t.after.date,(0,b.getZoneName)(t.after.date)),t.index,t.slots),(e=>({date:e,src:`before:${t.before.src},after:${t.after.src}`}))):void 0};const V=(0,s.lazy)((()=>new _.FileCache({name:"tags.beforeAfterCapturedAt"})));function W(e){return V().getOrSet(e.nativePath,(async()=>{const t=await q(e),i=await j(t?.younger),n=await j(t?.older);return null==i||null==n?void 0:{before:i,after:n,index:i.index,slots:i.index+n.index+1}}))}t.beforeAfterCapturedAt=W;const H=(0,M.extFilter)(L.ExtTypes.AssetFile);function U(e){return null==e?[]:(0,a.compact)((0,h.flatZip)((0,d.toA)(e.younger),(0,d.toA)(e.older)))}async function q(e,t=7,i=!0){if(!await z(e.parent()))return;const n=await(0,g.time)("tags.nearestSiblings:"+e,(async()=>{const t=await e.parent().directoryEntry(),i=await(t?.childFiles());return i?.filter((async e=>e.isFile()&&!e.isNameHidden()&&(H(e)??await(0,R.isAssetFileMimeType)(e))))}));if(null==n)return void N().info("nearestSiblings(): can't readdir parent, "+e.parent());const r=(0,o.sortBy)(n,(e=>(0,F.bname)(e))),s=(0,T.findFileIndex)(e,r);if(s<0)return N().warn("nearestSiblings(): can't find self in siblings: "+e,{canRetry:i}),i?(e.parent().clear(),q(e,t,!1)):void 0;const l=k.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[u,c]=[r.slice(s-2*t,s),r.slice(s+1,s+1+2*t)],d=[],h=[];for(;(0,a.isNotEmpty)(u)&&d.length=l&&d.push(t)}for(;(0,a.isNotEmpty)(c)&&h.length=l&&h.push(t)}return N().tap({msg:"nearestSiblings()",level:"trace",result:{younger:d,older:h},meta:{f:e}})}t.nearestSiblings=q,t.nearestSiblingTzOffset=async function(e){if(!await z(e.parent()))return;const t=U(await q(e)),i=await async function(e){e=(0,d.toA)(e).slice(0,B);for(const t of e){const e=await(0,I.readRawTags)(t);if(null!=e&&(0,l.notBlank)(e.tz)&&e.tzSource!==n.defaultVideosToUTC)return N().tap({msg:"firstWithZoneName()",result:{zoneName:e.tz,path:t.nativePath,base:t.base,src:e.tzSource??"tags.tz"},meta:{tzSource:e.tzSource}})}N().debug("firstWithZoneName(): no zone name found",{arr:e})}(t);return N().tap({msg:"nearestSiblingTzOffset()",result:i,meta:{f:e,sibs:t.map((e=>e.base))}})},t.extractStatBname=async function(e){const t=(0,a.uniq)([(0,F.bname)(e,!0),(0,F.bname)(e,!1)]),i=(0,S.parseDated)({input:t});if(null==i)return void N().debug("extractStatBname(): bname isn't dated",{base:e.base,input:t});const n=await e.stat();if(null!=n){for(const e of["birthtime","atime","mtime","ctime"])if((0,v.datedOverlap)({a:i,b:n[e]}))return N().tap({msg:"extractStatBname()",result:{src:e,date:i},meta:{input:t,stat:n}});return N().tap({msg:"extractStatBname(): no stat overlap with bname",result:void 0,meta:{input:t,fromName:i,stat:n}})}N().debug("extractStatBname(): no stat",{path:e.nativePath})},t.extractStatPathTime=async function(e){const t=(0,S.extractDateFromPath)(e.pathsForDateParsing);if(null==t)return;const i=await e.stat();if(null!=i){for(const e of["birthtime","mtime","ctime"]){const n=i[e];if(null!=n&&!0===(0,v.datedOverlap)({a:t,b:n}))return N().tap({msg:"extractStatPathTime()",result:{src:"path+"+e,date:r.DateTime.fromJSDate(n)},meta:{dateFromPath:t,stat:i,src:e}})}return N().tap({msg:"extractStatPathTime(): no match",result:void 0,meta:{dateFromPath:t,stat:i}})}}},42231:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.omitAncestorTags=t.isTagPathDescendant=t.leafIsExcluded=t.tagPathLeaf=t.tagPathsInclude=t.tagDiff=t.tagPathEql=t.uniqTagPaths=t.normalizeTagPath=t.splitTagPath=t.joinedTagPathBasename=t.joinTagPath=t.tagPathToStringArray=t.tagPathToPathTag=t.tagRefToS=t.TagSep=void 0;const n=i(40958),r=i(76790),s=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,n.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map((e=>(0,o.replaceAll)(e,i,""))).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(s.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,s.blank)(e)?void 0:Array.isArray(e)?f((0,n.last)(e)):(0,n.last)(g(e))}function w(e,t){if((0,n.isEmpty)(e)||(0,n.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every(((e,t)=>(0,h.equalsIgnoreCase)(e,i[t])))}t.TagSep=String.fromCharCode(31),t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map(((e,t)=>({tagPath:e,displayName:e[t].displayName})))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,n.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,n.uniqBy)((0,l.toA)(e),(e=>(0,n.isEmpty)(e)?void 0:p(e)))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,n.compact)(t).map((e=>y(e))));return(0,n.compact)(e).filter((e=>!i.has(y(e))))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some((e=>i===y(e)))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),(e=>(0,h.includesIgnoreCase)(t,e)),(()=>!1))},t.isTagPathDescendant=w,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,r.sortBy)(e.filter(n.isNotEmpty),(e=>-e.length)))t.some((e=>w(i,e)))||t.push(i);return(0,r.sortBy)(t,(t=>e.indexOf(t)))}},8791:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=void 0;const n=i(40958),r=i(22573),s=i(68708),a=i(54993);t.extractTitleDescription=function(e){const t=(0,n.uniq)(["OLYMPUS DIGITAL CAMERA",e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map((e=>(0,r.mapNotBlank)(e,(e=>e.trim().toLowerCase().normalize())))),i=(...i)=>{for(const n of i){const i=(0,a.toS)(e[n]).trim();if((0,r.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,s.compactValues)({title:i("XPTitle","Title","ObjectName"),description:i("XPSubject","Description","ImageDescription","Caption-Abstract")})}},45200:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriExists=t.uri2nativePath=t.uriVariants=t.nativePath2uriVariants=t.nativePath2uris=t.nativePath2uri=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(96249),o=i(89937),l=i(59455),u=i(50213),c=i(56519),d=i(16287),h=i(7014),f=i(34238),m=i(87001),p=i(20237),g=i(5696),y=i(12228),v=(0,n.lazy)((()=>(0,u.mkLogger)("uri.FileURI")));async function w(e){const t=await(0,h.bestVolumeForPath)(e);return(0,c.thenCompact)([(0,g.nativePath2pslib)(e),(0,p.nativePath2psfile)(e,t),(0,y.nativePath2psnet)(e,t),f.URI.file(e)])}async function S(e){const t=await w(e);return(0,r.uniq)((0,a.flatten)(t.map(m.uriEncodingVariants)))}async function b(e,t){if((0,s.blank)(e))return;const i=function(e){try{return f.URI.isUri(e)?e:f.URI.parse(e,!0)}catch(t){return void v().warn("bad URI",{uri:e,err:t})}}(e);if(null!=i)switch(i.scheme){case"file":return i.fsPath;case o.PS_LOCAL_FILE_SCHEME:return(0,p.psfile2nativePath)(i,t);case o.PS_NETWORK_FILESYSTEM_SCHEME:return(0,y.psnet2nativePath)(i,t);case o.PS_LIBRARY_SCHEME:return(0,g.pslib2nativePath)(i);default:throw new Error("unsupported URI: "+e)}}t.nativePath2uri=async function(e,t){return null==e||(0,s.blank)(e)?v().throw("empty nativePath passed to nativePath2uri()",{retriable:!1}):(0,g.nativePath2pslib)(e)??await(0,p.nativePath2psfile)(e,t)??await(0,y.nativePath2psnet)(e,t)??f.URI.file(e)},t.nativePath2uris=w,t.nativePath2uriVariants=S,t.uriVariants=async function(e,t){const i=(0,m.uriEncodingVariants)(e);return i.push(...(0,l.toA)(await(0,c.thenMap)(b(e,t),S))),(0,r.uniq)(i)},t.uri2nativePath=b,t.uriExists=async function(e,t){const i=await b(e,t);return null!=i&&await(0,d.exists)(i)}},34238:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriToBasename=t.toURI=t.percentDecode=t.uriToFsPath=t.encodeURIComponentFast=t.URI=void 0;const n=i(76760),r=i(57975),s=i(57160),a=i(22573),o=i(55835),l=i(51926),u=i(29652),c=i(54993),d=i(48884),h=i(43334),f=/^\w[\w+.-]*$/,m=/^\//,p=/^\/\//,g="",y="/",v=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class w{static isUri(e){return e instanceof w||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}constructor(e,t,i,n,r,s=!1){"object"==typeof e?(this.scheme=e.scheme||g,this.authority=e.authority||g,this.path=e.path||g,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||g):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=t??g,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==y&&(t=y+t):t=y}return t}(this.scheme,i??g),this.query=(0,u.toURLSearchParams)(n??""),this.fragment=r??g,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!f.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!m.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(p.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,s))}get fsPath(){return E(this,!1)}with(e){if(null==e)return this;let{scheme:t,authority:i,path:n,query:r,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=g),void 0===i?i=this.authority:null===i&&(i=g),void 0===n?n=this.path:null===n&&(n=g),void 0===r?r=this.query:null===r&&(r=g),void 0===s?s=this.fragment:null===s&&(s=g),t===this.scheme&&i===this.authority&&n===this.path&&r===this.query&&s===this.fragment?this:new b(t,i,n,r,s)}static parse(e,t=!1){const i=v.exec(e);if(!i)return new b(g,g,g,g,g);const n=i[2]||g,r=k(i[4]||g),s=(i[5]||g).split("/").map(k).join("/"),a="psfile"===n&&s.startsWith("//")?s.slice(1):s,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||g);return new b(n,r,a,o,l,t)}static file(e){let t=g;if(h.isWin&&(e=e.replace(/\\/g,y)),e[0]===y&&e[1]===y){const i=e.indexOf(y,2);-1===i?(t=e.substring(2),e=y):(t=e.substring(2,i),e=e.substring(i)||y)}return new b("file",t,e,g,g)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=h.isWin&&"file"===e.scheme?w.file(n.win32.join(E(e,!0),...t)).path:n.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===y}get pathBase(){return this.isRootPath()?"":(0,o.map)(this.path,(e=>(0,d.findLast)(e.split(y),a.notBlank)))}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(y))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,y)+e.join(y)})}toString(e=!1){return x(this,e)}toJSON(){return this}[r.inspect.custom](){return this.toString()}}t.URI=w;const S=h.isWinPortable?1:void 0;class b extends w{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return null==this._fsPath&&(this._fsPath=E(this,!1)),this._fsPath}toString(e=!1){return e?x(this,!0):(null==this._formatted&&(this._formatted=x(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=S),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,a.mapNotBlank)(this.query,(t=>e.query=t)),this.fragment&&(e.fragment=this.fragment),e}}const P={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function M(e,t){let i,n=-1;for(let r=0;r=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),void 0!==i&&(i+=e.charAt(r));else{void 0===i&&(i=e.substr(0,r));const t=P[s];void 0!==t?(-1!==n&&(i+=encodeURIComponent(e.substring(n,r)),n=-1),i+=t):-1===n&&(n=r)}}return-1!==n&&(i+=encodeURIComponent(e.substring(n))),void 0!==i?i:e}function _(e){let t;for(let i=0;i1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,h.isWin&&(i=i.replace(/\//g,"\\")),i}function x(e,t){const i=t?_:M;let n="";const{scheme:r,query:s,fragment:o}=e;let{authority:l,path:u}=e;if(r&&(n+=r,n+=":"),(l||"file"===r)&&(n+=y,n+=y),l){let e=l.indexOf("@");if(-1!==e){const t=l.substr(0,e);l=l.substr(e+1),e=t.indexOf(":"),-1===e?n+=i(t,!1):(n+=i(t.substr(0,e),!1),n+=":",n+=i(t.substr(e+1),!1)),n+="@"}e=l.indexOf(":"),-1===e?n+=i(l,!1):(n+=i(l.substr(0,e),!1),n+=l.substr(e))}if(u){if(u.length>=3&&47===u.charCodeAt(0)&&58===u.charCodeAt(2)){const e=u.charCodeAt(1);e>=65&&e<=90&&(u=`/${String.fromCharCode(e+32)}:${u.substr(3)}`)}else if(u.length>=2&&58===u.charCodeAt(1)){const e=u.charCodeAt(0);e>=65&&e<=90&&(u=`${String.fromCharCode(e+32)}:${u.substr(2)}`)}n+=i(u,!0)}return(0,a.mapNotBlank)(s,(e=>n+="?"+e)),o&&(n+="#",n+=t?o:M(o,!1)),n}function T(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+T(e.substr(3)):e}}t.encodeURIComponentFast=M,t.uriToFsPath=E;const D=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,s.toUnicode)(e):e.match(D)?e.replace(D,(e=>T(e))):e}t.percentDecode=k,t.toURI=function(e){return w.isUri(e)?e:w.parse(e)},t.uriToBasename=function(e){return(0,l.splitLast)((0,c.toS)(e),"/")}},87001:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.uriEncodingVariants=t.uriIsEquivalent=t.uriEqlSync=t.normalizeURI=t.isUri=void 0;const n=i(19851),r=i(40958),s=i(50357),a=i(89937),o=i(54993),l=i(50213),u=i(45200),c=i(34238),d=["http:","https:","file:",a.PS_LOCAL_FILE_SCHEME,a.PS_NETWORK_FILESYSTEM_SCHEME].map((e=>e+"//"));t.isUri=function(e){const t=(0,o.toS)(e).toLowerCase();return d.some((e=>t.startsWith(e)))};const h=(0,n.lazy)((()=>(0,l.mkLogger)("uri.UriNormalization")));function f(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function m(e,t){try{if(null==e||null==t)return!1;const i=(0,c.toURI)(e),n=(0,c.toURI)(t);return i.scheme===n.scheme&&i.authority===n.authority&&f(i.path,n.path)}catch{return!1}}t.normalizeURI=function(e){try{return c.URI.parse(e).toString()}catch(t){return h().warn("Failed to normalize invalid URI",{uri:e,err:t}),e}},t.uriEqlSync=m,t.uriIsEquivalent=async function(e,t){try{return null!=e&&null!=t&&((0,s.eql)(e,t)||m(e,t)||f(await(0,u.uri2nativePath)(e),await(0,u.uri2nativePath)(t)))}catch{return!1}},t.uriEncodingVariants=function(e){const t=(0,c.toURI)(e);return(0,r.uniq)([t.toString(),t.with({path:t.path.normalize("NFC")}).toString(),t.with({path:t.path.normalize("NFD")}).toString()])}},20237:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.psfile2nativePath=t.joinMountpoint=t.nativePath2psfile=void 0;const n=i(76760),r=i(22573),s=i(51926),a=i(89937),o=i(29882),l=i(78133),u=i(43334),c=i(7014),d=i(34238),h=i(85087);function f(e,t){return(0,n.join)(e,...t.split("/").slice(1))}t.nativePath2psfile=async function(e,t){if((0,r.blank)(e))return;if(null==(t=null!=t&&(0,o.containedByNativePath)({ancestor:t.mountpoint,descendant:e,acceptSelf:!0})?t:await(0,c.bestVolumeForPath)(e))||(0,r.blank)(t.uuid))return;const i=(0,l.native2posix)(e),n=(0,l.native2posix)(t.mountpoint);if(!i.normalize().startsWith(n.normalize()))return;const u=(0,s.ensurePrefix)(i.slice(n.length),"/");return d.URI.from({scheme:a.PS_LOCAL_FILE_SCHEME,authority:(0,h.volsha)(t.uuid),path:u})},t.joinMountpoint=f,t.psfile2nativePath=async function(e,t){if(e.scheme!==a.PS_LOCAL_FILE_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,r.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=u.isPosix?n.win32.sep:n.posix.sep,s=(0,r.notBlank)(t)&&!t.includes(i);if(s&&!(0,r.blank)(t)){const i=await(0,c.bestVolumeForPath)(t);if(null!=i?.uuid&&(0,h.volsha)(i.uuid)===e.authority)return f(i.mountpoint,e.path)}const o=await(0,c.bestVolumeForVolsha)(e.authority);return null!=o?f(o.mountpoint,e.path):s&&(0,r.notBlank)(t)?f(t,e.path):void 0}},5696:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pslib2nativePath=t.nativePath2pslib=t.PSLIB_ROOT_URI=void 0;const n=i(40958),r=i(22573),s=i(51926),a=i(89937),o=i(87290),l=i(29882),u=i(95696),c=i(28874),d=i(34238);t.PSLIB_ROOT_URI=d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:""}),t.nativePath2pslib=function(e){if((0,r.blank)(e))return;const t=c.Settings.libraryDir.valueOrDefault;if((0,r.blank)(t))return;const i=(0,n.uniq)([t,(0,o.libraryOriginalsDirPosixFile)()]).find((t=>(0,l.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0})));if(null==i)return;const u=(0,s.ensurePrefix)((0,l.posixPathFrom)(i,e),"/");return d.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:u})},t.pslib2nativePath=function(e){if(e.scheme!==a.PS_LIBRARY_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");const t=(0,o.libraryOriginalsDirPosixFile)();if(null==t)throw new Error("invalid URI: "+e+" (no library set)");const i=(0,s.stripPrefix)(e.path,"/"),n=t.join(i);if(n.isFileSync())return n.nativePath;if(!t.eql(c.Settings.libraryDir.valueOrDefault)){const e=u.PosixFile.for(c.Settings.libraryDir.valueOrDefault).join(i);if(e.isFileSync())return e.nativePath}return n.nativePath}},12228:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.psnet2nativePath=t.nativePath2psnet=void 0;const a=s(i(76760)),o=i(22573),l=i(89937),u=i(59455),c=i(81168),d=i(78133),h=i(16287),f=i(96128),m=i(43334),p=i(7014),g=i(34238);t.nativePath2psnet=async function(e,t){if(!(0,o.blank)(e))return t??(t=await(0,p.bestVolumeForPath)(e)),null!=t&&!0===t.remote&&(0,o.notBlank)(t.remoteHost)&&(0,o.notBlank)(t.remoteShare)?g.URI.from({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME,authority:t.remoteHost,path:a.posix.join("/"+t.remoteShare,(0,c.stripPrefix)((0,d.native2posix)(e),(0,d.native2posix)(t.mountpoint)))}):e.startsWith("\\\\")?g.URI.file(e).with({scheme:l.PS_NETWORK_FILESYSTEM_SCHEME}):void 0},t.psnet2nativePath=async function(e,t){if(e.scheme!==l.PS_NETWORK_FILESYSTEM_SCHEME)throw new Error("invalid URI: "+e+" (bad scheme)");if((0,o.blank)(e.authority))throw new Error("invalid URI: "+e+" (missing authority)");const i=e.path.split("/").slice(1),n=i[0];if((0,o.blank)(n))throw new Error("invalid URI: "+e+" (missing share)");if(m.isWin)return`\\\\${e.authority}\\${i.join(a.sep)}`;const r=i.slice(1),s=await(0,p.volumes)();for(const t of(0,u.toA)(s))if(!0===t.remote&&(0,c.equalsIgnoreCase)(t.remoteShare,n)&&await(0,f.isEquivalentHost)(e.authority,t.remoteHost))return a.join(t.mountpoint,...r);return await(0,h.isReadableDirectory)(t)?a.join(t,...r):void 0}},85087:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const n=i(22573),r=i(42659),s=i(9103),a=i(37628);t.volsha=(0,s.memoize)((e=>(0,n.mapNotBlank)(e,a.shortStringSha)),{maxSize:128,ttlMs:r.minuteMs})},60865:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const n=i(37805),r=i(30577);t.channel=function(){return(0,r.extractUpdateChannel)(n.version)},t.baseVersion=()=>[n.versionMajor,n.versionMinor,n.versionPatch].join("."),t.versionMajorMinor=n.versionMajor+"."+n.versionMinor},76280:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toSemver=t.semverSatisfies=t.debianVersionToSemver=void 0;const n=i(38064),r=i(22573),s=/^(?:\d+:)?[vn]?(?\d+)(?\.\d+)?(?\.\d+)?/;function a(e){if(e instanceof n.SemVer)return e.version;const t=s.exec(e??"")?.groups;return null==t?void 0:t.major+(t.minor??".0")+(t.patch??".0")}t.debianVersionToSemver=a,t.semverSatisfies=function(e,t){if((0,r.blank)(e))return!1;const i={loose:!0,includePrerelease:!0};if((0,n.satisfies)(e,t,i))return!0;const s=a(e);return null!=s&&(0,n.satisfies)(s,t,i)},t.toSemver=function(e){try{return e instanceof n.SemVer?e:(0,n.parse)(e,{loose:!0})??void 0}catch{return}}},30577:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const n=i(50989);t.UpdateChannels=(0,n.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const i of t.UpdateChannels.values)if(e.includes("-"+i))return i;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},8540:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mightBeAssetMountpoint=void 0;const n=i(40958),r=i(9595),s=i(29882),a=i(43334),o=i(28874);t.mightBeAssetMountpoint=function(e){for(const t of(0,n.compactBlanks)([o.Settings.libraryDir.valueOrDefault,(0,r.originalsDir)(),...o.Settings.scanPaths.values]))if((!a.isPosix||!(0,s.pathIsRoot)(t))&&(0,s.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))return!0;return!1}},1485:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const n=i(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,n.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},50424:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dfPosix=t.acceptPosixVolume=void 0;const n=i(19851),r=i(22573),s=i(59455),a=i(50213),o=i(88158),l=i(66430),u=i(45969),c=i(28874),d=i(8540),h=i(69108),f=i(68884),m=i(98770),p=i(59107),g=i(69375),y=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.DfPosix"))),v=(0,m.lazyFsAsync)("localMountpoints",(async()=>(await(0,h.dfPosixRaw)({localsOnly:!0,paths:await(0,p.mountpoints)()}))?.map((e=>e.mountpoint))));function w(e){const t=!(0,d.mightBeAssetMountpoint)(e.mountpoint),i=null!=e.filesystem&&(0,g.isExcludedFilesystem)(e.filesystem),n=(0,g.isExcludedMountpoint)(e.mountpoint),r=!!c.Settings.validateMountpoints.valueOrDefault&&!(0,l.isReadableDirectorySync)(e.mountpoint),s=t&&(i||n||r);return y().tap({msg:"acceptPosixVolume()",result:!s,meta:{volume:e,notAssetMountpoint:t,excludedFS:i,excludedMP:n,excludedDir:r}})}t.acceptPosixVolume=w,t.dfPosix=async function(){const e=(0,u.isDocker)()?await(0,p.mountpoints)():void 0,t=await(0,h.dfPosixRaw)({paths:e});if(null==t)return;const i=(0,s.toA)(await v());if(t.forEach((e=>{var t;e.remote=!i.includes(e.mountpoint)||(t=e.filesystem,(0,r.notBlank)(t)&&c.Settings.remoteFilesystemTypes.values.includes(t))})),await(0,f.isGioSupported)())for(const e of(0,s.toA)(await(0,f.gioVolumes)())){const i=t.find((t=>t.mountpoint===e.mountpoint));null==i?t.push(e):(y().info("Merging GIO and df volume",{dfVol:i,gioVol:e}),(0,o.assignMissingPrimitives)(i,e))}return t.filter(w)}},69108:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseDfVolume=t.parseDfVolumes=t.dfPosixRaw=t.dfPosixRawLocal_=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(31586),o=i(12168),l=i(53507),u=i(50213),c=i(84777),d=i(43334),h=i(63870),f=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.DfPosixRaw")));function m(e){return(0,a.toInt)(e,{defaultValue:0})*o.KiB}function p(e){const t=(0,l.parseFixed)(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],e);return(0,r.compact)(t.map((e=>g(e))))}function g(e){const t=e.Filesystem,i=e["Mounted on"],n=m(e["1024-blocks"])??0;if(0===n)return void f().info("parseDfVolume(): skipping (size is 0)",{vol:e});const r=m(e.Used)??0,s=m(e.Available)??0;if(0!==r||0!==s)return{filesystem:t,mountpoint:i,size:d.isMac?r+s:n,used:r,available:s};f().info("parseDfVolume(): skipping (used and available is 0)",{vol:e,size:n,used:r,available:s})}t.dfPosixRawLocal_=async function(){return(0,c.stdout_)("df",["-l","-k","-P"],{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!1,ignoreExitCode:!1})},t.dfPosixRaw=async function({localsOnly:e,paths:t,output:i}={}){const n=["-k","-P"];if(!0===e&&n.push("-l"),n.push(...(0,r.compactBlanks)(t)),i??(i=await(0,c.stdout_)("df",n,{timeoutMs:(0,h.commandTimeoutMs)(),ignoreStderr:!0,ignoreExitCode:!0})),(0,s.blank)(i))return f().warn("empty output",{localsOnly:e,paths:t}),[];f().debug("output",{localsOnly:e,paths:t,output:i});const a=p(i);return!0===e&&a.forEach((e=>e.remote=!1)),a},t.parseDfVolumes=p,t.parseDfVolume=g},48165:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.volumeInfoWin=t.parseGetVolumeRow=t.getLocalVolumesWin_=t.getVolumeCommand=t.getPsDriveCommand=t.normalizeDriveLetter=t.dfWin=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(22573),o=i(96249),l=i(55835),u=i(31586),c=i(68708),d=i(51926),h=i(59455),f=i(54993),m=i(50213),p=i(81168),g=i(56519),y=i(8769),v=i(24399),w=i(28874),S=i(24541),b=i(60224),P=i(63870),M=(0,n.lazy)((()=>(0,m.mkLogger)("volumes.DfWin")));t.dfWin=async function(){return(await I()).filter((e=>!1!==e.ok&&(0,u.gt0)(e.size)))};const _=/([a-z]+)(?::\\)?/i;function E(e){return e?.match(_)?.[1]?.toUpperCase()}function x(e){return(0,l.map)(E(e),(e=>e+":\\"))}function T(e){return`Get-PSDrive -PSProvider FileSystem ${(0,f.toS)(E(e))} | Select-Object -Property Root,DisplayRoot,Description,Used,Free`}function D(e){return null!=e&&!(0,a.blank)(e.Root)&&(0,u.gte0)(e.Free)&&(0,u.gte0)(e.Used)?(0,c.compactBlankValues)({mountpoint:(0,d.ensureSuffix)(e.Root,":\\").toUpperCase(),label:e.Description,size:e.Used+e.Free,used:e.Used,available:e.Free,remote:(0,a.notBlank)(e.DisplayRoot),...(0,l.map)((0,b.parseRemoteName)(e.DisplayRoot),(e=>({remoteHost:e.host,remoteShare:e.share})))}):void 0}function k(e){return`Get-Volume ${(0,f.toS)(E(e))} | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus,UniqueId`}t.normalizeDriveLetter=x,t.getPsDriveCommand=T,t.getVolumeCommand=k,t.getLocalVolumesWin_=function(){return v.PowerShell.instance().executeJsonToA(k())};const C=/\{([-a-z\d]{7,})\}/i;function F(e,t){return e=e?.trim(),(0,a.blank)(e)||(0,p.equalsIgnoreCase)(e,t)?void 0:e}function O(e){if(null==e.DriveLetter||"null"===e.DriveLetter||"System Reserved"===e.FileSystemLabel)return void M().debug("parseGetVolumeRow(): skipping system recovery volume",{o:e});const t=x(e.DriveLetter);if(null==t)return void M().debug("parseGetVolumeRow(): skipping volume: invalid DriveLetter",{o:e});const i=(0,r.compact)([F(e.HealthStatus,"healthy"),F(e.OperationalStatus,"OK")]).join("; "),n=null!=e.Size&&null!=e.SizeRemaining&&(0,a.notBlank)(e.DriveLetter)&&(0,a.blank)(i);return M().tap({msg:"parseGetVolumeRow()",result:{mountpoint:t,filesystem:e.FileSystem,label:e.FileSystemLabel,uuid:(s=e.UniqueId,M().tap({msg:"uniqueId2uuid",result:(0,l.map)(C.exec((0,f.toS)(s)),(e=>e[1])),meta:{s}})),size:e.Size,used:e.Size-e.SizeRemaining,available:e.SizeRemaining,remote:!1,ok:n,status:i},meta:{input:e}});var s}async function I(){const e=(0,r.uniq)((0,h.toA)(await(0,S.mountpointsWin)()).map(x)),t=await(0,g.mapAsync)({name:"volumeInfoWin.psDrivesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(T(e)).catch((t=>((0,y.onError)("volumeInfoWin(): Get-PSDrive failed for drive "+e,{error:t}),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),i=(0,r.compact)((0,o.flatten)(t).map(D)),n=await(0,g.mapAsync)({name:"volumeInfoWin.volumesJson",arr:e,f:e=>v.PowerShell.instance().executeJsonToA(k(e)).catch((t=>(M().debug("volumeInfoWin(): Get-Volume failed for drive "+e,t),[]))),maxConcurrent:w.Settings.powerShellProcs.valueOrDefault,timeoutMs:(0,P.commandTimeoutMs)()}),a=(0,r.compact)((0,o.flatten)(n).map(O)),l=(0,r.uniq)([...i,...a].filter((e=>!1===e.ok)).map((e=>e.mountpoint))),u=(0,s.sort)((0,r.uniq)([...i,...a].map((e=>e.mountpoint))).filter((e=>!l.includes(e))));M().info("volumeInfoWin()",{psDriveVols:i,getVolumesVols:a,healthyMountpoints:u,unhealthy:l});const c=u.map((e=>({...i.find((t=>e===t.mountpoint)),...a.find((t=>e===t.mountpoint))})));return c.forEach((e=>{l.includes(e.mountpoint)&&(e.ok=!1),e.ignorable=!0===e.ignorable||!1===e.ok})),c}t.parseGetVolumeRow=O,t.volumeInfoWin=I},68884:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gioVolumes=t.GioMountMonitorArgs=t.GioCommand=t.isGioSupported=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(97790),c=i(50213),d=i(23560),h=i(45255),f=i(81168),m=i(1728),p=i(56519),g=i(4867),y=i(84777),v=i(83278),w=i(8103),S=i(16287),b=i(45969),P=i(43334),M=i(69108),_=i(98770),E=i(44224),x=i(63870);t.isGioSupported=(0,n.lazy)((async()=>{if(!P.isLinux||(0,b.isDocker)()||(0,d.isBillingService)()||null==await(0,w.pathTo)({tool:t.GioCommand}))return!1;try{return 0===(await(0,y.stdoutResult_)(t.GioCommand,["version"],{timeoutMs:(0,x.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}})),t.GioCommand="gio",t.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const T=(0,n.lazy)((()=>(0,c.mkLogger)("volumes.Gio")));t.gioVolumes=(0,n.lazy)((async()=>(0,g.thenOrTimeoutError)({p:async()=>{if(!await(0,t.isGioSupported)())return;const e=await async function(){return await(0,t.isGioSupported)()?T().tap({msg:"gvfsFuseDirectories()",result:await(0,p.thenFlatten)(await(0,p.thenMap)((0,E.readProcMounts)(void 0,(e=>"gvfsd-fuse"===e),S.isReadableDirectory),(e=>e.map((e=>v.BaseFile.for(e).clear().childDirectories())))))}):T().tap({msg:"gvfsFuseDirectories(): gio is not supported",result:[]})}();return(0,r.isEmpty)(e)?[]:(T().info("gioVolumes()",{fuseDirs:e}),(0,p.mapAsyncSerial)({arr:e,name:"gioVolumes",timeoutMs:(0,x.mountpointsTtlMs)(),f:async e=>{const t=await(0,M.dfPosixRaw)({paths:[e.nativePath]}),i=t?.[0];if(null==i||!e.nativePath.startsWith(i.mountpoint))return void T().warn("df failed to find "+e,{vols:t});i.mountpoint=e.nativePath;const n=await D(i.mountpoint);return null==n?i:{remote:!0,...i,...n}}}))},timeoutMs:(0,x.mountpointsTtlMs)()}))),(0,o.later)((()=>(0,_.setupVolumeTTL)(t.gioVolumes)));const D=(0,m.memoizeAsync)((async e=>{try{const i=(await(0,y.stdout_)(t.GioCommand,["info",e],{timeoutMs:(0,x.commandTimeoutMs)()})).split(/[\r\n]+/),n=(0,s.mapNotBlank)(i.find((e=>e.startsWith("uri: "))),(e=>new URL((0,f.stripPrefix)(e,"uri: "))));return{displayName:(0,l.map)(i.find((e=>e.startsWith("display name: "))),(e=>(0,f.stripPrefix)(e,"display name: "))),remoteHost:(0,l.map)(n,(e=>e.hostname)),remoteShare:(0,u.opt)(n).flatMap((e=>e.pathname)).flatMap((e=>(0,f.stripPrefix)(e,"/"))).flatMap((e=>(0,f.stripSuffix)(e,"/"))).flatMap(decodeURIComponent).filter(s.notBlank).get()}}catch(t){return void T().warn("getRemoteInfo(): info failed",{mountpoint:e,err:t})}}),{name:"gio.getRemoteInfo",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},98770:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setupVolumeTTL=t.lazyFsAsync=void 0;const n=i(19851),r=i(5233),s=i(41400),a=i(56038),o=i(70025),l=i(34102),u=i(28874),c=i(59107),d=i(63870);function h(e){e.setTTL(u.Settings.volumeMetadataTtlMs.valueOrDefault),u.Settings.volumeMetadataTtlMs.watchLater((t=>e.setTTL(t)))}t.lazyFsAsync=function(e,t,i){const u=(0,n.lazy)((()=>(0,a.time)("volumes."+e,(()=>(0,r.retryOnReject_)(t,{maxRetries:2,timeoutMs:(0,d.commandTimeoutMs)(),errorIsRetriable:e=>!1!==(0,o.isRetriableError)(e)&&!1!==(0,o.isIgnorableError)(e)})))),i);return(0,s.later)((()=>{c.mountpoints.watchLater((()=>u.unset())),(0,l.ee)().on("clearCache",(()=>u.unset())),null==i&&h(u)})),u},t.setupVolumeTTL=h},27461:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.localVolumes_blkid_=t.localVolumes_lsblk_=t.addLocalVolumeInfoLinux=void 0;const n=i(19851),r=i(40958),s=i(22573),a=i(31586),o=i(50213),l=i(88158),u=i(45255),c=i(81168),d=i(84777),h=i(6012),f=i(84542),m=i(68284),p=i(57902),g=i(45969),y=i(69108),v=i(98770),w=i(63870),S=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.LocalVolumesLinux")));t.addLocalVolumeInfoLinux=async function(e){if((0,g.isDocker)())return;const i=await(0,t.localVolumes_lsblk_)().catch((e=>S().warn("lsblk failed",{error:e}))),n=await(0,t.localVolumes_blkid_)().catch((e=>S().warn("blkid failed",{error:e})));if(null==i&&null==n)return;const s=(0,c.sortIgnoreCase)((0,r.uniq)([...(i??[]).filter((e=>!e.ignorable)).map((e=>e.mountpoint)),...e.map((e=>e.mountpoint))])),a=[];for(const t of s){const r=e.find((e=>e.mountpoint===t)),s=i?.find((e=>e.mountpoint===t)),o={...r,...s},u=n?.find((e=>e.filesystem===o.filesystem));if(null!=u&&(0,l.assignMissingPrimitives)(o,u),null==o.size||null==o.available){const e=(await(0,y.dfPosixRaw)({localsOnly:!1,paths:[t]}))?.[0];S().info("backfilling mountpoint",{info:s,vol:r,df:e}),null!=e&&(0,l.assignMissingPrimitives)(o,e)}a.push(o)}return a};const b=/lsblk from util-linux ([\d.]+)$/i,P=(0,n.lazy)((async()=>{const e=await(0,d.stdout_)("lsblk",["--version"],{timeoutMs:u.ShortCommandTimeoutMs});return b.exec(e)?.[1]?.split(".").map((e=>(0,a.toInt)(e)))})),M=(0,n.lazy)((async()=>{const e=["mountpoint","label","uuid"],t=await P();return null!=t&&(0,a.gte)(t[0],2)&&(0,a.gte)(t[1],34)&&e.push("fsused","fsavail"),e.join(",")}));t.localVolumes_lsblk_=(0,v.lazyFsAsync)("localVolumes_lsblk",(async()=>{const e=await(0,d.stdout_)("lsblk",["-P","-b","--output",await M()],{timeoutMs:(0,w.commandTimeoutMs)()}),t=(0,f.splitLines)(e).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!0}))).filter((e=>null!=e)).map((e=>{const t=(0,s.blank)(e.mountpoint)||e.mountpoint.startsWith("/snap/")||"/boot"===e.mountpoint||e.mountpoint.startsWith("/boot/")||!(0,m.isDirectorySync)(e.mountpoint),i=(0,a.toInt)(e.fsused),n=(0,a.toInt)(e.fsavail);return{mountpoint:e.mountpoint,label:e.label,uuid:e.uuid,ignorable:t,...null!=i&&null!=n?{used:i,available:n,size:i+n}:void 0,...(0,g.isDocker)()?void 0:{remote:!1}}}));return S().tap({msg:"localVolumes_lsblk",level:p.LogLevels.trace,result:t})}),0),t.localVolumes_blkid_=(0,v.lazyFsAsync)("localVolumes_blkid",(async()=>(await(0,d.stdout_)("blkid",["-o","export"],{timeoutMs:(0,w.commandTimeoutMs)()})).split(/\n{2,}/).map((e=>(0,h.parseEnvTokens)({input:e,lowerCaseKeys:!1}))).filter((e=>!0===e?.DEVNAME?.includes("/"))).map((e=>({filesystem:e.DEVNAME,label:(0,s.toNotBlank)(e.PARTLABEL)??(0,s.toNotBlank)(e.LABEL),uuid:(0,s.toNotBlank)(e.PARTUUID)??(0,s.toNotBlank)(e.UUID)})))),0)},66840:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mnt2uuidMac=t.addLocalVolumeInfoMac=void 0;const n=i(57272),r=i(19851),s=i(40958),a=i(22573),o=i(38639),l=i(55835),u=i(20214),c=i(59455),d=i(50213),h=i(56519),f=i(4867),m=i(84777),p=i(69108),g=i(98770),y=i(63870),v=(0,r.lazy)((()=>(0,d.mkLogger)("volumes.LocalVolumesMac")));t.addLocalVolumeInfoMac=async function(e){return(0,u.thenMap)((0,t.mnt2uuidMac)(),(t=>e.map((e=>(0,l.mapOr)(t.get(e.mountpoint),(t=>({...e,...t})),(()=>e))))))},t.mnt2uuidMac=(0,g.lazyFsAsync)("mnt2uuidMac",(async function(){const e=await(0,p.dfPosixRaw)({localsOnly:!0}),t=(0,s.uniq)(e.map((e=>e.filesystem?.match(w)?.[1]))),i=Math.round((0,y.commandTimeoutMs)()/3),r=await(0,h.mapAsyncSerial)({name:"_mnt2uuidMac()",arr:t,f:async e=>(0,f.thenOrTimeoutError)({p:(0,m.stdout_)("diskutil",["list","-plist",e],{timeoutMs:i}),timeoutMs:i})}),l=new Map;for(const e of r)try{const t=(0,n.parse)(e);for(const e of(0,c.toA)(t.AllDisksAndPartitions))for(const t of(0,c.toA)(e.APFSVolumes))(0,a.blank)(t.MountPoint)||(0,o.isTrue)(t.OSInternal)?v().debug("skipping",t):l.set(t.MountPoint,{filesystem:"/dev/"+t.DeviceIdentifier,label:t.VolumeName,size:t.Size,uuid:t.VolumeUUID})}catch(t){v().warn("Failed to parse diskutil output",{err:t,out:e})}return l}),0);const w=/^(\/dev\/disk\d+)/},59107:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findmntPoll=t.gioMountMonitor=t.diskUtilActivity=t.isPosixMountpoint=t.mountpoints=t.mountpoints_=t.localMountpointSetup=void 0;const n=i(19851),r=i(40958),s=i(76790),a=i(42659),o=i(41400),l=i(13538),u=i(50213),c=i(7282),d=i(409),h=i(23560),f=i(45255),m=i(81168),p=i(27395),g=i(56519),y=i(56038),v=i(84777),w=i(34330),S=i(8769),b=i(34102),P=i(17217),M=i(16287),_=i(43334),E=i(28874),x=i(8540),T=i(68884),D=i(44224),k=i(24541),C=i(69375),F=i(63870),O=(0,n.lazy)((()=>(0,u.mkLogger)("volumes.Mountpoints")));function I(){t.mountpoints.unset(),t.mountpoints_.unset()}function L(e=(0,F.mountpointsTtlMs)()){t.mountpoints.setTTL(e),t.mountpoints_.setTTL(e)}async function A(){I()}t.localMountpointSetup=(0,n.lazy)((async()=>{E.Settings.libraryDir.watchLater(I),E.Settings.scanPaths.watchLater(I),(0,h.isSyncService)()&&E.Settings.scanAllDrives.valueOrDefault?(0,o.later)((async()=>{const e=(0,u.mkLogger)("Mountpoints.localMountpointSetup()");if(_.isMac&&(e.info("Setting up Mac diskutil activity watcher"),L((0,F.volumeMetadataTtlMs)()),(0,t.diskUtilActivity)()),_.isLinux){const i=(0,D.maybeWatchProcMounts)();await(0,T.isGioSupported)()&&(e.info("Setting up Linux gio mount monitor"),L((0,F.volumeMetadataTtlMs)()),(0,t.gioMountMonitor)()),null==i&&await N()&&(e.info("Setting up Linux findmnt mount monitor"),L((0,F.volumeMetadataTtlMs)()),(0,t.findmntPoll)())}}),a.minuteMs):await(0,g.awaitAll)([(0,p.end)(t.diskUtilActivity.clear()),(0,p.end)(t.gioMountMonitor.clear()),(0,p.end)(t.findmntPoll.clear())])}));const R=(0,n.lazy)((()=>{}));t.mountpoints_=(0,n.lazy)((async()=>{{const e=E.Settings.mountpoints.values;if((0,r.isNotEmpty)(e))return e}const e=await(0,l.thenOrTimeoutError)((0,y.time)("volumes.Mountpoints",_.isWin?k.mountpointsWin:D.mountpointsPosix),f.ShortCommandTimeoutMs);if((0,r.isEmpty)(e))return O().throw("mountpointsImpl() returned empty.",{fatal:!1});{const t=(0,s.sort)(await(0,g.filterAsync)({arr:e,name:"mountpointFilter",timeoutMs:(0,F.commandTimeoutMs)(),f:async e=>!(!(0,x.mightBeAssetMountpoint)(e)&&(0,C.isExcludedMountpoint)(e)||E.Settings.validateMountpoints.valueOrDefault&&!await(0,M.isReadableDirectory)(e)&&(O().warn(`mountpoint ${e} is not readable`),1))}));return R.set(t),t}})),t.mountpoints=(0,n.lazy)((async()=>{try{return await(0,t.mountpoints_)()}catch(e){return(0,S.onError)("mountpoints() failed",{cause:e}),R()}})),t.isPosixMountpoint=async function(e){if(_.isWin)return!1;const i=await(0,t.mountpoints)()??[],n=(0,P.toNativePath_)(e);return _.isMac?(0,m.includesIgnoreCase)(i,n):i.includes(n)},(0,o.later)((()=>{(0,b.ee)().on("clearCache",(()=>{T.gioVolumes.unset(),I()})),E.Settings.mountpointsTtlMs.watch(L)}),(0,c.isTest)()?1:a.minuteMs),t.diskUtilActivity=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"diskutil",args:["activity"],onStdout:(0,d.rateLimited)({name:"diskUtilActivity",f:()=>A(),minCallDelayMs:1.5*a.secondMs})}))),t.gioMountMonitor=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:T.GioCommand,args:T.GioMountMonitorArgs,onStdout:(0,d.rateLimited)({name:"gioMountMonitor",f:()=>(T.gioVolumes.unset(),A()),minCallDelayMs:f.ShortCommandTimeoutMs})})));const N=(0,n.lazy)((async()=>{if(!_.isLinux)return!1;try{return 0===(await(0,v.stdoutResult_)("findmnt",["--version"],{timeoutMs:(0,F.commandTimeoutMs)(),ignoreStderr:!0})).code}catch(e){return!1}}));t.findmntPoll=(0,n.lazy)((()=>(0,w.mkBasicWatchedChild)({cmd:"findmnt",args:["--poll"],onStdout:(0,d.rateLimited)({name:"findmntPoll",f:()=>A(),minCallDelayMs:f.ShortCommandTimeoutMs})})))},44224:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.maybeWatchProcMounts=t.readProcMounts=t.defaultFilesystemTypePredicate=t.mountpointsPosix=void 0;const n=i(19851),r=i(40958),s=i(42659),a=i(48884),o=i(50213),l=i(23560),u=i(81168),c=i(56519),d=i(73614),h=i(73787),f=i(55690),m=i(16287),p=i(68284),g=i(57902),y=i(43334),v=i(28874),w=i(69108),S=i(68884),b=i(59107),P=i(69375),M=(0,n.lazy)((()=>(0,o.mkLogger)("volumes.MountpointsPosix")));t.mountpointsPosix=async function(){const e=await T()??await(0,c.thenMap)((0,w.dfPosixRaw)({localsOnly:!1}),(e=>e.map((e=>e.mountpoint))));if(null!=e&&await(0,S.isGioSupported)())try{await(0,c.thenMap)((0,S.gioVolumes)(),(t=>e.push(...t.map((e=>e.mountpoint)))))}catch(e){M().warn("Failed to fetch gio volumes",e)}return e};const _="/proc/mounts";function E(e){return!v.Settings.excludedFilesystemTypes.has(e)}function x(e){return!(0,P.isExcludedMountpoint)(e)&&(!v.Settings.validateMountpoints.valueOrDefault||(0,m.isReadableDirectory)(e))}async function T(e=_,t=E,i=x){if(y.isLinux)try{const n=await(0,f.readLines_)(e),s=(0,r.compact)(n.map((e=>{const[t,i]=e.split(/\s+/);return(0,a.allNotBlank)(t,i)?[t,(0,u.unoctal)(i)]:void 0}))),o=await(0,c.filterAsync)({name:"mountpoints filter",arr:s,f:async([e,n])=>{const r=t(e),s=await i(n);return M().tap({level:g.LogLevels.trace,msg:"readProcMounts().predicate filters",result:r&&s,meta:{fs:e,mp:n,fsOK:r,mpOK:s}})}});return M().tap({msg:"readProcMounts()",result:o.map((([,e])=>e)),meta:{procMounts:e}})}catch(e){return void M().info("Failed to read /proc/mount",e)}}t.defaultFilesystemTypePredicate=E,t.readProcMounts=T,t.maybeWatchProcMounts=(0,n.lazy)((()=>y.isLinux&&(0,l.isSyncService)()&&!(0,p.isEmptyFileSync)(_)?new h.FileWatcher(_,{recursive:!1,persistent:!1},(()=>{M().info("detected change in "+_),(0,d.setUnrefTimeout)((()=>b.mountpoints.refresh()),s.secondMs)})):void 0))},24541:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mountpointsWinFsutil=t.mountpointsWinPwsh=t.mountpointsWin=void 0;const n=i(19851),r=i(42659),s=i(13538),a=i(50213),o=i(45255),l=i(81168),u=i(84777),c=i(8103),d=i(24399),h=(0,n.lazy)((()=>(0,a.mkLogger)("volumes.MountpointsWin")));async function f(){const e=await d.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root");return null==e?void 0:(0,l.sortIgnoreCase)(e.map((e=>e.Root)))}t.mountpointsWin=(0,n.lazy)((async()=>{try{return await(0,s.thenOrTimeoutError)(f(),o.ShortCommandTimeoutMs)}catch(e){return h().warn("mountpointsWinPwsh()",{error:e}),p()}})),t.mountpointsWinPwsh=f;const m=/\s([A-Z]:\\)/g;async function p(){const e=await(0,u.stdout_)((0,c.fsutil)(),["fsinfo","drives"],{timeoutMs:10*r.secondMs}),t=[];let i;for(;null!==(i=m.exec(e));)t.push(i[1]);return(0,l.sortIgnoreCase)(t)}t.mountpointsWinFsutil=p},69375:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const n=i(19851),r=i(22573),s=i(50213),a=i(9103),o=i(7282),l=i(29882),u=i(43334),c=i(28874),d=(0,n.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,r.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,o.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,o.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,o.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,p=u.isLinux||(0,o.isTest)()?/^\/var\/lib\//:void 0;function g(e){if((0,r.blank)(e))return"blank";const t=(0,l.toPathnames)(e),i=t[0],n=t[t.length-1];return c.Settings.excludedRootDirectories.has(i)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(n)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===i&&!1===m?.test(e)?"LinuxRunRE":!0===p?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,a.memoize)((e=>{if(u.isWin)return!1;const t=g(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=g},70313:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRemote=t.addRemoteVolumeInfoPosix=t.nfsRe=void 0;const n=i(22573),r=/\/\/(?.+@)?(?[^/@]+)\/(?.+)/,s=/(?:\._(?:smb|afs|nfs|tcp|afpovertcp))+/i;function a(e){if((0,n.blank)(e))return;const i=r.exec(e)?.groups;if(null!=i&&!(0,n.blank)(i.remoteHost)&&!(0,n.blank)(i.remoteShare))return{remoteHost:i.remoteHost.replace(s,""),remoteShare:i.remoteShare};const a=t.nfsRe.exec(e);if(null!=a){const e=a[1],t=a[2];if(!(0,n.blank)(e)&&!(0,n.blank)(t))return{remoteHost:e,remoteShare:t}}}t.nfsRe=/^([^:\s]+):(\/.*)$/,t.addRemoteVolumeInfoPosix=function(e){for(const t of e)if(!0===t.remote){const e=a(t.filesystem);null!=e&&(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare)}return e},t.parseRemote=a},60224:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._netInfoWinWmic=t.parseRemoteName=t.NetInfoCmd=t.addRemoteVolumeInfoWin=void 0;const n=i(40958),r=i(22573),s=i(42659),a=i(55835),o=i(97790),l=i(54993),u=i(53507),c=i(56639),d=i(88158),h=i(81168),f=i(84777),m=i(38835),p=i(8103),g=i(43334),y=i(24399),v=i(98770);t.addRemoteVolumeInfoWin=async function(e,t){if(!g.isWin)throw new Error("unsupported platform"+m.InternalErrorFlag);const i=(0,c.toMap)(t??await E()??[],(e=>[e.mountpoint,e]));return e.forEach((e=>{(0,a.map)(i.get(e.mountpoint),(t=>{e.remote=!0,e.remoteHost=t.host,e.remoteShare=t.share,e.ok=t.ok}))})),e};const w=["LocalName","RemoteName","Status"],S=["NETUSE","get",w.join(",")],b=/^\\\\([^\\]+)\\(.+)$/,P=/^[a-z]:\\?$/i;function M(e){if(!(0,r.blank)(e))return(0,o.opt)(e).flatMap((e=>b.exec(e))).map((e=>({host:e[1],share:e[2]}))).orElse((()=>(0,o.opt)(e).flatMap((e=>(0,d.Try)((()=>new URL(e))))).filter((e=>(0,r.notBlank)(e.hostname))).map((e=>({host:e.hostname,share:(0,o.opt)(e.pathname).filter(r.notBlank).getOrElse((()=>"/"))}))))).get()}async function _(){const e=(0,p.wmic)(),t=await(0,f.stdout_)(e,S,{timeoutMs:15*s.secondMs}),i=(0,u.parseFixed)(w,t);return(0,n.compact)(i.map((e=>(0,a.map)(b.exec((0,l.toS)(e.RemoteName)),(t=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(i=>({mountpoint:(0,h.ensureSuffix)(i[0],"\\"),host:t[1],share:t[2],ok:"OK"===e.Status}))))))))}t.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",t.parseRemoteName=M,t._netInfoWinWmic=_;const E=(0,v.lazyFsAsync)("netInfoWin",(async function(){const e=await y.PowerShell.instance().executeJsonToA(t.NetInfoCmd);return null==e?_():(0,n.compact)(e.filter((e=>(0,r.notBlank)(e.LocalName))).map((e=>(0,a.map)(M(e.RemoteName),(({host:t,share:i})=>(0,a.map)(P.exec((0,l.toS)(e.LocalName)),(n=>({mountpoint:(0,h.ensureSuffix)(n[0],"\\"),host:t,share:i,ok:"OK"===e.Status&&"Connected"===e.ConnectionState}))))))))}),0)},63870:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const n=i(42659),r=i(12168),s=i(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=r.MiB/n.secondMs},86848:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readVolumeUUID=t.readUuidFile_=t.toVolumeUUID=t.volumeUuidNotExpected=t.addVolumeUUIDs=void 0;const n=i(76760),r=i(19851),s=i(22573),a=i(38639),o=i(41400),l=i(13538),u=i(80049),c=i(50213),d=i(7282),h=i(81168),f=i(42638),m=i(34102),p=i(83278),g=i(84542),y=i(85772),v=i(95696),w=i(45969),S=i(28874),b=i(59107),P=i(63870),M=i(68995),_=(0,r.lazy)((()=>(0,c.mkLogger)("volumes.VolumeUUID"))),E=(0,r.lazy)((()=>new u.FifoCacheAsync({name:"volumes.VolumeUUID",maxSize:500,timeoutMs:(0,P.commandTimeoutMs)()})));function x(e){return(0,a.isTrue)(e.ignorable)||(0,w.isDocker)()&&"/"===e.mountpoint||(0,d.isTest)()&&"node_modules"===(0,n.basename)(e.mountpoint)}function T(e){if((0,s.blank)(e))return;const t=(0,h.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<=8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,l.thenOrTimeoutError)(e.readTextFile_(),(0,P.commandTimeoutMs)());for(const e of(0,g.splitLines)(t)){const t=T(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function k(e){if(S.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of S.Settings.volumeUuidFilePaths.values){const i=v.PosixFile.for(e.mountpoint).join(t),n=await D(i).catch((e=>_().info("Failed to read "+i,{error:e})));if(null!=n)return _().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:n,meta:{mountpoint:e.mountpoint}})}const t=(0,n.join)(e.mountpoint,(0,M.volumeUuidSubpath)());if("/"===e.mountpoint)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(S.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,y.whyNoMediaDir)(p.BaseFile.for(e.mountpoint));if(null!=i)return _().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(S.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await(0,M.writeVolumeUuid)(e);if(!(0,s.blank)(t))return _().tap({msg:"readVolumeUUID(): wrote new "+(0,M.volumeUuidSubpath)(),result:t,meta:{volume:e}})}return _().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:e.uuid})}(0,o.later)((()=>{(0,m.ee)().on("clearCache",(()=>E.clear())),b.mountpoints.watchLater((()=>E.clear()))})),t.addVolumeUUIDs=async function(e){await(0,f.withBoundedConcurrency)({name:"addVolumeUUIDs",laters:e.map((e=>()=>(0,l.thenOrOnTimeout)(async function(e){if(x(e))return;if((0,a.isFalse)(e.ok))return;const t=await E().getOrSetAsync(e.mountpoint,(async()=>k(e)));null!=t&&(e.uuid=t)}(e),(0,P.commandTimeoutMs)(),(()=>_().warn("addVolumeUUIDs("+e.mountpoint+") timed out",{timeoutMs:(0,P.commandTimeoutMs)()})))))})},t.volumeUuidNotExpected=x,t.toVolumeUUID=T,t.readUuidFile_=D,t.readVolumeUUID=k},7014:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findVolumeForVolsha=t.bestRemoteVolume=t.remoteVolumeFor=t.bestVolumeForVolsha=t.bestVolumeForPath=t.bestMountpoint=t.rootVolume=t.rootPath=t.volumesImpl=t.volumes=t.priorVolumesIfMountpointsMatch=t.cachedVolumes=t.writeVolumesToCache=t.priorWriteVolumesToCacheLatch=t.canWriteVolumesToCache=t.clearVolumesCache=t.mountpointToVolsha=void 0;const r=n(i(48161)),s=n(i(76760)),a=i(19851),o=i(40958),l=i(76790),u=i(22573),c=i(38639),d=i(42659),h=i(41400),f=(i(50357),i(56409)),m=i(55835),p=i(31586),g=i(97790),y=i(42279),v=i(59455),w=i(48884),S=i(50213),b=i(7282),P=i(23560),M=i(28850),_=i(45255),E=i(81168),x=i(56519),T=i(4867),D=i(49776),k=i(9595),C=i(77740),F=i(44198),O=i(96706),I=i(8769),L=i(57159),A=(i(34102),i(21144)),R=i(73209),N=i(29882),B=i(95696),z=i(17217),j=i(16287),V=i(49076),W=i(96128),H=i(45969),U=i(43334),q=i(28874),G=i(85087),$=i(50424),J=i(48165),K=i(98770),Z=i(27461),X=i(66840),Y=i(59107),Q=i(70313),ee=i(60224),te=i(63870),ie=i(86848),ne=(0,a.lazy)((()=>(0,S.mkLogger)("volumes.Volumes"))),re=r.default.platform(),se=new Map,ae=new Map,oe=new Map;function le(e,t,i){if((0,u.blank)(e))return;const n=i.get(e);null!=n&&(0,p.gt)(n.updatedAt,t.updatedAt)||(i.set(e,t),(0,m.map)((0,G.volsha)(t.uuid),(e=>ae.set(t.mountpoint,e))))}function ue(e){if(null!=e)return le(e.mountpoint,e,se),le((0,G.volsha)(e.uuid),e,oe),e}function ce(){return(0,o.compact)([B.PosixFile.forMaybe((0,D.cacheDir)())?.join("volumes"),B.PosixFile.forMaybe((0,k.libraryDataDir)())?.join("volumes")])}t.mountpointToVolsha=(0,K.lazyFsAsync)("mountpointToVolsha",(async()=>(await de(),ae))),t.clearVolumesCache=async function({deleteFileCache:e=!1}={}){ne().warn("clearVolumesCache()",{deleteFileCache:e}),t.volumes.unset(),se.clear(),oe.clear(),de.unset(),t.cachedVolumes.unset(),e&&await Promise.all(ce().map((e=>e.rmrf())))};const de=(0,K.lazyFsAsync)("loadCachedVolumes",(async()=>{const e=await async function(){const e=await(0,x.mapAsync)({name:"readCachedVolumes",arr:(0,x.thenFlatten)(ce().map((e=>e.childFiles((e=>".json"===e.ext&&!e.base.startsWith(".")))))),f:e=>e.readJson()}),t=(0,l.sortBy)(e,(e=>[e.mountpoint,-e.updatedAt]));[...t.reverse()].forEach(ue);const i=(0,o.uniqBy)(t,(e=>e.mountpoint)).map((e=>({...e,fromCache:!0})));return(0,E.sortByCaseInsensitive)(i,(e=>e.mountpoint))}();return e?.forEach(ue),e}));async function he(e){if(null==e)return;const i=new f.Latch;t.priorWriteVolumesToCacheLatch.set(i);const n=Date.now(),r=e.filter((e=>!(0,c.isTrue)(e.fromCache))).map((e=>({...e,...(0,H.isDocker)()?{}:{fromHost:(0,V.cleanHostname)()},updatedAt:n,os:re}))),s=new Map;for(const e of r)for(const t of(0,o.compactBlanks)([(0,G.volsha)(e.uuid),(0,G.volsha)(e.mountpoint)]))s.set(t,e);const a=ce();for(const e of a)await(0,R.withLock_)({file:e,timeoutMs:_.ShortCommandTimeoutMs},(async()=>{for(const[t,i]of s.entries()){const n=e.join(t+".json");try{await n.writeJson_(i)}catch(e){ne().warn("writeVolumesToCache(): failed to write volumes cache",{error:e,output:n.nativePath,vol:i}),await n.unlink()}}}));ne().debug("writeVolumesToCache(): complete.",{dirs:a,vol_mountpoints:r.map((e=>e.mountpoint))}),i.resolve()}async function fe(){const e=await(0,t.cachedVolumes)();if((0,P.isWorkerService)()&&(0,o.isNotEmpty)(e))return e;const i=(0,v.toA)(await(0,Y.mountpoints)()),n=Date.now()-(0,p.clamp)(d.minuteMs,d.dayMs,q.Settings.volumeMetadataTtlMs.valueOrDefault),r=0!==q.Settings.volumeMetadataTtlMs.valueOrDefault&&e.some((e=>!(0,p.gt)(e.updatedAt,n))),s=!(0,o.eqlPrimitiveUnordered)(i,e.map((e=>e.mountpoint)));return ne().debug("priorVolumesIfMountpointsMatch()",{priorIsStale:r,priorIsMissingMountpoints:s}),r||s?void 0:e}async function me(e,i){const n=(0,m.map)(e,z.toNativePath_);if((0,u.blank)(n))return;const r=await(0,A.actualPath)(n);for(const e of[{name:"args",vols:i},{name:"cachedVolumes()",vols:t.cachedVolumes},{name:"volumes()",vols:t.volumes},{name:"allPriorVolumes()",vols:de}]){const t=await(0,y.tol)(e.vols);if((0,o.isEmpty)(t))continue;const i=(0,N.bestMountpointForDir)(r,t.map((e=>e.mountpoint)));if(null==i)continue;const n=t.find((e=>e.mountpoint===i));if(null!=n)return ne().trace("bestVolumeForPath()",{nativePath:r,result:n.mountpoint,src:e.name}),n}return ne().tap({msg:"bestVolume(): no volumes were applicable(!!)",result:void 0,meta:{nativePath:r}})}async function pe(e,t,i){const n=i.filter((e=>(0,E.equalsIgnoreCase)(t,e.remoteShare)));if((0,o.isEmpty)(n))return;const r=n.find((t=>(0,c.isTrue)(t.remote)&&(0,u.notBlank)(t.remoteHost)&&(0,E.equalsIgnoreCase)(e,t.remoteHost)));if(null!=r)return r;const s=await(0,W.friendlyname)(e);return(0,x.asyncFind)(n,(async e=>(0,E.equalsIgnoreCase)(s,await(0,W.friendlyname)(e.remoteHost))))}t.canWriteVolumesToCache=(0,a.lazy)((()=>(0,P.isSyncService)()||(0,b.isTest)())),t.priorWriteVolumesToCacheLatch=(0,a.lazy)((()=>{})),t.writeVolumesToCache=he,t.cachedVolumes=(0,a.lazy)((async()=>{const e=(0,o.compact)(await de()),t=(0,v.toA)(await(0,Y.mountpoints)()),i=e.filter((e=>t.includes(e.mountpoint))),n=(0,o.isNotEmpty)(i)?i:e.filter((e=>re===e?.os));return ne().tap({msg:"cachedVolumes()",level:"trace",result:n.filter((e=>!(0,c.isTrue)(e.ignorable))),meta:{currentMountpoints:t,withCurrentMountpoints:i.map((e=>e.mountpoint))}})}),d.minuteMs),t.priorVolumesIfMountpointsMatch=fe,t.volumes=(0,K.lazyFsAsync)("volumes",(async function(){try{const e=await(0,T.thenOrTimeoutError)({p:fe(),timeoutMs:(0,te.commandTimeoutMs)()});if(null!=e)return ne().debug("volumes(): returning prior-cached volumes"),e;const i=await(0,T.thenOrTimeoutError)({p:(0,t.volumesImpl)(),timeoutMs:(0,te.commandTimeoutMs)()});if((0,o.isNotEmpty)(i))return i}catch(e){(0,I.onError)((0,L.toWrappedError)("volumes() failed",{cause:e}))}return ne().debug("fallback: returning priorVolumes()"),(0,t.cachedVolumes)()})),t.volumesImpl=(0,M.shim0)({name:"fs.volumes",impl:async function(){if((0,b.isTest)()){const e=(0,p.toInt)((0,F.env)().PS_VOLUMES_HANG_MS);if((0,p.gt0)(e)&&(ne().warn("PS_VOLUMES_HANG_MS: delay for "+e),await(0,h.delay)(e,!1)),(0,C.getDevEnvFlag)("PS_FAIL_VOLUMES"))return void ne().throw("PS_FAIL_VOLUMES")}const e=await(0,T.thenOrTimeoutError)({p:U.isWin?(0,J.dfWin)():(0,$.dfPosix)(),timeoutMs:(0,te.mountpointsTtlMs)()});if(null==e)return void ne().warn("df failed");const t=q.Settings.validateMountpoints.valueOrDefault?(0,o.compact)(await(0,x.mapAsync)({name:"nonRpcVolumes: filter unhealthy volumes",arr:e,timeoutMs:(0,te.commandTimeoutMs)(),f:async e=>{try{if(await(0,j.isReadableDirectory)(e.mountpoint))return e;ne().info("validateMountpoints(): "+e.mountpoint+" is not a directory")}catch(t){ne().info("validateMountpoints(): failed to stat "+e.mountpoint,t)}}})):e;t.some((e=>!0===e.remote&&(0,u.blank)(e?.remoteHost)))&&await(0,T.thenOrTimeoutError)({p:U.isWin?(0,ee.addRemoteVolumeInfoWin)(t):(0,Q.addRemoteVolumeInfoPosix)(t),timeoutMs:10*d.secondMs}).catch((e=>{(0,I.onError)("Failed to get remote volume info",{error:e})}));const i=(U.isWin?t:U.isMac?await(0,X.addLocalVolumeInfoMac)(t):await(0,Z.addLocalVolumeInfoLinux)(t))??t;for(const e of i)e.updatedAt??(e.updatedAt=Date.now()),e.remote=(0,c.isTrue)(e.remote),(0,u.blank)(e.label)&&delete e.label,(0,u.mapNotBlank)(e.remoteHost,(t=>e.remoteHost=t.toLowerCase().normalize().trim()));await(0,ie.addVolumeUUIDs)(i);const n=(0,l.sortBy)(i,(e=>e.mountpoint));return ne().debug("_volumes(): final result",{sorted:n}),n.forEach(ue),await he(n),Object.freeze(n)}}),t.rootPath=(0,a.lazy)((()=>U.isWin?(0,g.opt)((0,O.getEnv)("SystemDrive")).filter(u.notBlank).orElse((()=>"C:")).map((e=>(0,E.ensureSuffix)(e,"\\"))).get():"/")),t.rootVolume=function(){return me((0,t.rootPath)())},t.bestMountpoint=function(e,t){return(0,u.blank)(e)||(0,o.isEmpty)(t)?void 0:(0,w.greatestBy)(t.filter((t=>(0,N.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}))),(t=>(0,o.commonPrefixLength)(e.split(s.default.sep),t.split(s.default.sep))))},t.bestVolumeForPath=me,t.bestVolumeForVolsha=async function(e){for(const i of[{name:"allPriorVolumes()",vols:de},{name:"volumes()",vols:t.volumes}]){const t=(0,v.toA)(await i.vols()).find((t=>(0,G.volsha)(t.uuid)===e));if(ne().debug("bestVolumeForVolsha(): "+i.name,{match:t}),null!=t)return t}},t.remoteVolumeFor=async function(e,i){return(0,x.thenMap)((0,t.volumes)(),(t=>pe(e,i,t)))},t.bestRemoteVolume=pe,t.findVolumeForVolsha=async function(e){if(!(0,u.blank)(e))return oe.get(e)??(await de())?.find((t=>(0,G.volsha)(t.uuid)===e))??(await(0,t.volumes)())?.find((t=>(0,G.volsha)(t.uuid)===e))}},68995:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeVolumeUuid=t.volumeUuidSubpath=void 0;const n=i(76760),r=i(19851),s=i(22573),a=i(50213),o=i(37805),l=i(16287),u=i(73428),c=i(17921),d=i(28874),h=(0,r.lazy)((()=>(0,a.mkLogger)("volumes.WriteVolumeUUID")));function f(){return(0,s.toNotBlank)(d.Settings.volumeUuidFilePaths.values[0])??".uuid"}t.volumeUuidSubpath=f,t.writeVolumeUuid=async function({mountpoint:e,uuid:t}){const i=(0,n.join)(e,f());t=(0,s.toNotBlank)(t)??(0,c.safeUUID)();const r=(0,n.dirname)(i);if(await(0,l.isReadWriteableDirectory)(r))try{return await(0,u.writeText_)(i,t,"","# This volume UUID was written by PhotoStructure v"+o.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details."),h().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){h().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t})}else h().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`)}},55111:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const n=i(50989);t.HelmetPlugins=(0,n.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},65713:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decuss=t.isCussy=t.getCuss=t.loadCuss=t.CussNativePath=void 0;const n=i(76760),r=i(19851),s=i(23838),a=i(81168),o=i(84542),l=i(43899),u=i(13047),c=i(31589);t.CussNativePath=(0,r.lazy)((()=>(0,n.join)(l.ProjectPath.Data(),"cuss.txt.br"))),t.loadCuss=(0,r.lazy)((async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(f(e))}));const d=(0,r.lazy)((()=>({trie:new s.MultiMap,small:[]}))),h=3;function f(e){const t=new s.MultiMap,i=[];for(const n of e)n.lengthe.includes(t)));if(null!=t)return t;for(let t=0;tn.startsWith(e)));if(null!=r)return r}}}}function p(e){return null!=m(e)}t.getCuss=m,t.isCussy=p,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&p(i.replace(/[^a-z]/gi,"")));return i}},31589:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unl33t=t.l33t=void 0;const n=i(22573),r=i(96249),s=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=s.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,n.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],s=c(e.substring(1));return(0,r.flatten)(s.map((e=>i.map((t=>t+e)))))}t.l33t=function(e){let t="";const i=l;for(const n of e)t+=i[n]?.[0]??n;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())}},30933:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const r=n(i(48161)),s=i(19851),a=i(42659),o=i(31586),l=i(50213),u=i(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>r.default.cpus()),5*a.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=r.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const r=n(i(48161)),s=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=r.default.freemem(),t=r.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const n=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(n))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([n,i]),meta:{freemem:e,totalmem:t,cgroupMem:n}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})}))},15674:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const n=i(19851),r=i(42659),s=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,n.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,n.lazy)((()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})}),r.minuteMs);function w(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,n.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,n=w();if(1!==n){const e=t;t*=n,g().warn("Recent timeouts! Throttling down.",{penalization:n,resultBeforePenalization:e,resultAfterPenalization:t})}const r=Math.min(e,v());return t=(0,a.clamp)(1,r,Math.floor(t)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:n,timeoutsPerSecond:i,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,n.lazy)((function(){return(0,a.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,a.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,a.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const n=i(58587),r=i(87997),s=i(19851),a=i(42659),o=i(41400),l=i(50213),u=i(7282),c=i(45255),d=i(34102),h=i(976),f=i(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new n.Rate(5*a.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const p=(0,s.lazy)((()=>(0,r.setInterval)(g,a.minuteMs).unref()));function g(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),p()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),g()},(0,o.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},91863:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(i(1708)),s=i(98553),a=i(5670),o=i(59880),l=i(19913),u=i(71567),c=i(80061),d=i(17181),h=i(41944),f=i(28874),m=i(7014),p=i(16848);!async function(){r.default.argv.includes("--help")&&(console.log((0,c.cliWrapWithFooter)("This is PhotoStructure's background worker, and is for internal use only")),r.default.exit(0)),(r.default.argv.includes("--version")||r.default.argv.includes("-V"))&&(console.log((0,c.cliWrapVersion)()),r.default.exit(0)),(0,l.setServiceName)(a.ServiceNames.worker),(0,o.setShortProcessNames)(f.Settings.shortProcessNames.valueOrDefault),(0,o.setProcessTitle)(),(0,d.setupLogger)(),r.default.argv.includes("--volumes")&&(console.log((0,s.stringify)(await(0,m.volumes)())),r.default.exit(0)),h.onProgressEvt.setShim((async e=>{(0,u.stdoutWrite)(e,void 0)})),(0,p.handleWorkRequests)()}()},24817:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequest_=t.isWorkRequest=t.mkWorkRequest=t.WorkRequestMethods=t.WorkerFunctions=t.AllWorkerFunctionCandidates=void 0;const n=i(98553),r=i(31586),s=i(68708),a=i(50989),o=i(32639),l=i(13991),u=i(50597),c=i(48368),d=i(52121),h=i(48604),f=i(181),m=i(66106),p=i(47783),g=i(83966);t.AllWorkerFunctionCandidates={_extractVideoFrame_:m._extractVideoFrame_,_readRawTags:p._readRawTags,_readTags:p._readTags,assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkerFunctions={assetFileMetadata_:l.assetFileMetadata_,buildAssetPreviews_:h.buildAssetPreviews_,imageHash_:c.imageHash_,ping:g.ping,prepFileForBrowser:d.prepFileForBrowser,whyInvalidFile:f.whyInvalidFile,shimmedFileSha_:u.shimmedFileSha_},t.WorkRequestMethods=(0,a.strEnum)(...(0,s.keys)(t.WorkerFunctions));let y=0;t.mkWorkRequest=function(e,t){return{id:++y,fn:e,args:t}},t.isWorkRequest=function(e){return"object"==typeof e&&t.WorkRequestMethods.has(e?.method)&&(0,r.isNumber)(e.id)},t.handleWorkRequest_=async function(e){const i=t.WorkerFunctions[e?.fn];if((0,o.isFunction)(i))return i(e?.args);throw new Error("invalid method "+(0,n.stringify)(e))}},16848:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.handleWorkRequests=void 0;const r=n(i(1708)),s=i(19851),a=i(50213),o=i(71567),l=i(33456),u=i(22573),c=i(26905),d=i(67478),h=i(54993),f=i(45608),m=i(55534),p=i(8769),g=i(57159),y=i(24817),v=(0,s.lazy)((()=>(0,a.mkLogger)("worker.Worker")));async function w(e){if(e=(0,h.toS)(e),(0,u.blank)(e))return;if(e.trim()===m.ServiceExitCommand)return(0,f.exit)({reason:e+" from stdin",status:0});const t=(0,d.parseJSON)(e);v().trace("onData",{request:t});try{const e=await(0,y.handleWorkRequest_)(t);(0,o.stdoutWrite)({id:t.id,response:e},!0)}catch(e){const i=(0,c.errorToJson)(e);v().warn("failed to process request",{request:t,error:i}),(0,o.stdoutWrite)({id:t.id,error:i},!1)}}t.handleWorkRequests=function(){!0!==r.default.stdin?.readable?(0,f.exit)({reason:"process.stdin is not readable",status:13}):(function(){for(const e of["SIGINT","SIGTERM"])r.default.on(e,(e=>(0,f.exit)({reason:e,status:0})))}(),function(){for(const e of["uncaughtException","uncaughtException","disconnect"])r.default.on(e,(e=>{const t=new g.WrappedError("uncaughtException",{cause:e});return(0,p.onError)(t)?(0,f.exit)({error:t,status:(0,c.errorErrno)(t)??1}):void 0}))}(),(0,f.exitOnStdStream)(),r.default.stdin.pipe(new l.LineReader).on("data",w),v().info("Child process mode: listening on stdin..."))}},83966:function(e,t,i){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const r=n(i(1708)),s=i(41400),a=i(31586),o=i(7282),l=i(12089),u=i(45608),c=i(57159),d=i(89035);t.ping=(0,l.shim1)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,s.delay)(e.delay),(0,o.isTest)()&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:r.default.pid,input:e?.input??"(no input)"}}})},40958:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const n=i(76790),r=i(22573),s=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,i)=>e===t[i]))}function v(e,t){for(let i=0;i=e.length||i>=e.length)return e;const n=e[t];return e.splice(t,1),e.splice(i,0,n),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&(0,o.getOrSet)(i,e,(()=>n))}return[...i.values()]}function P(e,t,i=1,n=(e=>e)){const r=[];if(et;s-=i)r.push(n(s));return r}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;it.includes(e)))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,n.sortBy)(e,g),r=(0,n.sortBy)(t,g);return i.every(((e,t)=>e===r[t]))},t.pushUniq=function(e,...t){for(const i of t)null==i||e.some((e=>(0,s.eql)(e,i)))||e.push(i);return e},t.pushUniqBy=function(e,t,i){const n=e.map(i);for(const r of t){const t=i(r);n.includes(t)||(e.push(r),n.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let n=0;n0)return e.splice(n,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,(e=>t.every((t=>e!==t)))),i!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(r.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,s.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const i=[];for(const e of(0,n.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))i.some((t=>t.includes(e)))||i.push(e);return(0,n.sortBy)(i,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,a.stringify)(e))){const i=new Map;for(const n of e)if(null!=n){const e=t(n);null!=e&&i.set(e,n)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const n of e)null!=n&&i.every((e=>!t(n,e)))&&i.push(n);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,i,n)=>e+(t(i,n)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,i,n)=>e+t(i,n)),0)},t.firstMatch=function(e,t){for(const i of S(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const n=Math.round(i);if(n<2)return e;for(let i=0;ie)){return P(e,t,1,i)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,i,n=t.primitiveValueOfOrElse){const r=new Set(i.map(n));return e.filter((e=>!r.has(n(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const n=i(40958),r=i(36783),s=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return(0,r.copyArrayTo)(f(e,t),e)}function h(e,t){const i=new Map;for(const n of e)(0,o.getOrSet)(i,(0,a.stringify)(t(n)),(()=>n));return f(i.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),(e=>[e,i]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,n.compact)(e),n.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,r.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,i)=>0===i||t>=e[i-1]))},t.sortedBy=function(e,t){return e.every(((i,n)=>0===n||t(i)>=t(e[n-1])))},t.sortBy=f,t.deepSortBy=function e(t,i){return f(t,i).map((t=>(0,s.isIterable)(t)?e(t,i):t))},t.pushSorted=function(e,t,i){const n=e.findIndex((e=>i(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const n=i(32639);t.asPromise=async function(e){const t=await e;return(0,n.isFunction)(t)?t():t}},75761:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assetImgAttrs=t.assetSqImgAttrs=t.assetVideoLink=t.assetImgActualLink=t.assetImgLink=t.assetLinkAttrs=t.assetUrl=void 0;const n=i(58939),r=i(40958),s=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652),h=i(22403),f=i(2322);function m(e,t){return e+" "+t+"w"}function p(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const n=(0,c.toS)(e.v);return(0,s.blank)(n)||"1"===n||(i??(i=new URLSearchParams)).append("v",n),i}function g({assetId:e,params:t}){return null==e?"":(0,d.assembleFullPath)("/asset/"+(0,n.id2id)(e),p(e,t))}function y({assetId:e,reducer:t,width:i,params:r}){return(0,d.assembleFullPath)(`/img/${(0,n.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,p(e,r))}function v({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,r.compact)([(0,n.id2id)(e),t]).join("/")}/actual`,p(e,i))}function w({assetId:e,params:t,reducer:i,widths:r,lazyLoad:s,af:l}){if(null==(0,n.id2id)(e))return{src:"/images/clear-64.png"};0===(r=(r??[]).filter(u.gt0)).length&&r.push(320);const d=Math.min(...r),p={width:(0,c.toS)(d)},g=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=g&&(p.title=g);const w=y({assetId:e,params:t,reducer:i,width:d});s??(s=!0);const S=s&&(0,f.isSafari)((0,h.ua)());S?(p.src="/images/clear-64.png",p["data-src"]=w):p.src=w,(0,f.isSafari)((0,h.ua)())||(p.loading=s?"lazy":"eager"),i===o.ReducerNames.sq&&(p.height=(0,c.toS)(d));const b=r.map((n=>m(y({assetId:e,params:t,reducer:i,width:n}),n)));return null!=l&&b.push(m(v({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),p[(S?"data-":"")+"srcSet"]=b.join(","),p}t.assetUrl=g,t.assetLinkAttrs=function({assetId:e,params:t}){const i=g({assetId:e,params:t});return(0,s.blank)(i)?{}:{href:i}},t.assetImgLink=y,t.assetImgActualLink=v,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,n.id2id)(e)}-${t}`,p(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:n="m"}){return{...w({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===n?80:"m"===n?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=w},5233:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const n=i(41400),r=i(31586),s=i(13538),a=i(41583);t.retryOnReject_=async function(e,t){const i=(0,r.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return i();const o=t.onRetryWaitUntil??(e=>(0,n.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await i()}catch(e){const i=(0,a.toErr)(e);if(!1===t.errorIsRetriable?.(i)||l>t.maxRetries)throw i;return l++,await o(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},82950:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.li=t.b=t.tt=t.md2html=void 0;const n=i(40958),r=i(22573),s=i(96249),a=i(55938),o=i(54993);t.md2html=function(e){let t=e.replace(/").replace(/^ *- (.*)$/gm,((e,t)=>"
  • "+t.trim()+"
  • "));return t=(0,a.replaceAllMatches)(t,/```([^`]+)```/g,(e=>`${e[1]}`)),t=(0,a.replaceAllMatches)(t,/\*\*([^*]+)\*\*/,(e=>`${e[1]}`)),t},t.tt=function(e){return(0,r.blank)(e)?"":"```"+(0,o.toS)(e)+"```"},t.b=function(e){return"**"+(0,o.toS)(e)+"**"},t.li=function(...e){return(0,n.compactBlankish)((0,s.flatten)(e)).map((e=>"- "+(0,o.toS)(e))).join("\n")}},22573:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const n=i(55835),r=i(42279),s=i(54993);function a(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,s.toS)(e);return o(i)?t(i):void 0}t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,r.tot)(t);const i=(0,s.toS)(e).trim();return i.length>0?i:(0,r.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,n.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function i(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const i=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(i)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=i,t.toBoolean=function(e){return!!i(e)||!n(e)&&void 0},t.toNotBoolean=function(e){return!i(e)&&(!!n(e)||void 0)},t.boolToInt=function(e){return i(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>i(e)))},t.and=function(e){return e.every((e=>i(e)))},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t=!0)}return t},t.mapBoolean=function(e,t){return i(e)?t(!0):n(e)?t(!1):void 0},t.mapTrue=function(e,t){return i(e)?t():void 0}},79666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const n=i(98553);t.clone=function(e){return null==e?e:JSON.parse((0,n.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const n=i(40958),r=i(22573),s=i(30301),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function p(e){return e instanceof Date}function g(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=p,t.thisYear=function(){return(new Date).getFullYear()},t.ago=g,t.hence=function(e,t){return g(-e,t)},t.unixtime=function(e){const i=p(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,i={includeMs:!0}){const n=Math.floor(e/t.hourMs);e-=n*t.hourMs;const r=Math.floor(e/t.minuteMs);e-=r*t.minuteMs;const s=Math.floor(e/t.secondMs),a=Math.floor(e-s*t.secondMs);return(0,l.pad2)(n)+":"+(0,l.pad2)(r)+":"+(0,l.pad2)(s)+(i.includeMs?"."+(0,l.pad3)(a):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},n=10*i(),r=i(),s=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,s,r,n)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,i="ago"){return e<1e3?"just now":(i=(0,r.blank)(i)?"":(0,u.ensurePrefix)(i," "),et.ms<=e)))){const s=Math.floor(e/n.ms);e-=s*n.ms,s>0&&(n.ms>=t.dayMs?i:r).push(s+n.s)}return e>0&&r.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,n.isEmpty)(r)?"":"T"+r.join(""))},t.fmtIsoDate=function(e){const t=p(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,a.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const n=i(38639),r=i(73872);function s(e,t,i){if(null==i||y(e)||y(t))return null;const n=i.get(e)?.get(t);return"boolean"==typeof n?n:null}function a(e,t,i,n){if(null==i||y(e)||y(t))return;let r=i.get(e);null!=r?r.set(t,n):(r=new WeakMap,r.set(t,n),i.set(e,r))}function o(e,t,i,n){if(null!=i?.comparator)return u(e,t,i,n);const r=l(e,t);return null!==r?r:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,n){i??(i={});const u=!1===i.memoize?void 0:i.memoize??(i.memoize=new WeakMap),d=i?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,n);if(!1===i||!0===i)return a(e,t,u,i),i;const r=l(e,t);if(null!==r)return r}const y=r(e);if(y!==r(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,n){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],n);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,n);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,n);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),n);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),n);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const n=[],r=[];return e.forEach((function(e,t){n.push([e,t])})),t.forEach((function(e,t){r.push([e,t])})),c(n.sort(),r.sort(),i)}(e,t,n);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,n)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const n=e.length;if(n!==t.length)return!1;if(0===n)return!0;let r=-1;for(;++r{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,i,n=!1;const r=function(){if(n){if(null!=i)throw i;return t}try{return n=!0,t=e()}catch(e){throw i=e,e}};return r.prior=()=>t,r.hasPrior=()=>n,r}},41400:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const n=i(42659),r=i(35556),s=i(31586),a=i(68708);function o(e,t=!0){return new Promise((i=>{if(e<=0)i();else{const s=setTimeout((()=>i()),Math.ceil(e+.5));e>n.secondMs&&t&&r.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then((()=>t))},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),s=r.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return r.isBrowser||t<=n.secondMs?s:(0,a.maybeCall)(s,"unref")??s}},33374:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pixels=t.dmegapixels=t.isPortrait=t.maybeFlipInPlace=t.maybeDimSwap=t.dimSwap=t.dimToSize=t.fmtDim=t.dimGte=t.isCloseAspectRatio=t.isDimensions=void 0;const n=i(31586),r=i(21605),s=i(12168);function a(e){return{width:e.height,height:e.width}}function o(e){return((0,n.toGt0)(e?.width)??0)*((0,n.toGt0)(e?.height)??0)}t.isDimensions=function(e){return null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height)},t.isCloseAspectRatio=function(e,t,i=.05){return(0,n.gt0)(e)&&(0,n.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=Math.max(e,t)*i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,s.pixels2size)(e.width*e.height)},t.dimSwap=a,t.maybeDimSwap=function(e,t){return(0,r.swappableRotation)(t)?a(e):e},t.maybeFlipInPlace=function(e,t){(0,r.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,s.megapixels)(o(e))},t.pixels=o},50357:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const n=i(12487),r=i(68708),s=i(34666),a=i(32639);function o(e,t){return(0,n.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,a.isFunction)(e)&&(0,a.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=o,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,r.isObject)(e)||!(0,r.isObject)(t))return!1;for(const i of(0,r.keys)(e))if(!o(e[i],t[i]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const n=d.get(i);if(null!=n)return n(e,t)??null}for(const i of c){const n=i(e,t);if(null!=n)return n}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const n=i(40958),r=i(22573),s=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,r.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,n.uniq)((0,n.compactBlankish)((0,s.flatten)((0,n.compact)(i).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,r.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter((e=>!(0,r.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,n.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,r.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(r.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},4188:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=void 0,t.fitInside=function(e,t){const i=e.width/e.height;if(i>=t.width/t.height){const e=t.width;return{width:e,height:Math.floor(e/i)}}{const e=t.height;return{width:Math.floor(e*i),height:e}}}},96249:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const n=i(59455);t.flatten=function(e,t=[]){for(const i of(0,n.toA)(e))if(null!=i)for(const e of(0,n.toA)(i))null!=e&&t.push(e);return t}},75240:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=void 0;const n=i(40958),r=i(42659),s=i(55835),a=i(31586),o=i(12168),l=[{ms:r.yearMs,s:"year",p:"years"},{ms:r.yearMs/12,s:"month",p:"months"},{ms:r.weekMs,s:"week",p:"weeks"},{ms:r.dayMs,s:"day",p:"days"},{ms:r.hourMs,s:"hour",p:"hours"},{ms:r.minuteMs,s:"minute",p:"minutes"},{ms:r.secondMs,s:"second",p:"seconds"}];t.fmtDuration=function e(t,i=2,r){if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t),i):"";const u=l.findIndex((e=>e.ms<=t));if(-1===u)return"";let c=t+(0,s.mapOr)(l[u+Math.max(2,i)-1],(e=>Math.round(.4*e.ms)),0);const d=(0,n.compact)(l.slice(u,u+i).map((e=>{if(!(e.ms>c)){const t=Math.floor(c/e.ms);return c-=t*e.ms,{i:t,s:(0,o.plur)(t,e.s,e.p)}}})));return(0,n.isEmpty)(d)?"":d.map((e=>e.s)).join(", ")+(0,s.mapOr)(r,(e=>" "+(1!==d[d.length-1].i?e.singular:e.plural)),"")}},57924:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const n=i(40958);function r(e,t){return null==(e=(0,n.uniq)((0,n.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=r,t.orList=function(e){return r(e,"or")},t.andList=function(e){return r(e,"and")}},50268:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.newHealthCheckSections=t.BaseHealthCheckSummary=t.isHealthCheckSummary=t.isHealthCheckResult=t.HealthCheckLevelDescription=t.healthCheckLevelToEmoji=t.HealthCheckLevelToEmoji=t.levelIsNotOK=t.HealthCheckLevels=t.HealthCheckSections=void 0;const n=i(22573),r=i(38639),s=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending];function c(e){return(0,s.isObject)(e)&&!(0,n.blank)(e.id)&&!(0,n.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,n.blank)(e.msg)}t.levelIsNotOK=function(e){return!u.includes(e)},t.HealthCheckLevelToEmoji={pending:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.HealthCheckLevelDescription={pending:"Health checks are running...","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,s.isObject)(e)&&a.RunStates.has(e.state)&&(0,r.isBoolean)(e.settled)&&c(e)},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map((e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]})))}},11371:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const n=i(50989);t.ReducerNames=(0,n.strEnum)("fit","sq")},73722:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const n=i(50989);t.FitSizes=(0,n.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,n.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const n=i(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,i){if((0,n.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,n.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,i){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(i))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],i=[];return function e(n,r){if((0,isFunction_1.isFunction)(n))return;let s,a,o,l=toJSON(n);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(n===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let n=0;t.Latch=class{constructor(e=n++){this.id=e,this[i]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},i=Symbol.toStringTag},30301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const n=i(40958),r=i(50357),s=i(31586),a=i(65812);t.lazy=function(e,t){let i,o;const l=[];function u(){return u.isStale()&&u.setResult(e()),o}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return i=Date.now(),async function(e,i){if((0,n.isEmpty)(l))return;const s=await e,o=await i;if(!(0,r.eql)(s,o))for(const e of l)e(o);null!=t&&t>0&&void 0!==o&&(0,a.setUnrefTimeout)((()=>u.vacuum()),t)}(o,e),o=e},u.isStale=function(){return null==i||(0,s.gt0)(t)&&i+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const n=i();return null!=n&&e.set(t,n),n}},t.deleteIf=function(e,t){for(const[i,n]of e.entries())t(i,n)&&e.delete(i)}},55835:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const n=i(42279),r=i(54993);function s(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,n.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,n){return null==e||null==t||null==i?void 0:n(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,n.tot)(i)},t.map2Or=function(e,t,i,n){return o(a(e,t,i),n)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,r.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const n=i(68708);class r extends Error{constructor(e,t){super(e),this.message=e,(0,n.assignFields)(this,t)}}t.MetaError=r},23838:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const n=i(40958),r=i(76790),s=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{static fromJSON(e){const t=new d;for(const[i,n]of Object.entries(e))t.add(i,...n);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,n.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const i=(0,o.getOrSet)(this.store,e,(()=>[]));return i.push(...t),i}addUniq(e,...t){return(0,n.pushUniq)((0,o.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const n=i.filter((e=>!(0,s.eql)(e,t)));return 0===n.length?this.store.delete(e):this.store.set(e,n),i.length!==n.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,n.uniq)(t))){for(const t of this.keys()){const i=this.store.get(t),r=null==i?[]:e(t,i);(0,n.isEmpty)(r)?this.store.delete(t):this.store.set(t,r)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,n.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,i]of e.store.entries())i.length>0&&(yield[t,i])}()}tuples(){const e=this;return function*(){for(const[t,i]of e.store.entries())for(const e of(0,c.toA)(i))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[i,r]of this.store.entries()){const s=(0,n.findIndexes)(r,(t=>!e(i,t,r)));if(s.length>0){t=!0;for(const e of s.reverse())r.splice(e,1)}0===r.length&&this.store.delete(i)}return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const n of i)e.add(n,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,n]of this.entries())n.some((t=>e(i,t)))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>i.add(t,e))))),i}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,r.sortBy)((0,c.toA)(i.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const n=i(76790),r=i(22573),s=i(42279),a=i(54993);function o(e){return"number"==typeof e&&isFinite(e)}t.isNumber=o,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,a.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return o(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,a.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,i)=>o(t)&&o(i)&&e(t,i);function f(e,i,r){return!(null==r||!o(r))&&([e,i]=(0,n.sort)([e,i]),(0,t.lte)(e,r)&&(0,t.gte)(i,r))}function m(e){if(!o(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function p(e){return"function"==typeof e?.toNumber}function g(e,t){if((0,r.blank)(e))return t.defaultValue;if(o(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return g(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return o(e)&&e>0}function S(e){return o(e)&&e>=0}function b(e,t){return o(e)?t(e):void 0}function P(e){return o(e)?e<0?-Math.round(-e):Math.round(e):0}function M(e,t){if(null==e)return 0;const i=Math.pow(10,t);return P(e*i)/i}function _(e,t,i){if(e>t||!o(e)||!o(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return o(i)?it?t:i:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return o(e)?e:t},t.diff=function(e,t){return o(e)&&o(t)?e-t:void 0},t.absdiff=function(e,t){return o(e)&&o(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!o(e)||!o(t))return!1;if(e===t)return!0;if(i>=1)return!1;const n=(0===t?1e-5:t)*(1-i);return f(t-n,t+n,e)},t.within=f,t.max_=function(...e){let t;for(const i of e)o(i)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return o(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return o(e)&&o(t)&&e>t?e:void 0},t.lte0=function(e){return o(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const i=y(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=v(e);return null==i?void 0:t(i)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,i){return b(e,(e=>b(t,(t=>i(e,t)))))},t.mapNumericOr=function(e,t,i){return o(e)?t(e):i},t.numericOr=function(e,t){return o(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=M,t.toPrecisionMaybe=function(e,t){return d(e,(e=>M(e,t)))},t.sigFigs=function(e,t){if(!o(e)||0===e||0===t)return 0;const i=t-P(Math.ceil(Math.log10(Math.abs(e)))),n=Math.pow(10,Math.abs(i));return i<0?P(e/n)*n:P(e*n)/n},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=_,t.times=function(e,t){if(!w(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map(((e,i)=>t(i)))},t.pct=function(e,t){return _(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const i=Math.round(e??-1);return null==t||f(0,t,i)?i+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const i of e){if(!o(i))return;t+=i}return t}},68708:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const n=i(40958),r=i(76790),s=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function p(e){return h(e).map((t=>e[t]))}function g(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,n]=i;null!=e&&void 0!==n&&("object"!=typeof t&&(t={}),t[e]=n)}return t}function v(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>null!=e)))return e;const i=t.filter((([,e])=>null!=e));return(0,n.isEmpty)(i)?void 0:y(i)}function w(e,t,i={}){return y((0,n.compact)((0,r.sort)(h(e)).map((i=>t(i,e[i])))).filter((([e,t])=>null!=e&&void 0!==t)),i)}function S(...e){const t=(0,n.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const r={};for(const e of(0,n.uniq)((0,n.flatMap)(i,h)))r[e]=S(...i.map((t=>t[e])));return r}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(i.test(t))return{key:t,value:e[t]}}function P(e){return p(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const i=v(e);return m(i)?t(i):void 0},t.values=p,t.entries=g,t.fromEntries=y,t.assignFields=function(e,t,i){if(null==t)return e;for(const[n,r]of g(t))!0!==i?.omitKeys?.includes(n)&&(null==r&&!0!==i?.assignNullish||(e[n]=r));return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const n of i){const i=t[n];void 0!==i&&void 0===e[n]&&(e[n]=i)}return e},t.assignAllFields=function(e,t){for(const[i,n]of g(t??{}))e[i]=n;return e},t.definedValues=function(e){if(null==e)return;const t=g(e);if(t.every((([,e])=>void 0!==e)))return e;const i=t.filter((([,e])=>void 0!==e));return(0,n.isEmpty)(i)?void 0:y(i)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,n.compact)(t.map(e));{const i=(0,n.compact)(g(t).map((([t,i])=>(0,o.map)(e(i),(e=>[t,e])))));return 0===i.length?void 0:y(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=g(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,n.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickCompact=function(e,...t){if(null==e)return;const i={};for(const n of t)void 0!==e[n]&&(i[n]=e[n]);return i},t.pickNonBlank=function(e,...t){if(null==e)return e;const i={};for(const n of t){const t=e[n];(0,s.notBlank)(t)&&(i[n]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(null!=e)for(const n of t)if(i(e[n]))return e[n]},t.pickDeep=function e(t,...i){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...i)));const n={};function r(e,t){if(null==t)return;const i=n[e];n[e]=null==i?t:S(i,t)}for(const n of i){const[i,a]=(0,c.splitFirst)(n,"."),o=b(t,i);null!=o?.value&&r(o.key,(0,s.blank)(a)?o.value:e(o.value,a))}for(const n of h(t))((0,l.toInt)(n)??-1)>=0&&r(n,e(t[n],...i));return n},t.pluck=b,t.pluckDeep=function e(t,i){if(null==t||(0,s.blank)(i))return;if(Array.isArray(t)){const r=(0,n.compact)(t.map((t=>e(t,i))));return(0,n.isEmpty)(r)?void 0:{key:r[0].key,value:(0,n.flatMap)(r,(e=>e.value))}}const[r,a]=(0,c.splitFirst)(i,"."),o=b(t,r);if(null==o)return;if((0,s.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const i=g(e).filter((([e])=>!t.includes(e)));return(0,n.isEmpty)(i)?void 0:y(i)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(g(e).filter((([e,i])=>t(e,i))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,n.uniq)(t)},t.maybeCall=function(e,t,...i){const n=e?.[t];return(0,a.isFunction)(n)?n.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of h(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,((t,i)=>[t,e(i)])),n=p(i);return 1===n.length?n[0]:i}},97790:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class n{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new n(e(this.a))}flatMap(e){const t=e(this.a);return r(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,i){return s(e).flatMap((e=>s(t).flatMap((t=>i(this.a,e,t)))))}zip3(e,t,i,n){return s(e).flatMap((e=>s(t).flatMap((t=>s(i).flatMap((i=>n(this.a,e,t,i)))))))}}function r(e){return e instanceof n||e===t.None}function s(e){return r(e)?e:null!=e?new n(e):t.None}t.Some=n,t.isOpt=r,t.opt=s},39926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const n=i(31586),r=i(54993),s={};function a(e,t){if(t<1)return"";if(!(0,n.gte)(s[e]?.length,t)){let i=s[e]??e;for(;i.length{Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var n=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return n.parseJSON}})},46891:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const n=i(22573),r=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,n.blank)(e))return e;const t=r.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const n=i(40958),r=i(54993),s=["number","string","boolean"];function a(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=a,t.mapPrimitive=function(e,t){return a(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return a(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(a)};const o=["boolean","number","bigint","symbol","string","object","function"];function l(e,i){if(null==e&&null==i)return 0;if(null==e)return-1;if(null==i)return 1;const n=typeof e,s=typeof i;if(!("string"!==n&&"symbol"!==n||"string"!==s&&"symbol"!==s)){const n=(0,r.toS)(e),s=(0,r.toS)(i),a=n.localeCompare(s);return n[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?u(e,i):n!==s?o.indexOf(n)-o.indexOf(s):e>i?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const n=i(59455);function r(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const i=await e;return null==i?void 0:t(i)},t.thenCollect=async function(e,t){const i=[];for(const r of(0,n.toA)(await e))if(null!=r){const e=await r;if(null!=e){const n=await t(e);null!=n&&i.push(n)}}return i},t.thenTap=async function(e,t=console.dir.bind(console)){const i=await e;return await t(i),i},t.isPromiseLike=r,t.isPromise=function(e){return r(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:i}){const n=await e;return t(n)?i(n):void 0}},57153:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const n=i(50989);t.PromiseStates=(0,n.strEnum)("pending","resolved","rejected")},30976:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const n=i(40958),r=i(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?s(e,t):o(e,t,1,i)[0]}function o(e,t,i,n){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const r=t-e,a=new Set(n??[]);if(t===e&&0===r&&0===a.size&&1===i)return[e];const o=r-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:r,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size0;e--){const i=Math.floor(Math.random()*(e+1));e!==i&&([t[e],t[i]]=[t[i],t[e]])}return t},t.sample=function(e,t){const i=[];for(const n of o(0,e.length,t))i.push(e[n]);return i},t.pickWeightedRandom=function(e){if((0,n.isEmpty)(e))return;const t=e.filter((e=>(0,r.gt0)(e.priority)));let i=l(0,(0,n.sum)(t,(e=>e.priority)));return t.find((e=>(i-=e.priority,i<=0)))}},55938:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.replaceAllMatches=void 0,t.replaceAllMatches=function(e,t,i){let n=e;t.global||(t=new RegExp(t,"g"));let r=null;for(;null!=(r=t.exec(e));)r.index===t.lastIndex&&t.lastIndex++,n=n.slice(0,r.index)+i(r)+n.slice(r.index+r[0].length);return n}},21605:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swappableRotation=t.normalizeRotation=t.isRotation=t.Rotations=void 0;const n=i(31586);function r(e){if(!(0,n.isNumber)(e))return;const t=90*Math.round(e/90)%360;return t<=0?(t+360)%360:t}t.Rotations=[0,90,270,180],t.isRotation=function(e){return(0,n.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=r,t.swappableRotation=function(e){const t=r(e);return 90===t||270===t}},62220:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const n=i(50989);t.RunStates=(0,n.strEnum)("loading","welcome","ready","failed")},5670:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const n=i(50989);t.ServiceNames=(0,n.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const n=i(68708),r=i(42279);t.strEnum=function(...e){const t=Object.freeze(e),i=(0,n.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const a=e=>null!=e?i[e]:void 0,o=e=>null!=a(e);return{...s,values:t,length:t.length,has:o,includes:o,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:a,ordinal:e=>a(e)??t.length,validOrElse:(e,t)=>o(e)?e:(0,r.tot)(t),mapValid:(e,t)=>o(e)?t(e):void 0,cmp:(e,t)=>{const i=a(e),n=a(t);return null==i||null==n?void 0:i>n?1:i{const i=a(e);return null==i?void 0:t[i]}}}},51926:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const n=i(40958),r=i(17586),s=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,i){if(d(e))return t<0&&(t+=e.length),e.slice(t,i);{const n=f();return null!=n?(0,o.sliceIterable)(n.segment(e),t,i).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function p(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function g(e,t){const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.startsWith(n)?i.slice(n.length):i}function y(e,t){if(null==t)return e;const i=(0,c.toS)(e),n=(0,c.toS)(t);return n.length>0&&i.endsWith(n)?i.slice(0,-n.length):i}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let n=i;n>=0;n--)if(m(e,n).startsWith(t))return n;return-1}function b(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const n=(0,c.toS)(e),r=(0,c.toS)(t);return n.length===r.length&&(n===r||n.toLowerCase()===r.toLowerCase()||"function"==typeof n.localeCompare&&0===(i?n.normalize():n).localeCompare(i?r.normalize():r,void 0,{sensitivity:"base"}))}function P(e,t){return(0,n.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,r.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,o.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,i){return d(e)?e.slice(t,null==i?void 0:t+i):m(e,t,null==i?void 0:t+i)},t.charArr=p,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=g,t.stripPrefixes=function e(t,i){if(null==t)return"";const n=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&n.startsWith(t))return e(n.slice(t.length),i);return n},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return y(g(e,t),i)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(v(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const n=p(e);return n.length<=t?n.join(""):n.slice(0,t-1-i).join("")+"…"+(i>0?n.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const n=i?.maxLineLen??80,r=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const n=(0,a.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,a.flatten)(n.map((t=>e(t,i))))}if((t=v((0,c.toS)(t),r).trim()).length<=n)return[t];const s=S(t," ",n);if(s>r.length)return[m(t,0,s),...e(m(t,s+1),i)];{const n=t.indexOf(" ",r.length+1);return n>0&&n{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const n=i(42659),r=i(68708),s=i(42279),a=i(83104),o=i(85556);function l(e){return e===a.Timeout?void 0:e}async function u(e,t,i=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(i,n)=>{let r=!0;const s=setTimeout((()=>{r&&(r=!1,i(a.Timeout))}),t);try{s.unref?.();const t=await e;r&&(r=!1,i(t))}catch(e){r&&(r=!1,n(e))}finally{clearTimeout(s)}}))}async function c(e,t,i=!0){const r=await u(e,t,i);if(r===a.Timeout)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(t)+")");return r}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,i=!0){return u(e,t,i).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,i=!0){const n=t-Date.now();return n<=0?a.Timeout:u(e,n,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((async(n,s)=>{let a=!0;try{const o=setTimeout((async()=>{if(a){a=!1;try{n(await i())}catch(e){s(e)}}}),t);(0,r.maybeCall)(o,"unref");const l=await e;a&&(a=!1,clearTimeout(o),n(l))}catch(e){a&&(a=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,i=!0){const r=t-Date.now();if(r<=0)throw new o.TimeoutError("timeout ("+(0,n.fmtHMS)(r)+")");return c(e,r,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:n=!0}){if(null==e)return(0,s.tot)(i);const r=await u(e,t,n);return r===a.Timeout?(0,s.tot)(i):r}},42279:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const n=i(32639);t.tot=function(e){return(0,n.isFunction)(e)?e():e},t.tol=async function(e){return(0,n.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class i extends Error{}t.TimeoutError=i},89937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples"},29652:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addQueryToFullpath=t.assembleFullPath=t.mergeURLSearchParams=t.toURLSearchParams=t.isURLSearchParams=void 0;const n=i(40958),r=i(22573),s=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,n.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,n]of e.entries())i.set(t,n);return i}}t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,s.toS)(l(...t));return e+((0,r.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,s.toS)(l(...t));return(0,r.blank)(i)?e:e+(e.includes("?")?"&":"?")+i}},12168:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const n=i(22573),r=i(30301),s=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,r.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,r.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let i=0;for(const n of e)(0,s.isNumber)(n)&&(i+=n/t.MB);return(0,s.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,n.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),n=Math.floor(i/3),r=Math.pow(10,3*n),a=d[n];return(0,s.sigFigs)(e/r,t)+" "+a}t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),n=Math.floor(i/10),r=Math.pow(2,10*n),a=h[n];return(0,s.sigFigs)(e/r,t)+" "+a},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,n.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??(i=(0,a.pluralize)(t)),{count:c(e),desc:1===e?t:i}}},459:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const n=i(68708);t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,n.maybeCall)(i,"unref")??i}},22403:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ua=void 0;const n=i(30301),r=i(54993);t.ua=(0,n.lazy)((()=>(0,r.toS)(globalThis?.navigator?.userAgent)))},2322:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIphone=t.isIpad=t.isFirefox=t.isSafari=t.isChrome=void 0;const i=/\bChrome\b/,n=/\bSafari\b/,r=/\bFirefox\b/,s=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,r)}t.isChrome=l,t.isSafari=function(e){return o(e,n)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,s)},t.isIphone=function(e){return o(e,a)}},58939:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.idEql=t.id2id=void 0;const n=i(55835),r=i(31586);function s(e){const t=e;return(0,r.isNumber)(e)?e:(0,r.isNumber)(t.id)?t.id:(0,r.isNumber)(t.assetId)?t.assetId:(0,r.isNumber)(t.tagId)?t.tagId:void 0}t.id2id=s,t.idEql=function(e,t){return(0,n.map2Or)(s(e),s(t),((e,t)=>e===t),(()=>!1))}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const n=i(41801),r=i(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,r.isString)(e)?[e]:(0,n.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const n=i(40958),r=i(23541),s=i(59455),a=i(54993);function o(e){return null==e?void 0:(0,r.isError)(e)?e:new Error((0,a.toS)(e))}t.toErr=o,t.toErrs=function(...e){return(0,n.compact)((0,s.toA)(e).map(o))}},54993:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const n=i(98553);t.toS=function(e){return s(e,",")};const r={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==r?e.toString():(0,n.stringify)(e)}}t.toStr=s},23227:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),i(91863)},90858:e=>{e.exports=require("@iarna/toml")},53705:e=>{e.exports=require("@photostructure/tz-lookup")},58587:e=>{e.exports=require("batch-cluster")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},66150:e=>{e.exports=require("fast-xml-parser")},68817:e=>{e.exports=require("file-type")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},93973:e=>{e.exports=require("ml-kmeans")},4927:e=>{e.exports=require("papaparse")},83058:e=>{e.exports=require("picomatch")},57272:e=>{e.exports=require("plist")},85949:e=>{e.exports=require("process")},57160:e=>{e.exports=require("punycode.js")},38064:e=>{e.exports=require("semver")},9288:e=>{e.exports=require("sharp")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},40610:e=>{e.exports=require("node:dns")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},77030:e=>{e.exports=require("node:net")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},53916:e=>{e.exports=require("node:path/posix")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")},16928:e=>{e.exports=require("path")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(i.exports,i,i.exports,__webpack_require__),i.loaded=!0,i.exports}__webpack_require__.c=__webpack_module_cache__,__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__=__webpack_require__(__webpack_require__.s=23227);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/defaults.env b/defaults.env index c0a5fd8..1358822 100644 --- a/defaults.env +++ b/defaults.env @@ -1,5 +1,5 @@ # -# Welcome to PhotoStructure! These are the settings for version 2024.3.1. +# Welcome to PhotoStructure! These are the settings for version 2024.3. # # Please see https://photostructure.com/environment-variables for more # information about using environment variables with PhotoStructure. diff --git a/package.json b/package.json index a15a8c1..216aadd 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "photostructure", "productName": "PhotoStructure", "author": "PhotoStructure, Inc. ", - "version": "2024.3.2-beta", + "version": "2024.3.3-prealpha", "license": "SEE LICENSE IN LICENSE.md", "description": "PhotoStructure for Servers", "homepage": "https://photostructure.com/server/photostructure-for-node/", @@ -25,7 +25,7 @@ "@iarna/toml": "2.2.5", "@parcel/watcher": "2.4.1", "@photostructure/tz-lookup": "9.0.2", - "@sentry/node": "7.105.0", + "@sentry/node": "7.107.0", "argon2": "0.40.1", "batch-cluster": "13.0.0", "better-sqlite3": "9.4.3", @@ -33,9 +33,9 @@ "commander": "12.0.0", "croner": "^8.0.1", "exiftool-vendored": "24.6.0", - "express": "4.18.3", + "express": "4.19.1", "express-session": "1.18.0", - "fast-xml-parser": "4.3.5", + "fast-xml-parser": "4.3.6", "file-type": "16.5.4", "fs-extra": "11.2.0", "he": "1.2.0", @@ -51,7 +51,7 @@ "platform-folders": "0.6.0", "plist": "3.1.0", "pug": "3.0.2", - "punycode": "2.3.1", + "punycode.js": "2.3.1", "semver": "7.6.0", "sharp": "0.32.6", "source-map-support": "0.5.21", diff --git a/photostructure b/photostructure index 3558f03..9ef76a2 100755 --- a/photostructure +++ b/photostructure @@ -6,4 +6,4 @@ * IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE */ -(()=>{"use strict";var __webpack_modules__={37975:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const i=r(1708),n=r(22573),s=r(38639);function o(){return(0,s.toNotBoolean)(i.env.PS_LOG_COLOR)??(!(0,n.blank)(i.env.NO_COLOR)||["dumb","unknown"].includes(i.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(r){return l()?`[${e}m${r}[${t}m`:r}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const i=r(19851),n=r(7282),s=r(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,i.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,i.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const i=r(40958),n=r(36783),s=r(76790),o=r(22573),a=r(50357),l=r(98553),u=r(55835),c=r(31586),d=r(68708),h=r(34666),f=r(59455),m=r(84885);var g=r(40958);function p(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,r=i.primitiveValueOfOrElse){const n=new Set(t.map(r));return e.filter((e=>n.has(r(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],r=e.lastIndexOf(t);return[{t,count:r+1},...v(e.slice(r+1))]}function w(...e){const t=[],r=Math.max(...e.map((e=>e?.length??0)));for(let i=0;ie?.[i])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function E(e,t){return(0,i.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,r){return C(e,t,r).index}function C(e,t,r){if((0,i.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let i=0;ie.slice(r,r+t)))}async function x(e,t){return(0,i.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return g.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return g.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return g.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=p,t.mapAllDefined=function(e,t){return p(e)?t(e):void 0},t.mapAll=function(e,t){return p(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const r of(0,f.toA)(e))if(null!=r&&!0===await t(r))return r},t.findLastAsync=async function(e,t){for(let r=(e=(0,f.toA)(e)).length-1;r>=0;r--){const i=e[r];if(null!=i&&!0===await t(i))return i}},t.first=function(e,t){if(null!=e)for(const r of(0,f.toA)(e))if(null!=r){const e=t(r);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null!=i){const e=await t(i,r);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,i.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,r){for(let i=r;i<=e.length-1;i++)if(t(e[i]))return i},t.findLast=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},t.findLastIndex=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},t.concat=function(...e){const t=[];for(const r of e)if(Array.isArray(r))for(const e of r)null!=e&&t.push(e);else null!=r&&t.push(r);return t},t.moveToEnd=function(e,t){return(0,i.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const r=e[t];if(null==r)return e;e.push(r);for(let r=t;r(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const r=e.findIndex(t);return r>=0?e.splice(r,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,i.uniqBy)(e,t),e)},t.partition=function(e,t){const r=[],i=[];let n=0;for(const s of e)(t(s,n++)?r:i).push(s);return[r,i]},t.isUniq=function(e){return e.every(((t,r)=>e.indexOf(t)===r))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,i.compact)((0,i.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),r=[];return(0,c.times)(t,(t=>e.map((e=>r.push(e?.[t]))))),r},t.unFlatZip=function(e,t){const r=e.length/t;if(r!==Math.round(r))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const i=(0,c.times)(t,(()=>new Array(r)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=E,t.least=function(e){return E(e,(e=>e))},t.greatestBy=function(e,t){return(0,i.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const r=C(e??[],t,h.lt);return null==e||null==r||r.index<0||null==r.value?void 0:{result:e[r.index],index:r.index,value:r.value}},t.reverse=function(e){const t=[];for(let r=e.length-1;r>=0;r--)t.push(e[r]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(r(s)));return n},t.collectBatchedAsync=async function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(await r(s)));return n},t.contextFilter=function(e,t){let r;return e.filter(((e,i)=>(0,d.tap)(t(e,i,r),(t=>{t&&(r=e)}))))},t.clusterSome=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.some((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterEvery=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.every((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterAsync=async function(e,t){const r=[];e:for(const i of e){for(const e of r)if(null!=i&&await x(e,(e=>t(i,e)))){e.push(i);continue e}null!=i&&r.push([i])}return r},t.someAsync=async function(e,t){if(null!=e)for(let r=0;r=0&&!0===(0,u.map)(e[i],(e=>r(e,i))))return i}{const i=t+n;if(ie+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,r){return e.lengthr))),e}},36557:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=r(77988),l=o(r(1708)),u=r(19851),c=r(42659),d=r(55835),h=r(31586),f=r(85556),m=r(54993),g=r(50213),p=r(79089),y=r(45255),v=r(25764),w=r(38836),S=r(99331),b=r(95937),P=r(98314),_=r(38835),E=r(70025),M=r(8769),C=r(43334),T=r(95402),x=r(28874),D=r(63870);class k extends w.EndableWrapper{constructor(e,t,r=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,i,"m",n).call(this)),r,"worker"===e?(0,D.commandTimeoutMs)():y.ShortCommandTimeoutMs),i.add(this),this.t=t;const o=t;o.on("childStart",(async r=>{null!=r.pid?(this.logger.info("Started child process",{pid:r.pid}),(0,p.renice)(r.pid).catch((e=>this.onError("renice failed",e))),(0,T.addPid)({pid:r.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,r,i)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&T.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,E.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=k,i=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(C.isWin?3:1)*c.minuteMs,maxTasksPerProcess:x.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:x.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:x.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,g.mkLogger)(t))),spawnTimeoutMillis:(0,D.commandTimeoutMs)(),taskTimeoutMillis:x.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=r(92460),d=r(31586);class h{constructor(e){if(i.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,r;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,i,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,r;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,i,"m",a).call(this,0,(e=>{var t,r;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(r=u(this,s,"f"),--r),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,i,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const r=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=r}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const i=r(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:r}of n)if(o(e,t))return e.subarray(t.length).toString(r);return e.toString()}function o(e,t){return t.every(((t,r)=>e[r]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,i.toS)(e)},t.bufferStartsWith=o},9092:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,r]of e)this.set(t,r)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const r=this.normalizer(e);return null!=e&&null!=r&&this.store.set(r,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=r(40958),a=r(23838),l=s(r(68708)),u=r(59455),c=r(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const r of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(r,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const r=this.lookup(e);if(null!=r)return r;let i,n=-1;for(const[r,s]of this.m.entries()){const o=(0,c.diceCoeff)(r,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(i=e,n=o)}}return i}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),r=this.m.get(t);if(null!=r){for(const e of r)delete this.obj[e];this.m.delete(t)}return r}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const i=r(76790),n=r(31586),s=r(68708),o=r(54993),a=r(82647),l=r(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const r=this.get(e)+t;return 0===r?this.m.delete(e):this.m.set(e,r),r}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,r]of this.m.entries())e[(0,o.toS)(t)]=r;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,i.sortBy)([...this.entries()],(([t,r])=>[-r,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,r]of(0,i.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,r);return e}addAll(e){for(const[t,r]of e.entries())this.incr(t,r);return this}get toS(){return(0,i.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let r=0;for(const[i,n]of this.m.entries()){const s=e(i);t.fill(s,r,r+n),r+=n}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const i=r(19851),n=r(72993),s=r(45969),o=r(43334);t.EditionType=(0,i.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,i.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const i=r(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),r=t-this.ts;this.ts=t,(0,i.map)(this.listener,(t=>t(e,r))),r>2&&this.l.log(r>500?"warn":r>100?"info":"debug",e,{elapsedMs:r})}},t.elapsed=function(e){const t=Date.now(),r=e();return{elapsedMs:Date.now()-t,result:r}},t.thenElapsed=async function(e){const t=Date.now(),r=await e;return{elapsedMs:Date.now()-t,result:r}}},23467:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const i=r(50357),n=r(55835),s=r(68708);var o=r(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,i.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,i.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,i.eql,(()=>!1))},t.eqlPicked=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))},t.eqlOmit=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.omit)(e,...r),(0,s.omit)(t,...r))},t.eqlAsyncPicked=async function(e,t,...r){return(0,n.map2Or)(await e,await t,((e,t)=>(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))),(()=>!1))}},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(31586),a=r(54993),l=r(77377),u=r(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const r of this.expireListeners)r(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[i.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const r of this.expireListeners)r(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const r of this.expireListeners)r(e,t)}const r=this.priorCache[e];if(void 0!==r&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,r)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const r=this.currentCache[t]??this.priorCache[t];null!=r&&e(t,r)}}deleteIf(e){for(const t of this.keys()){const r=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=r&&e(t,r)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const r=t();return this.set(e,r),r}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=r(31586),d=r(85556),h=r(54993),f=r(54557),m=r(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,i.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,i,l(this,i,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,i,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,r,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(r=l(this,n,"f"),++r),"f"),c.promise):(u(this,i,(o=l(this,i,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,i,(a=l(this,i,"f"),++a),"f"),c}get(e){var t,r;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,i,(r=l(this,i,"f"),++r),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,i,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const r=this.get(e);if(null!=r){if(r instanceof Error)throw r;return r}return this.set(e,t())}getOrSetAsync(e,t){const r=(0,h.toS)(e);{const e=this.get_(r);if(null!=e)return e instanceof m.Deferred?e.promise:e}const i=new m.Deferred(this.opts.name).observe(t());return this.cache.set(r,i),(0,c.gt0)(this.opts.timeoutMs)&&i.setTimeout(this.opts.timeoutMs),i.promise.then((e=>{this.set(r,e)}),(e=>{var t,i;this.cache.set(r,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(i=l(this,a,"f"),++i),"f")})),i.promise}},i=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class i{constructor(e){this.maxSize=e,this[r]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(r=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=i},53507:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(31586),a=r(68708),l=r(50213),u=r(68852),c=r(81168),d=r(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,i.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,r=!0){return new m(e,t,r).entries};class m{constructor(e,t,r=!0){this.warnIfMissingHeaders=r,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const i=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,i).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let r=e;r!==t;t>e?r++:r--)if(this.blankColumns.has(r))return r;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),r=[];let i,a=0;for(;null!=(i=t.exec(this.headerRow));){const l=this.headerRow.substring(a,i.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:i.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(i.index,t.lastIndex),d=i.index+((0,c.indexOfNonSpace)(u)??0),h=i.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),g=e.find((e=>e.text===m));if(null==g||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:i,left:d,right:h});else{const e=(0,n.last)(r);if(r.push(g),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=g.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,i.index-((0,c.lastIndexOfNonSpace)(l)??l.length));g.leftIdx=g.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),g.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(r);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),r}}t.Fixed=m},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const i=r(51455),n=r(98553);var s=r(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const r=(0,n.parseJSON)(e);return null==r?void 0:t(r)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,i.readFile)(e)).toString())}},19851:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=r(57975),a=r(40958),l=r(50357),u=r(31586),c=r(65812),d=r(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),i.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,i,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const r=await e,i=await t;if(!(0,l.eql)(r,i))for(const e of this.watchers)e(i);null!=this.ttlMs&&this.ttlMs>0&&void 0!==i&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(42659),a=r(50213),l=r(81168),u=r(5916),c=r(56519),d=r(84777),h=r(44198),f=r(6012),m=r(43334),g=r(24399),p=r(63870);t.DefaultLocale="en";const y=(0,i.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?E():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,p.commandTimeoutMs)()}),t.envLocale=(0,i.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const r=w.exec(e.trim())?.groups;return null==r?void 0:(0,n.compact)([r.lang,r.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(g.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function E(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=E,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},50213:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const i=r(19851),n=r(32105),s=r(14593);t.rootLoggers=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},9103:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const i=r(98553),n=r(54557);t.memoize=function(e,t){let r=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return r++,s.getOrSet((0,i.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,i.stringify)(e)),o.size=()=>s.size,o.callCount=()=>r,o}},7282:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=i(r(1708)),s=r(38639),o=r(54993),a=r(19851),l=r(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(55835),a=r(31586),l=r(39926),u=r(54993),c=r(20014);var d=r(31586);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,r){return(0,o.orElse)(h(e,t),r)},t.mapGte0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>=0?t(r):void 0},t.mapGt0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>0?t(r):void 0},t.mapGt0=function(e,t){const r=(0,a.toInt)(e);return null!=r&&r>0?t(r):void 0},t.map2Gt0=function(e,t,r){const i=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=i&&i>0&&null!=n&&n>0?r(i,n):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(f.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(m(e))}function p(e,t){if(null==e||null==t)return;const r=[e,t].map((e=>e.toString(2))),i=Math.max(...r.map((e=>e.length)));return r.map((e=>(0,l.leftPad)(e,i,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let r=0;for(let i=0;ie/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,r){this.store[e*this.columns+t]=r}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(p(e,t),(([e,t])=>(0,i.count)([...e],((e,r)=>e!==t.charAt(r)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(p(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,i.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,r){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let i=0;const n=r*e.length;for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const i=r(40958),n=r(42659),s=r(96249),o=r(55835),a=r(31586),l=r(68708),u=r(34666),c=r(41583),d=r(48884),h=r(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const r={};for(const[i,n]of(0,l.entries)(e)){const e=t(i,n);null!=e&&(r[i]=e)}return r}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const r of e){const e=r();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(r=>t(r,e[r])?e[r]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,r){if(null!=e)return t(e);throw new Error(r)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,i.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[r,i]of m(t))null==e[r]&&(e[r]=i);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[r,i]of(0,l.entries)(t))null==e[r]&&(e[r]=i);return e},t.pickMap=function(e,t,r){const i={};for(const n of t)i[n]=r(n,e[n]);return i},t.mapEntries=g,t.mapNullEntries=function(e,t,r){const i={};let n=0;for(const s of(0,l.keys)(e))if(i[s]=t(s,e[s]),n++,(0,a.gt)(n,r))break;return i},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const r={};for(const i of(0,h.sortIgnoreCase)((0,l.keys)(t)))r[i]=e(t[i]);return r}return t},t.deepDelete=function e(t,...r){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...r))):g(t,((t,i)=>r.includes(t)?void 0:e(i,...r)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const r of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[r])return e[r]}},t.pairToObject=function(e,t){const r={};return r[e]=t,r},t.zipPojos=function(...e){const t={};for(const r of(0,i.uniq)((0,s.flatten)(e.map(l.keys))))t[r]=e.map((e=>e?.[r]));return t}},12801:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=i(r(48161)),s=r(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const i=r(41400),n=r(56409),s=r(31586),o=r(22911),a=r(73614),l=r(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:r,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const g=[];function p(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...i){f=!0,m=Date.now()+(0,s.max_)(t,r);const n=d=new o.Deferred(c);(0,s.gt0)(r)&&n.setTimeout(r);try{n.resolve(await e(...i))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),g.forEach((e=>e.resolve())),g.length=0}return n.promise}const w=(...e)=>{if(p()){if(!0===u)return null;const t=d?.promise;return h=e,(0,i.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return g.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>p(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const i=r(68708),n=r(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const r=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:r.push((0,i.pick)(n,"index","groups"));return r},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,r){const i=[];for(const t of e)try{i.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{i.push(s(t))}const n=0===i.length?t.NothingRegExp:i.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,r)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let r="",i=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(r+=t.source,i||(i=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):r+=s((0,n.toS)(t));return new RegExp(r,t??(i?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=i(r(48161)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(42659),u=r(41400),c=r(96249),d=r(31586),h=r(51926),f=r(54993),m=r(50213),g=r(12801),p=r(22277),y=r(84777),v=r(34102),w=r(43334),S=r(24399),b=r(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let E=!0;const M=(0,o.lazy)((()=>new p.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const r=(0,g.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=g.PriorityClassToNode[r]),E)try{return n.default.setPriority(e,t),t}catch(r){const i=-13===r?.errno||"EACCES"===r?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:i,error:r}),i)return;E=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&g.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,r):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,g.PriorityClassToPosix[r]??g.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+r),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=i(r(1708)),s=r(19851),o=r(40958),a=r(5670),l=r(54993),u=r(7282),c=r(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function g(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=g,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||g())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||g())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const i=r(59455);function n(e){return e instanceof Set?e:new Set((0,i.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,i.toA)(e.keys()).every((e=>t.has(e)))&&(0,i.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,r){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),r())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const r=n(t);return new Set([...e].filter((e=>r.has(e))))},t.diff=function(e,t){const r=n(t);return new Set([...e].filter((e=>!r.has(e))))}},12089:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=r(98553),d=r(34666),h=r(54993),f=r(62344),m=r(56038);t.shim1=function(e){return new g(e.name,e.impl,e.cache,e.toKey)};class g extends f.ExtensibleFunction{constructor(e,t,r,o){super(),i.add(this),this.impl=t,this.cache=r,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,i,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,i,"m",o).call(this,e),(()=>u(this,i,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,i,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,i=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const i=r(42659);t.ShortCommandTimeoutMs=7*i.secondMs},92322:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=r(76790),o=r(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,i.set(this,[])}[(i=new WeakMap,Symbol.iterator)](){return n(this,i,"f")[Symbol.iterator]()}get length(){return n(this,i,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,r=n(this,i,"f").length-1;for(;t<=r;){const s=t+Math.floor((r-t)/2),o=this.valueOf(n(this,i,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:r=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,i,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:r}){if(t>=this.length)return[...n(this,i,"f")];const o=t=>t<0||t>n(this,i,"f").length-1?null:(r??this.diff)(n(this,i,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return n(this,i,"f").shift()}at(e){return(0,o.at)(n(this,i,"f"),e)}toA(){return[...n(this,i,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,i,"f").length-1){const e=[...n(this,i,"f")];return n(this,i,"f").length=0,e}return n(this,i,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,i,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},82328:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const i=r(1708),n=r(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(i.stdout)}},71567:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=i(r(1708)),s=r(22573),o=r(98553),a=r(23560),l=r(82328),u=r(38835),c=r(70025),d=r(95705);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:r,stream:i}){if(null==i||(0,d.streamEnded)(i))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);i.write(n+"\n"),(0,a.isWorkerService)()&&null!=r&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?i.write(u.FailStr+"\n"):i.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const r of e)r.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(55835),a=r(31586),l=r(39926),u=r(34666),c=r(51926),d=r(59455),h=r(54993),f=r(48884),m=r(68852),g=r(38835);var p=r(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return p.splitFirst}});var y=r(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=r(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,r){if(0===r.length)throw new Error("rightPad() given empty pad");const i=String(e);return i+(0,l.padding)(r,t-i.length)},t.padReplace=function(e,t,r,i){return(0,c.strslice)(e,0,t)+(0,l.padding)(i,r)+(0,c.strslice)(e,t+r)},t.contains=function(e,t,r){return(0,h.toS)(e).indexOf((0,h.toS)(t),r)>-1},t.countChars=function e(t,r,i=0){if(null==r||0===r.length)return 0;const n=t.indexOf(r,i);return-1===n?0:1+e(t,r,n+r.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,r){const i=Math.min(Math.ceil(e.length/t),r??e.length)-1;return i<=0?[e]:[...(0,a.times)(i,(r=>e.slice(r*t,(r+1)*t))),e.slice(i*t)]},t.spliceCapture=function(e,t){const r=t.exec(e);if(null==r||null==r[1])return;const i=r[0].indexOf(r[1])+r.index;return{captured:r[1],uncaptured:e.substring(0,i)+e.substring(i+r[1].length),unmatched:e.substring(0,r.index)+e.substring(r.index+r[0].length),matchedIndex:i}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,r={}){if(null==t)return e;const i=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(i.slice(-n.length),n,r)?i.slice(0,-n.length):i},t.gist=function(e,t=80,r=80){const i=(0,h.toS)(e),n=i.length-(t+r);return n<=0?i:i.slice(0,t).trim()+" …(+"+n+" chars)…"+i.slice(-r).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const r=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===r?e.localeCompare(t):r}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,i.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,o.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const r=S(e.cmp[0],t.cmp[0]);return 0!==r?r:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,i.isEmpty)(e)||(0,s.blank)(t))return;for(const r of e)if((0,c.equalsIgnoreCase)(r,t))return{index:0,match:r};for(const r of e){const e=t.indexOf(r);if(e>=0)return{index:e,match:r}}const r=t.normalize();for(const t of e){{const e=r.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=r.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=r.toLowerCase(),i=e.toLowerCase(),n=t.indexOf(i);if(n>=0)return{index:n,match:i}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function E(e){return _.reduce(((e,[t,r])=>e.replace(t,r)),e).normalize()}t.dumbquote=E;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(E(e))&&(e=e.slice(1,-1).trim())),e};const C=/^['‘’].*['‘’]$/,T=/^["“”„«»〃].*["“”„«»〃]$/;function x(e,t){const r=D(e,t);return(0,f.flatZip)(r.nonSeparators,r.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+g.NonRetriableErrorFlag);const r=[],i=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,r.push(e.substring(s,n.index)),i.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),C.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const r=(0,i.compactBlanks)(e),n=Math.max(...r.map((e=>e.length)));for(let e=0;e(0,o.map)(r[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,i.compactBlanks)(e)),r=t.filter(((e,r)=>!P(t[r+1],e)));return(0,n.sortBy)(r,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const r=Math.min(e.length,t.length);for(let i=0;i4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const r=new Set;for(const i of(0,d.toA)(e))if(null!=i&&!(0,s.blank)(i))for(const e of i.split(t))(0,s.blank)(e)||r.add(e);return[...r].join(t)},t.dedupeNeedle=function(e,t,r){if((0,s.blank)(t))return e;const i=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>i.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(r)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const i=r(54993);function n(e){return(0,i.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>"_"+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>" "+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=i(r(77598)),s=r(73913),o=r(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,r=o.Radix58,i=224){return r.encodeBuffer(a(e,i)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,r=o.GeoRadix,i=224){return l(e,t,r,i)}},94863:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const i=r(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,i.toS)(e).toLowerCase().normalize()}},96859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(31586),a=r(39926),l=r(51926),u=r(54993),c=r(55222),d=r(97352),h=r(88158),f=r(77377),m=r(81168);function g(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const r=new d.Array2D(e.length);let i=0,n="";for(let s=0;s=i&&(i=r.get(s,o),n=(0,l.substr)(e,s-i+1,i)));return n}function p(e,t){if(null==e||null==t)return;if(e===t)return 0;const r=y(e,t);if(null!=r)return r;const i=e.normalize(),n=t.normalize();return e!==i||t!==n?y(i,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,r,i)=>r===t.charAt(i)?e:e+1),0)}function v(e,t){const r=e.toUpperCase().normalize(),i=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>r===i?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(r),t=w(i);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,r)=>e+t[r+1]))}function S(e,t){const r=(0,f.intersection)(e,t),n=[];return r.forEach((r=>{const s=Math.min((0,i.count)(e,(e=>e===r)),(0,i.count)(t,(e=>e===r)));(0,o.times)(s,(()=>n.push(r)))})),n}function b(e,t,r){const n=(0,i.commonPrefixLength)(e,t);return r((0,l.strslice)(e,n))-r((0,l.strslice)(t,n))}function P(e){const t=(0,i.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[r,i]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(r,i,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:g(e,t).length/Math.max(e.length,t.length)},t.lcs=g,t.hamming=p,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const E=/[^\da-z]+/gi;function M(e,t){const[r,i]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(E,"").toLowerCase()));return b(r,i,(e=>c.RadixAlphaNum.decode(e)))}function C(e,t){let r;for(let i=Math.max(e.length,t.length);i>=0;i--){const n=(0,o.mapNumericOr)(e.charCodeAt(i),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(i),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);r=null==r?a:(r+a)/2}return r}t.radixDiff=M,t.str=function(e,t){return{pref:(0,i.commonPrefixLength)(e,t),ham:p(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,i.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=C,t.paddedPositionalDiff=function(e,t,r=8){return C((0,a.leftPad)(e,r," "),(0,a.leftPad)(t,r," "))}},84885:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const i=r(98553),n=r(88158);t.stringifySorted=function(e){return(0,i.stringify)((0,n.sortedKeys)(e))}},22277:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=r(73614);class u{constructor(e,t=!1){i.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,i,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,i,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const r=this.delegate.get(e);return null==r||a(this,i,"m",n).call(this,e,r)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,r]of this.delegate)a(this,i,"m",n).call(this,t,r)||e(t,t,this)}has(e){return null!=e&&!a(this,i,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield[t,t])}()}toA(){return a(this,i,"m",s).call(this),[...this.delegate.keys()]}[(i=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const r=t<=Date.now()-this.ttlMs;if(r){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return r},s=function(){for(const[e,t]of this.delegate)a(this,i,"m",n).call(this,e,t)}},94174:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(38639),c=r(31586),d=r(50213),h=r(45255),f=r(84777),m=r(96706),g=r(43334),p=r(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>g.isWin?p.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>g.isWin?g.isWin?p.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.2-beta",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=2,t.versionPrerelease=["beta"],t.release="2024.3.2-beta+20240320133326",t.gitSha="f510a99f0cb85a261405b7831fbbc749dc164e15",t.gitDate=new Date(1710966806e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const i=r(42659),n=r(55835),s=r(31586),o=r(97790),a=r(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const r=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(r))return;const[o,a,u,c,d,h,f]=r,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*i.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+i.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class r extends Error{}t.AbortError=r},76740:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=r(45599),l=r(56409),u=r(73568);t.Abortable=class{constructor(){this._aborted=!1,i.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,i,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,i,"f")&&clearTimeout(s(this,i,"f")),o(this,i,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},i=new WeakMap,n=new WeakMap},22911:function(e,t,r){var i,n,s,o,a,l,u,c,d,h,f,m,g=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(r(87997)),w=y(r(57975)),S=r(45599),b=r(26905),P=r(55835),_=r(31586),E=r(68708),M=r(20214),C=r(57153),T=r(85556),x=r(50213),D=r(70025),k=r(95937),O="TIMEOUT",I=(0,S.defer)((()=>(0,x.mkLogger)("async.Deferred")));class A{static async*toAsyncIterable(e,t){const r=[...e].reverse(),i=(0,_.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=i&&r.push(i);;){for(let i=r.length-1;i>=0;i--){const n=r[i];if(n.isSettled){if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});r.splice(i,1),yield n.value}}if(r.every((e=>e.name===O)))break;try{await Promise.race(r)}catch{}}i?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var r,m,y;i.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,C.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(p(r=n,n,(y=g(r,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{p(this,u,e,"f"),p(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return g(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:g(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,E.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return g(this,o,"f")}get elapsedMs(){return(g(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,i=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=g(this,h,"f")&&(v.default.clearTimeout(g(this,h,"f")),p(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(p(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),g(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return g(this,a,"f")===C.PromiseStates.pending}get value(){return this.isResolved?g(this,l,"f"):void 0}get error(){return g(this,d,"f")}get isSettled(){return g(this,a,"f")!==C.PromiseStates.pending}get isResolved(){return g(this,a,"f")===C.PromiseStates.resolved}get isRejected(){return g(this,a,"f")===C.PromiseStates.rejected}get settledMs(){return null==g(this,o,"f")?void 0:g(this,o,"f")-this.startedAt}resolve(e){return g(this,i,"m",m).call(this,(()=>{p(this,a,C.PromiseStates.resolved,"f"),p(this,l,e,"f"),g(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return g(this,i,"m",m).call(this,(()=>{p(this,d,t,"f"),p(this,a,C.PromiseStates.rejected,"f"),g(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=A,n=A,m=function(e){if(g(this,a,"f")===C.PromiseStates.pending){(0,P.map)(g(this,h,"f"),v.default.clearTimeout),e(),p(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:g(this,l,"f")});return this},s={value:0}},27395:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const i=r(19851),n=r(40958),s=r(42659),o=r(23838),a=r(13538),l=r(50213),u=r(7282),c=r(97352),d=r(77740),h=r(25764),f=r(99331),m=r(73614),g=(0,i.lazy)((()=>(0,l.mkLogger)("async.Endable"))),p=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const r=await e;if(null==r||!0===r?.ended)return;const i=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,r.endTimeoutMs,y);g().trace(r.name+" ending...",{timeoutMs:i});try{await(0,a.thenOrTimeoutError)(r.end(),i,(0,u.isTest)())}catch(e){try{g().warn(r.name+".end() failed",e)}catch{}}}function w(){p.filterInPlace(((e,t)=>!0!==t.ended)),g().debug("vacuumEndables()",p.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),p.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,i.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;g().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const r=p.get(t)??[];(0,n.isNotEmpty)(r)&&(g().debug("endEndables(): ending "+t),await Promise.allSettled(r.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,n.compact)(p.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const r=p.get(t)??[];e[t]=r.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,r){var i,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=r(87997),h=r(55835),f=r(31586),m=r(68708),g=r(25764),p=r(38836),y=r(99331);class v extends p.EndableWrapper{constructor(e){super(e.name,(()=>u(this,i,"m",o).call(this)),e.rank??g.EndableRanks.first,e.endTimeoutMs),i.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,r=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!r&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,i,"m",o).call(this);const h=()=>{u(this,i,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,i,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,i=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const i=r(50989);t.EndableRanks=(0,i.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=r(19851),l=r(45599),u=r(56409),c=r(50213),d=r(27395),h=r(25764),f=r(99331),m=r(56519);t.EndableWrapper=class{constructor(e,t,r=h.EndableRanks.first,o){this.endTimeoutMs=o,i.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(r,this)}setName(e){o(this,i,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,i,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},i=new WeakMap,n=new WeakMap},99331:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const i=r(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,i.isTest)()?e:e||n}},45608:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=i(r(1708)),s=r(22573),o=r(45599),a=r(37975),l=r(50213),u=r(71567),c=r(57159),d=r(57902),h=r(28874),f=r(27395),m=r(99331),g=r(56038),p=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(g.PromiseTimer.instance().report())}));async function v(e){p().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const r=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==r.errno||!0===r.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const i=(0,s.toNotBlank)(e?.reason)??r.toString();for(const e of t.onFatalHandlers)await e(i)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(r=>{v({reason:`${e}:${t}`,status:0,error:r})}))}))},5916:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=r(45599),f=r(50357),m=r(31586),g=r(41583),p=r(62344),y=r(50213),v=r(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:r,timeoutMs:i}){return new S(e,t,r,i)};class S extends p.ExtensibleFunction{constructor(e,t,r,l){super(),i.add(this),this.later=e,this.desc=t,this.ttlMs=r,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,i,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,i,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,i,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=async function(e,t){var r;try{const r=await t;if(!(0,f.eql)(e?.value??await(e?.promise),r))for(const e of c(this,a,"f"))await e.onChange(r)}catch(e){const t=(0,g.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(r=c(this,s,"f"),++r),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,i,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},56519:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const i=r(40958),n=r(76790),s=r(38639),o=r(42659),a=r(41400),l=r(31586),u=r(20214),c=r(13538),d=r(42279),h=r(32639),f=r(59455),m=r(41583),g=r(48884),p=r(50213),y=r(88158),v=r(15674),w=r(42638);var S=r(20214);async function b(e){if(null==e)return[];const t=(0,i.compact)(await e);return(0,i.isEmpty)(t)?[]:(0,i.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:r,timeoutMs:n}){const s=[];for(const o of(0,i.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(r(o),n):r(o));null!=e&&s.push([e,o])}catch(t){(0,p.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:r,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,i.compact)(await e);if((0,i.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:r,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(r,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(r,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,p.mkLogger)(r).warn("failed to apply",{ea:e,error:t})}})));return(0,i.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,r){const i=[];for(const n of(0,g.batches)((0,f.toA)(await e),t)){const e=await b(n);i.push(...await b(r(e)))}return i},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const r of(0,i.compact)(e)){const e=await r();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;if(null!=e)if(Array.isArray(e))for(const r of e){const e=await r;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;null!=e&&t.push(e)}return(0,i.uniq)(t)},t.asyncFind=async function(e,t){for(const r of e)if(await t(r))return r},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:r,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,i.compact)(t),f:r,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const r=await E({name:"partitionAsync",arr:e,f:t});return[r.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),r.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,r=(e=>console.error(e)),i=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,i)}catch(e){r((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),r=(()=>{})){let i,n=null;try{i=await((0,h.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await r(n??i)}catch{}if(null!=n)throw n;return i},t.thenNot=async function(e,t=!0){if(null==e)return t;const r=await e;return null==r?t:!(0,s.isTrue)(r)},t.thenMap2=async function(e,t,r){const i=await e;if(null==i)return;const n=await t;return null!=n?r(i,n):void 0},t.thenMapOr=async function(e,t,r){const i=await e;if(null==i)return r();const n=await t(i);return null==n?r():n},t.thenMap2Or=async function(e,t,r,i){const n=await e;if(null==n)return i();const s=await t;if(null==s)return i();const o=await r(n,s);return null==o?i():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null==i)continue;const e=await t(i,r);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const r of e){const e=await r();if(null!=e){const r=await t(e);if(null!=r)return r}}},t.firstResolvedDefinedPromise=async function(e,t){for(const r of e)try{const e=await r();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const r of t)try{const t=await r();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:r}){const i=await E({name:e,arr:t,f:r});return(0,n.sortBy)(i,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const i=r(19851),n=r(40958),s=r(76790),o=r(42659),a=r(49769),l=r(31586),u=r(68708),c=r(42279),d=r(41583),h=r(22454),f=r(14121),m=r(50213),g=r(7282),p=r(34102),y=r(82647),v=r(25764),w=r(38836),S=r(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,r){const i=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-i)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-i;return r?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),r?.((0,d.toErr)(t),Date.now()-i),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),r=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),i=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",r.stats()],...i])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:r.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:(0,l.mapFinite)(r.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:r.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:{sumSec:(0,l.sigFigs)(r.sum/o.secondMs,3),...(0,u.omit)(r.stats(),"sum")}})),{})}}function _(e,t,r){return P.instance().time(e,t,r)}function E(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,i.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.isTest)()&&(0,p.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const r=Date.now(),i=t();return E(e,Date.now()-r),i},t.pushTime=E,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,r){return(0,i.lazy)((async()=>_(e,t)),r)}},42638:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(r(66261)),m=r(40958),g=r(55835),p=r(31586),y=r(42279),v=r(54993),w=r(89788),S=r(82647),b=r(15674),P=r(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){i.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,p.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:r,serialId:n}){const s=d(this,i,"m",l).call(this,{name:e,l:t,payload:r,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const r=t.map((t=>d(this,i,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(r)}serial(e,t,r){return this.enqueue({name:e,l:t,serialId:e,payload:r})}push(e,t,r){return d(this,i,"m",u).call(this,new P.Deferred(e,{payload:r}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),r=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,p.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=function({name:e,l:t,payload:r,serialId:i}){const n=new P.Deferred(e,{payload:r,serialId:i});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const r=Date.now();return this.lastWorkTs=r,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-r),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const r=new _(e);return()=>r.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:r}){return new _(e,(0,g.map)(r,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class r extends Error{}t.RedoableError=r},4867:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const i=r(40958),n=r(34546),s=r(41400),o=r(31586),a=r(83104),l=r(85556),u=r(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:r}){let a=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,r?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:r}){let l=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,r?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let r=e=>null;t.setTimeoutHandler=function(e){r=e},t.onTimeout=function({soft:e}={}){r(e)}},73614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const i=r(87997);t.setUnrefTimeout=function(e,t,...r){return(0,i.setTimeout)(e,Math.round(t),...r).unref()},t.setUnrefInterval=function(e,t,...r){return(0,i.setInterval)(e,Math.round(t),...r).unref()}},31562:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const i=r(38639),n=r(42659),s=r(41400),o=r(32639),a=r(31586),l=r(45255),u=r(95937);async function c(e,{timeoutMs:t,intervalMs:r,acceptable:i,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const i=r??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(i,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:i.isTrue,timeoutResult:!1})}},9727:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=i(r(1708)),s=r(45599),o=r(41400),a=r(50357),l=r(68708),u=r(48884),c=r(36638),d=r(44198),h=r(59958),f=r(96706),m=r(34102),g=r(19851),p=r(19043),y=r(66184),v=r(50213),w=r(7282),S=r(88158),b=r(45969),P=r(43334),_=r(28874),E=r(3790);function M(e){return C().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const C=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const r of t.names)e.add(r);for(const r of t.keys)e.add(r)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const T=["HOME","LANG","USER"],x=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],D=(0,g.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?T:x),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function k(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const r of(0,_.persistedSettings)()){const i=e?r.value:r.envValue;null==i||(0,a.eql)(i,r.defaultValue)||r.addToEnv(t)}return t}t.sanitizedEnv=(0,g.lazy)((()=>(0,l.filter)(n.default.env,(e=>M(e)||!(0,E.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=k,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:I({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function I({overrides:e,forceCLocale:r=!0,forWorker:i=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...D(),...r?(0,p.childProcLocale)():{},...k(i),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,E.isHiddenEnvKey)(e)?"(hidden)":t])),[r,i]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(r)),e.debug("non PS env:",(0,l.fromEntries)(i))}return n}t.childEnv=I},84777:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=i(r(31421)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(42659),c=r(98553),d=r(56409),h=r(31586),f=r(68708),m=r(51926),g=r(50213),p=r(7282),y=r(88158),v=r(79089),w=r(45255),S=r(22911),b=r(4867),P=r(73614),_=r(70025),E=r(57159),M=r(36868),C=r(66184),T=r(45643),x=r(95402),D=r(9727),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const r=e.pid;if(null==r||r<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(r===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(r===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+r+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,x.killPid)(r).catch((e=>{k().warn("endProcess(): kill("+r+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,p.isSingleSpecTests)())return!0;if(await(0,T.waitForPidExit)(r,t))return k().debug("endProcess(): exitted",O(e)),!0;{x.Pids.instance()?.onKill(r);const t=e.kill("SIGKILL");k().warn("endProcess("+r+") had to resort to SIGKILL",{killResult:t}),t||await(0,x.killPid)(r,!0).catch((e=>{k().warn("endProcess(): kill("+r+",true) failed: "+e)}))}return(0,T.waitForPidExit)(r,5e3)}function A(e,r,i,n=0){const o=new Date,a=[];return(0,v.niceable)(r,i)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,x.addPid)({pid:e.pid,cmd:r,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function F(e,t,r,i){const s=(0,D.spawnOptions)(i);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:r,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:r}),A(n.default.execFile(e,t,s),e,t,r)}async function N(e,t,r){const i=r.quiet??!1,n=r.ignoreStderr??!1,s=r.ignoreExitCode??!1,o=F(e,t,r.timeoutMs,(0,f.omit)(r,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===r.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],g=[],p=[],y=new S.Deferred(f);o.on("error",(e=>p.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>p.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>p.push(e))),o.stderr?.on("data",(e=>g.push(e))),o.stderr?.on("end",(()=>P.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:r.timeoutMs,halt:r.halt}),k().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt});const C=g.join("");(0,l.notBlank)(C)&&p.push(new Error(C)),!i&&(0,a.isNotEmpty)(p)&&k().warn(f+" resulted in errors:",p);const T=r.isIgnorableError??_.isIgnorableError,x=p.filter((e=>!0!==T(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:C}}catch(e){throw k().error("stdoutResult_() failed",e),await(0,x.killPid)(o.pid,!0),e}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,r,i){const s=(0,D.spawnOptions)(i);return k().debug("spawn()",{command:e,args:t,maxAgeMs:r}),A(n.default.spawn(e,t,s),e,t,r)},t.execFile=F,t.stdoutResult_=N,t.stdout_=async function(e,t,r){const i=await N(e,t,r);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(i.result),meta:{cmd:e,args:t,opts:r,result:i}})}},3790:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const i=r(22573),n=r(41400),s=r(19851),o=r(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,i.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},41269:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const i=r(1708),n=r(31586),s=r(51926),o=r(17344),a=r(37805),l=r(84542);function u(e,t){const r=t?.maxLineLen??(0,n.toInt)(i.env.maxLineLen)??i.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:r,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},94361:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const i=r(19851),n=r(40958),s=r(55835),o=r(31586),a=r(94174),l=r(44198),u=r(45969);function c(e,t,r){const i=(0,o.toGt0)((0,l.env)()[t]);return null==i||r.includes(i)?void 0:`WARNING: ${e} is running as ${r} but $${t}=${i}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,i.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},76596:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const i=r(51168),n=r(19851),s=r(22573),o=r(42659),a=r(55835),l=r(31586),u=r(68708),c=r(34666),d=r(50213),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,r){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=r}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const r=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),i=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(r,i)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),r=Date.now();return t<=r?0:t-r},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const i=r(22573),n=r(31586),s=r(54557),o=r(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,i.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,i.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const i=r(51168),n=r(40958),s=r(22573),o=r(42659),a=r(31586),l=r(51926),u=r(68852),c=r(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=i.Duration.fromISO(e);if(t.isValid)return t.toMillis();const r=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(r,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const r=(0,a.toFloat)(e);if(null!=r){if((0,s.blank)(t))return r;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*o.yearMs;case"weeks":case"week":case"w":return r*o.weekMs;case"days":case"day":case"d":return r*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return r*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return r*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return r*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return r;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,r=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const i=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const r=Math.floor(t/e.ms);t-=r*e.ms,r>0&&i.push(r+e.s)}return i.join(r)}},84248:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const i=r(50989);t.AutoVacuumModes=(0,i.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const i=r(50989);t.CheckpointTypes=(0,i.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const i=r(50989);t.RepairModes=(0,i.strEnum)("dump","recover")},34365:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const i=r(50989);t.SynchronousModes=(0,i.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(r(76760)),a=r(40958),l=r(22573),u=r(55835),c=r(72993),d=r(19851),h=r(97352),f=r(94174),m=r(44198),g=r(96706),p=r(8769),y=r(57159),v=r(70698),w=r(64680),S=r(29882),b=r(45969),P=r(43334),_=r(28874),E=r(41692),M=r(32774),C=r(80612),T=r(32551),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,g.getEnv)("TEMP"),(0,g.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const r of t)(0,l.blank)(r)||e.push({dir:(0,o.join)(r,".photostructure-cache"+x()),preexistingDir:r});return e}}function k(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:M.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(P.isWin?[(0,g.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,r=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return r.push(...D()),r}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,C.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,C.firstDir)({dirs:k(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,E.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(I)}));function I(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,p.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=I},46292:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const i=r(19851),n=r(45969),s=r(41692),o=r(32774),a=r(10924),l=r(84373),u=r(80612);t.configDir=(0,i.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const i=r(66430),n=r(45969),s=r(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,i.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=i(r(76760)),s=r(40958),o=r(72993),a=r(44198),l=r(96706),u=r(43334),c=r(80612),d=r(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const i=r(22573),n=r(96706),s=r(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,i.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const i=r(44652),n=r(40958),s=r(22573),o=r(66430);function a({dirs:e,desc:t}){for(const{dir:r,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(r)){if((0,o.isReadWriteableDirectorySync)(r))return r;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,i.mkdirpSync)(r),r}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const i=r(48161),n=r(76760),s=r(1708),o=r(19851),a=r(40958),l=r(68284),u=r(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,i.homedir)()}))},46296:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(55835),u=r(54993),c=r(72993),d=r(96706),h=r(45969),f=r(43334),m=r(32707),g=r(6707),p=r(49776),y=r(32774),v=r(80612),w=r(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,p.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,g.readTomlFileSync)((0,m.systemSettingsFile)()),r=(0,u.toS)(t?.logDir);return(0,a.notBlank)(r)?r:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const i=r(76760),n=r(19851),s=r(22573),o=r(44198),a=r(43334),l=r(24399),u=r(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,i.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const i=r(38639),n=r(7282),s=r(29325),o=r(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,i.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const i=r(38639),n=r(44198);t.doNotTrack=function(){return(0,i.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=i(r(73024)),s=r(76760),o=i(r(1708)),a=r(19851),l=r(40958),u=r(41400),c=r(68708),d=r(76850),h=r(7282),f=r(23560),m=r(32551),g=r(34102),p=r(53265),y=r(45969),v=r(59958),w=r(6012),S=r(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),r={...o.default.env};for(const i of e)try{const e=(0,d.debom)(n.default.readFileSync((0,p.resolve)(i))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,i]of(0,c.entries)(s))t.test(e)||(r[e]=i)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+i,e)}return r})),(0,u.later)((()=>{(0,g.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const i=r(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,i.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const i=r(50989);t.EnvKeys=(0,i.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const i=r(22573),n=r(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const r={};if((0,i.blank)(e))return r;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,i.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");r[t?e.toLowerCase():e]=o}}return r}},96706:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=i(r(1708)),s=r(19851),o=r(22573),a=r(38639),l=r(41400),u=r(40583),c=r(79840),d=r(83556),h=r(34102),f=r(44198),m=r(83373);function g(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=g,(0,l.later)((()=>{f.env.watchLater(g),(0,h.ee)().on("clearCache",g)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},98314:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const i=r(58587),n=r(19851),s=r(40958),o=r(22573),a=r(26905),l=r(96249),u=r(51926),c=r(23541),d=r(54993),h=r(89788),f=r(50213),m=r(81168),g=r(84542),p=r(41954),y=r(38835),v=r(70025),w=r(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,p.getErrorDescriptions)(e));const r=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,g.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(r)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const r=(0,s.uniqSubstrings)(b(e)),i=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(r.join(a.ErrorDelimiter)),i-o.length,n)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new i.Rate,t.fatalErrorRate=new i.Rate,t.internalErrorRate=new i.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const r=(0,d.toS)(t?.[e]);if((0,o.notBlank)(r))return r}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,r=256,i=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:r})+" at "+(0,a.shortStack)(e?.stack,i).join("; ")}},41954:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const i=r(40958),n=r(26905),s=r(55835),o=r(54993),a=r(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const r of e)(0,s.map)((0,n.errorErrno)(r),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(r),(e=>t.push(l[e]?.description)));return(0,i.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const i=r(40958),n=r(76790),s=r(50989),o=r(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,i.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const i=r(40958),n=r(38639),s=r(26905),o=r(54993),a=r(68852),l=r(73568),u=r(78656),c=r(98314),d=r(38835);function h(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const r=(0,o.toS)(e)+(0,i.compact)(t).join("");return h(r)+f(r).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const g=/Can't write [a-z\d]+ files/i,p=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const r=(0,c.errorToS)(e);return!g.test(r)&&(!!p.test(r)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const r=(0,c.errorToS)(e);return!(!r.includes("EBUSY")&&!r.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const r=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>r.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const i=r(22573),n=r(31586),s=r(68708),o=r(7282),a=r(23560),l=r(45608),u=r(34102),c=r(28874),d=r(98314),h=r(38835),f=r(70025),m=r(57159),g=r(5012);function p(e,t){try{if((0,i.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,g.stack)()),!1;const r=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===r.fatal,c=!0===r.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",r));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:r}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:r.toString(),status:r.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=p,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,r){return p(e+h.InternalErrorFlag,{cause:t,...r})}},57159:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const i=r(40958),n=r(22573),s=r(38639),o=r(26905),a=r(98553),l=r(68708),u=r(59455),c=r(41583),d=r(48884),h=r(81168),f=r(98314),m=r(38835),g=r(70025);t.toWrappedError=function(e,t){const r=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof p&&(null==t||(0,n.blank)(r.message)||e.message.includes(r.message)))return e;const i=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,r?.message);return new p(i??"(missing error message)",r)};class p extends Error{constructor(e,t={}){super(e),this.causes=(0,i.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const r=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??r.some(g.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(r.map(g.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(r.map(g.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(r.map(g.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,g.stripErrorFlags)(function(e,t){let r=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const i=t?.path;return(0,n.blank)(i)||(r=(0,h.dedupeNeedle)(r,i,"file")),(0,f.joinErrorMessages)([r[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...r.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new p(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=p},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=r(49769),a=r(55835),l=r(54993),u=r(22911),c=r(89788),d=r(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,i.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,i,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const r=this.target.emit(e,...t),o=s(this,i,"f").get(e);return null!=o&&(o.resolve(t),s(this,i,"f").delete(e)),r}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},i=new WeakMap,n=new WeakMap},34102:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const i=r(78474),n=r(19851),s=r(15197);t.ee=(0,n.lazy)((()=>{const e=new i.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=i(r(73024)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(65843),u=r(16287),c=r(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):p({stat:e,r:!0,w:!0,x:!0})}function g(e,t){return c.isWin?f(t,n.default.constants.R_OK):p({stat:e,r:!0,x:!0})}function p({stat:e,r:t=!1,w:r=!1,x:i=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(r&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!i||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=g,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const r of(0,l.selfAndAncestorG)(e)){const i=await(0,u.statMaybe)(r);if(null!=i){if(!i.isDirectory())return!1;if(t){if(!g(i,e))return!1}else if(t=!0,!m(i,e))return!1}}return!0},t.access=p},21144:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=i(r(76760)),s=r(19851),o=r(81168),a=r(57159),l=r(43334),u=r(88561),c=r(29882),d=r(65238),h=r(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const r=(0,c.parseNativePath)((0,h.resolve)(...e)),i=await m(r.dir);for(const e of await(0,d.readdir_)(i))if((0,o.equalsIgnoreCase)(e.basename,r.base))return n.default.join(i,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const i=r(73024),n=r(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,i.readdirSync)(e)}catch(e){return[]}}function l(e,t){const r=a(e);return t.every((e=>r.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,r){var i,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&l(t,e,r);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(r(44652)),g=c(r(73024)),p=r(51455),y=f(r(76760)),v=f(r(1708)),w=r(46466),S=f(r(57975)),b=f(r(38522)),P=r(19851),_=r(40958),E=r(5233),M=r(22573),C=r(42659),T=r(50357),x=r(96249),D=r(98553),k=r(55835),O=r(31586),I=r(68708),A=r(97790),F=r(39926),N=r(51926),L=r(59455),R=r(54993),j=r(48884),B=r(22911),V=r(99331),z=r(56519),W=r(56038),q=r(31562),U=r(76850),G=r(70025),H=r(34102),J=r(80875),K=r(50213),$=r(70417),Y=r(43334),Z=r(81168),X=r(96859),Q=r(65162),ee=r(94174),te=r(64660),re=r(21144),ie=r(84542),ne=r(89968),se=r(20197),oe=r(88561),ae=r(50597),le=r(33456),ue=r(29882),ce=r(78133),de=r(43899),he=r(65238),fe=r(53265),me=r(17217),ge=r(16287),pe=r(68284),ye=r(66003),ve=r(27794),we=r(73428),Se=r(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(i.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,K.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,i=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),r=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(r)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const r=(0,me.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,M.blank)(r))throw new Error("BaseFile.for(): empty nativePathOrFile");const i=be().get(r);if(null!=i)return i;const n=(0,fe.resolve)(r),s=new Pe(n,t);return be().set(r,s),be().set(n,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const r=[];for(const i of t)!0===await e(i)&&r.push(i);return r}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,i,"m",s).call(this)??await d(e=this.clearThisAndParent(),i,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const r of t)await r.visitDescendants(e),await e(r)}))}async descendants(e){const t=[];t.push(...(0,L.toA)(await this.childFiles(e)));const r=await this.childDirectories();if(null==r)return t;for(const i of r)t.push(...(0,L.toA)(await i.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const r=await d(this,n,"f").call(this)??[];for(const t of r)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const i of r)if(i.isDirectory()){const r=await this._directoryEntryChild(i).someDescendant(e,t-1);if(null!=r)return r}}descendantsSync(e){const t=this.directoryEntrySync(),r=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&r.push(this.forDirectoryEntry(t))})),r}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,re.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,r)=>this.join((0,R.toS)(e),(0,F.pad2)(t+1),(0,F.pad2)(r))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,r="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(r,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,r="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(r,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,r){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(r??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,ge.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,ge.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,C.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,ge.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>=(0,C.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(r=>Math.abs(r-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>(0,C.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,A.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,q.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*C.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,J.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,J.parseJSON)((0,g.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,g.readFileSync)(this.nativePath)}readFile_(){return(0,p.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return g.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,E.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,V.ending)()?1:3,timeoutMs:0,retryDelay:C.secondMs,errorIsRetriable:G.isRetriableError})}async gunzip(){return d(this,i,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,i,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,i,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return g.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return g.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const r=await this.children((async r=>!r.isNameHidden()&&t===r.size()&&r.nativePath!==e.nativePath));if((0,_.isEmpty)(r))return;const i=await e.sha();if(null!=i)for(const e of r.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===i)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),r=g.default.createReadStream(this.nativePath,{flags:"r"});return r.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),r.close()):t.maybeReject(e)})),r.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(r,(0,N.newlineRe)(),(i=>{const n=e.exec(i);null!=n&&(t.maybeResolve(n),r.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,r)=>{for(const i of e)for(const e of r)if((0,O.closeTo)(i,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),r=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&r.setTimeout(e.timeoutMs),_e)try{const i=(0,g.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(i,n)=>{try{const s=await e.f(i,(0,k.denull)(n));t(s)&&r.resolve(s)}catch(e){r.reject(e)}}));r.finally((()=>{i.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const i=setInterval((async()=>{try{const i=await e.f();t(i)&&r.resolve(i)}catch(e){r.reject(e)}}),e.intervalMs);e.persistent||i.unref(),r.finally((()=>{clearInterval(i)}))}return r}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const r=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([g.default.createReadStream(this.nativePath,{autoClose:!0}),t,g.default.createWriteStream(r.nativePath,{autoClose:!0})]),await this.unlink(),r}))},Pe.attrTTL=3*C.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},84542:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const i=r(40958),n=r(96249),s=r(51926),o=r(54993),a=r(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,i.compactBlanks)(l(...e))}},70698:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const i=r(76760),n=r(19851),s=r(50213),o=r(37805),a=r(29882),l=r(93854),u=r(17217),c=r(16287),d=r(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const r=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return r===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,i.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const r=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(r),await(0,d.writeTextfile_)((0,a.joinNativePath)([r,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(45969),u=r(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(r(44652)),l=o(r(73024)),u=r(76760),c=r(57975),d=r(19851),h=r(59455),f=r(50213),m=r(81168),g=r(34102),p=r(29882),y=r(65238),v=r(14427),w=r(17217),S=r(16287),b=r(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class E{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,p.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new E(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:r,base:i}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,p.parseNativePath)(e)},n=await a.stat(t);return new E(r,new P(i,n))}clear(){return(0,g.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return E.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,p.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,p.parseNativePath)(this.dir);return e.dir===this.dir?this:new E(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>E.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new E(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const r of t)r.isDirectory()&&await r.visitDescendants(e);for(const r of t)r.isFile()&&await e(r);for(const r of t)r.isDirectory()&&await e(r)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const r of t)r.isFile()&&e(r);for(const r of t)r.isDirectory()&&(r.visitDescendantsSync(e),e(r))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async r=>{!0===await e(r)&&t.push(r)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,g.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,g.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=E},20197:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=i(r(76760)),s=r(39926),o=r(29882),a=r(16287),l=r(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if(await(0,o.mkdirp_)(i.dir),!r.requireNumber&&await(0,a.isEmptyFile)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if(await(0,a.isEmptyFile)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)},t.ensureNewNativePathSync_=function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if((0,o.mkdirpSync_)(i.dir),!r.requireNumber&&(0,l.isEmptyFileSync)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if((0,l.isEmptyFileSync)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)}},88561:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=r(40958),a=r(22573),l=r(41400),u=r(68708),c=r(25764),d=r(38836),h=r(34102),f=r(80049),m=r(50213),g=r(88158),p=r(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:p.ShortCommandTimeoutMs,...e}),i.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,i,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,g.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,i=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const i=r(73024),n=r(22573),s=r(45599),o=r(96249),a=r(68708),l=r(54993),u=r(49047),c=r(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...r]of d)for(const i of r)e[i]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof i.Dirent?e.name:(0,l.toS)(e),r=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(r)?void 0:h()[r]??r}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const r of t)if(r===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const i=r(68708),n=r(17217),s=r(16287),o=r(68284);async function a(e){return(0,i.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,i.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},4001:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const i=r(22573),n=r(55835),s=r(31586),o=r(51926),a=r(54993),l=r(97352),u=r(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,i.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,r){if(t.ymdIsoRE.test(e))return e;let i=e;for(const e of r.aggressive?d:c){const t=i.match(e);if((0,s.gt0)(t?.index)){const e=i.slice(0,t.index).trim();e.length>0&&(i=e)}}return e===i?e:f(i,r)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),r=t.pop();if((0,i.blank)(r))return e;const n=(0,u.parsePosixPath)(r),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),r=h(t),i=(0,o.stripPrefix)(t.toLowerCase().normalize(),r);return(0,n.map)((0,l.extractInt)(i),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,g=/(?<=.{6})_cover$/i,p=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(g,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(p.exec(t),(e=>t=e[1].trim())),t}},50597:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=i(r(77598)),s=i(r(73024)),o=r(46466),a=r(19851),l=r(98553),u=r(68708),c=r(23467),d=r(80049),h=r(73913),f=r(50213),m=r(12089),g=r(37628),p=r(43624),y=r(17217),v=r(16287),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:r=!0}={}){const i=(0,y.toNativePath_)(e);if(r){const t=S().get(i);if(null!=t){if((0,c.eql)(t.stats,await(0,p.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:i,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:i,prior:t}),S().delete(i)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),r=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(r)),stats:(0,u.pick)(await(0,v.stat_)(r),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],r="sha512"){const i=n.default.createHash(r);return await(0,o.pipeline)([e,...t,i]),i.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,g.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},25675:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const i=r(22573),n=r(54993),s=r(7282),o=r(43334),a=r(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,i.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const i=r(57075),n=r(51926),s=r(54993);class o extends i.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,r){const i=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=i.pop();this._prior=o??"";let a=!1;for(const e of i)a||(a=!this.push(e));a?setTimeout(r,1):r()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=i(r(76760)),s=r(17217),o=r(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},29882:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(5233),u=r(22573),c=r(98553),d=r(39426),h=r(51926),f=r(48884),m=r(50213),g=r(81168),p=r(70025),y=r(43334),v=r(78133),w=r(53265),S=r(17217),b=r(16287),P=r(66430),_=r(5545);function E(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=E,t.containsHiddenPathname=function(e){return k(e).some(E)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!E(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return C((0,v.posix2native)(e))},t.extname=function(e){return C(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,g.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function C(e){const t=M.exec(e)?.groups,r=t?.ext2??"",i=s.default.parse(t?.path??e);return{...i,ext:(i.ext??"")+r,base:(i.base??"")+r}}function T(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),r=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(r))return!1;const i=e.acceptSelf??!1;return t===r?i:r.startsWith((0,g.ensureSuffix)(t,s.default.sep))}catch(r){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:r}),!1}}function D(e,t,r){if(null==t||null==r)return!1;const i=e(t),n=e(r);return null!=i&&null!=n&&(y.isLinux?i===n:(0,g.equalsIgnoreCase)(i,n))}function k(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&k(e).length===(y.isWin?1:0)}function I({p:e,maxLength:t}){const r=(0,S.toNativePath_)(e);if(r.length<=t)return r;const i=k(e),n=[],s=[i.pop()];for(;i.length>0;)if(n.length=t){i.unshift(n.pop());break}}else if(s.unshift(i.pop()),F([...n,...s]).length>=t){i.push(s.shift());break}return i.length>0&&n.push("…"),F([...n,...s])}function A(e){return e.startsWith("\\\\")}function F(e){return(0,h.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=C,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(S.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const r=(0,S.toNativePath_)(e),i=(0,S.toNativePath_)(t);if((0,u.blank)(r)||(0,u.blank)(i))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return r===i?"":(0,g.stripPrefix)((0,v.native2posix)(i).normalize(),(0,g.ensureSuffix)((0,v.native2posix)(r),"/").normalize()).normalize()},t.ellipsizePath=I,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:r=4,arrLength:i=e.length}){const n=[];for(const i of e.slice(0,r))n.push(I({p:i,maxLength:t}));return n.join(", ")+(i>r?`, and ${i-r} more…`:"")},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const r=C(e);return`${r.base}${t}${r.ext}`},t.isUNC=A,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(A(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(31586),u=r(51926),c=r(12168),d=r(59455),h=r(54993),f=r(50213),m=r(44198),g=r(96706),p=r(45969),y=r(43334),v=r(64660),w=r(21144),S=r(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const r=await(0,S.statMaybe)(e,"trace");return null!=r&&r.isFile()&&(0,l.gte)(r.size,t)&&(0,v.isStatRX)(r,e)}function E(){if(y.isWin){const e=(0,a.toNotBlank)((0,g.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,g.getEnv)("SystemDrive"))??"C:",r=(0,a.toNotBlank)((0,g.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(r,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,p.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...E()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:r}){const i=(0,o.uniq)((0,o.compactBlanks)([...M(),...(0,d.toA)(r)]));for(const r of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(r,".exe"):r;for(const t of i){const r=n.default.join(t,e);if(await _(r))return y.isLinux?r:(0,w.actualPath)(r)}}b().warn("Failed to find tool",{tool:e,dirs:i})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},78133:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=i(r(76760)),s=r(22573),o=r(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const r=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",i=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(i[0],t)&&i.unshift(),r+i.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(48884),u=r(50213),c=r(45969),d=r(29325),h=r(43334),f=r(65843),m=r(25675),g=r(53265);function p(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(n.default.join((0,g.execDir)(),"resources"),n.default.join((0,g.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,g.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const r of t){if((0,f.hasChildrenSync)(r,e))return r;for(const t of(0,f.ancestors)(r).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const i=n.default.join(r,"node_modules","photostructure");if((0,f.hasChildrenSync)(i,e))return i}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:p("bin"),Data:p("data"),ICC:p("data","icc"),Migrations:p("data","migrations"),Public:p("public"),Tools:p("tools"),Views:p("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const i=r(44652),n=r(19851),s=r(31586),o=r(50213),a=r(57902),l=r(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,i.readFile)(e)}catch(r){return void u().log(t,".readFileMaybe("+e+")",r)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const i=r(44652),n=r(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:r}){let s=-1;try{const n=r??(await(0,i.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,i.open)(e,"r"),await(0,i.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,i.close)}}},69428:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(r(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},32323:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const i=r(57075);class n extends i.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=i(r(51455)),s=r(76760),o=r(19851),a=r(76790),l=r(22573),u=r(42659),c=r(41400),d=r(31586),h=r(13538),f=r(83104),m=r(54127),g=r(50213),p=r(95937),y=r(34102),v=r(28874),w=r(63870),S=r(88561),b=r(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,g.mkLogger)("fs.Readdir")));async function _(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const E=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||E.prior()?.delete(e)}async function C(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await E().getOrSetAsync(e,(()=>async function(e){const r=Date.now()+2*(0,b.statTimeoutMs)(),i=T(e),n=await(0,h.thenOrTimeout)(i,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===f.Timeout&&(0,p.onTimeout)({soft:!1}),n!==f.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),E.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!E().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=E().get(e)},t.childDirectories_=async function(e){return(await C(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?C(e):T(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=C,t.readdirCached=function(e){return E().get(e)},t.readdirUncached_=T},53265:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=r(73024),s=i(r(76760)),o=r(40958),a=r(22573),l=r(45599),u=r(50213),c=r(43334),d=r(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function g(...e){for(const t of m()){const r=s.default.resolve(t,...e);if((0,n.existsSync)(r))return r}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?g(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=g},50274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const i=r(50989);t.SidecarExts=(0,i.strEnum)("xmp","mie","exv")},14427:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const i=r(22573),n=r(38639);t.isSimpleDirent=function(e){return null!=e&&(0,i.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=i(r(73024)),s=i(r(76760)),o=r(22573),a=r(98553),l=r(81168),u=r(43334),c=r(29882),d=r(53265),h=r(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function g(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=g,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(g(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const p=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(p)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),r=t.indexOf(s.default.sep);return r>0?t.slice(1,r):void 0}},t.findFileIndex=function(e,t){for(let r=0;r(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,p.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((r=>{y().log(t,"stat() failed",{error:r,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const r=S(e),i=S(t);if(r!==i)return"inconsistent file type: "+r+" ≠ "+i;for(const r of["size","mtime"]){const i=e[r],n=t[r],s=(0,u.diff)(b(i),b(n));if(null==s||s>1)return"unmatched "+r+": "+i+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const r=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=r&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(r)},t.isNonEmptyFile=async function(e,t=0){const r=await w(e);return null!=r&&r.isFile()&&r.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.access)({stat:r,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.isStatRWX)(r,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=i(r(73024)),s=r(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const r=o(e);return t.emptyIsNew?null==r:a(r)},t.isNonEmptyFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const i=r(28874);t.statTimeoutMs=function(){return i.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const i=r(22573),n=r(56409);t.onDataChunked=function(e,t,r){const i=new s(t,r,!0);return i.read(e),i.done};class s{constructor(e,t,r=!0){this.sep=e,this.onData=t,this.filterBlanks=r,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,i.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,i.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=i(r(57075)),s=r(41400),o=r(55835),a=r(68708),l=r(42279),u=r(99331),c=r(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((r,i)=>{!1===e.write(t,(e=>{e&&i(e)}))?e.once("drain",r):r()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:r,ea:i}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(i,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(r,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends n.default.Transform{constructor(e){super({transform:(e,t,r)=>{this.onProgress(this.bytes+=e.length),r(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=i(r(73024)),s=r(76760),o=r(22573),a=r(76596),l=r(64660),u=r(78133),c=r(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},27794:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=i(r(44652)),s=r(19851),o=r(22573),a=r(42659),l=r(31586),u=r(68708),c=r(13538),d=r(29882),h=r(17217),f=r(16287),m=r(41080);function g(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const r=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const i=(0,h.toNativePath_)(t.file);r&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(g(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),p=Math.round(g(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(i,new Date(p),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!r||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(i),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},5545:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=i(r(76760)),s=r(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const r=t.driveRe.exec(e)?.groups;return null==r?e:r.drive.toUpperCase()+(0,s.toS)(r.path??n.default.sep)}},58722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const i=r(57075),n=r(22911);class s extends i.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,r){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),r()}}t.WritableToBuffer=s},73428:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(51926),a=r(54993),l=r(34102),u=r(84542),c=r(29882);async function d(e,t){const r=s.default.dirname(e);await(0,c.mkdirp_)(r),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",r)}function h(e,t){const r=s.default.dirname(e);(0,c.mkdirpSync_)(r),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",r)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const r=(0,u.crlf)(...(0,o.wrap)(t));await d(e,r)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=i(r(73024)),s=r(76760),o=r(46466),a=r(38522),l=r(19851),u=r(40958),c=r(98553),d=r(80875),h=r(50213),f=r(57159),m=r(29882),g=r(57902),p=r(32323),y=r(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,r){const i=[],s=[n.default.createReadStream(e,{autoClose:!0,...r}).on("error",(e=>i.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>i.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>i.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(i))throw new f.WrappedError("zPipe("+e+") failed",{causes:i,path:e})}async function b(e,t){const r=new y.WritableToBuffer;return await S(e,r,t),await r.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const r=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new p.ReadableBuffer(r),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=g.LogLevels.warn){try{return await P(e)}catch(r){return void v().log(t,"readJsonGz("+e+"): failed",r)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,r=g.LogLevels.warn){try{await _(e,t)}catch(t){v().log(r,"outputJsonGz("+e+"): failed",t)}}},33866:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const i=r(50989);t.HealthCheckIds=(0,i.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},52086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const i=r(50989);t.CropStrategies=(0,i.strEnum)("center","entropy","attention")},48584:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const i=r(50989);t.SharpFailOns=(0,i.strEnum)("none","truncated","error","warning")},32105:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const i=r(19851),n=r(23560),s=r(66184),o=r(72210);class a{log(e,t,r,i){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:r,meta:i})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,i.lazy)((()=>new a))},14593:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const i=r(57975),n=r(22573),s=r(26905),o=r(55835),a=r(68708),l=r(13538),u=r(50213),c=r(97352),d=r(45255),h=r(76740),f=r(57159),m=r(57902),g=/logger|lazy/i;class p{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!g.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[i.inspect.custom](){return this.toLogJSON()}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const r=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(r),this.log(!0===r.ignorable?"warn":"error",".throw() "+r.message,{stack:r.stack,...t}),r}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let r;try{r=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const i=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:i,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(r,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const r of this.loggers())if(r.enabled(e,t??this.context))return!0;return!1}log(e,t,r){for(const i of this.loggers())i.log(e,this.context,t,r)}elapsed(e,t,r){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...r})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=p},28981:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const i=r(19851),n=r(51879);t.DefaultLogFormatter=(0,i.lazy)((()=>new n.PlaintextLogFormatter))},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},4904:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const i=r(76790),n=r(31586),s=r(51926),o=r(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,i.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const i=r(19851),n=r(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,i.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,i.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,r){return(0,t.logFilter)().enabled(e)?r():void 0},t.isLogged=function(e,r){return(0,t.logFilter)().enabled(e,r)}},57902:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const i=r(31586),n=r(50989),s=r(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,r){return(0,i.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(r))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},72210:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const i=r(92322),n=r(82328),s=r(28981),o=r(20839),a=r(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new i.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const r of e)l?t.logEntries.add(r):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(r))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},51879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(68708),a=r(54993),l=r(23560),u=r(81168),c=r(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,i.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:r,meta:i})}}},82647:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=r(57975),a=r(40958),l=r(96249),u=r(55835),c=r(31586),d=r(68708),h=r(59455),f=r(48884),m=r(89788),g=r(22454),p=r(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const r=t.clone();return r.pushAll(e.samples),r}if(t.n<=t.maxSamples){const r=e.clone();return r.pushAll(t.samples),r}{const r=new y(Math.max(e.maxSamples,t.maxSamples));r._n=e.n+t.n,r._min=Math.min(e._min,t._min),r._max=Math.max(e._max,t._max),r._m=e._m*e.n/r.n+t._m*t.n/r.n,r._s=e._s*e.n/r.n+t._s*t.n/r.n;const i=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return r._samples.push(...i),r._weightedTotalAvg=(0,p.weightedAvg)([r._m,...i]),r}}constructor(e=20){i.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(i=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,p.min)([this._min,e.min]),this._max=(0,p.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),r={};return r.k=t(this.n),this.empty||(r.mean=t(this.avg),r.sum=t(this.sum),r.sd=t(this.stdDev),r.max=t(this.max),r.min=t(this.min)),r}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,i,"m",n).call(this,-1)}get p29(){return s(this,i,"m",n).call(this,-.5)}get p38(){return s(this,i,"m",n).call(this,-.25)}get p69(){return s(this,i,"m",n).call(this,.5)}get p84(){return s(this,i,"m",n).call(this,1)}get p98(){return s(this,i,"m",n).call(this,2)}get p99(){return s(this,i,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new g.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,p.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,p.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,p.avg)}get sampleSlope(){return(0,p.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,p.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const i=r(40958),n=r(55835),s=r(31586),o=r(30976),a=r(48884),l=r(70417);function u(e,t){const r=Math.pow(2,t),i=[];for(;e>0;)i.unshift(e%r),e=Math.floor(e/r);return i}t.concatBits=function(e,t){const r=Math.pow(2,t);return e.reduce(((e,t)=>e*r+(0,s.clamp)(0,r,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,r){return(0,n.map2)(e,t,((e,t)=>(0,i.sum)((0,a.zip)(u(e,r),u(t,r)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,r[t]=o):i[t]=o}return s}unzip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max));for(let n=0;n(r[e]+i[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,r){return!0!==r&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let r=0;rs?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const r=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,i.sum)(e,((r,i)=>t(r,i)?Math.pow(2,e.length-i-1):0))}},55222:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const i=r(77598),n=r(22573),s=r(55835),o=r(32639),a=r(88158),l=r(81168),u=BigInt(0);function c(e,t,r=0){if(!isFinite(t)||e<=1)return[];const i=[];if(0===t)i.unshift(0);else for(;t>0;)i.unshift(t%e),t=Math.floor(t/e);for(;i.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const r=e<0;return r&&(e=Math.abs(e),t--),(r?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],r=BigInt(this.base);let i=e;for(;i>u;)t.push(Number(i%r)),i/=r;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let r of e)for(t.forEach(((e,i)=>{r+=e<<8,t[i]=r%this.base,r=Math.floor(r/this.base)}));r>0;)t.push(r%this.base),r=Math.floor(r/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const r=BigInt(this.base);let i=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;i=i*r+BigInt(e)}return t?BigInt(-1)*i:i}randomChars(e){return this.encodeBuffer((0,i.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,r="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(r)}tokenEql(e,t,r){const i=this.normalizeToken(e),n=this.normalizeToken(t);return i.length>=r&&i===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const i=r(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,i.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},70417:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=r(40958),l=r(55835),u=r(31586),c=r(59455),d=r(22454),h=r(77377),f=r(82647);function m(e){let t;for(const r of e)null!=r&&(null==t||rt)&&(t=r);return t}function y(e,t){const r=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&r.incr(t);return r.topKeys(t)}function v(e,t){let r=0,i=0;for(const n of e){if(null!=n){const e=t(n,r);(0,u.isNumber)(e)&&(i+=e)}r++}return i}t.min=m,t.max=p,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,r)=>e-t[r]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const r of e)(0,u.isNumber)(r)&&(t+=r);return t},t.sumf=v;class w{constructor(){i.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,i,"f")/(s(this,i,"f")+1)+e/(s(this,i,"f")+1),"f"),o(this,i,(t=s(this,i,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const r of e)t.push(r);return t.mean}function b(e){const t=S(e);if(null==t)return;let r=0,i=0;for(const n of e)(0,u.isNumber)(n)&&(i++,r+=(n-t)*(n-t));return r/i}function P(e){let t=0;for(const r of e)t+=r*r;return Math.sqrt(t)}function _(e,t){let r=0;for(let i=0;i(1-t)*e+t*(r+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),r=S(t);if(null!=r){const e=(t.length-1)/2,i=v(t,((t,i)=>(t-r)*(i-e))),n=v(t,(e=>(e-r)**2));return 0===n?0:i/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let r;t=(0,u.clamp)(0,1,t);for(const i of e)r=null==r?i:r*t+i*(1-t);return r},t.centroid=function(e){const t=e[0].length,r=[];for(let i=0;ie[i]))));return r},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},45969:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const i=r(73024),n=r(38639),s=r(19851),o=r(59958),a=r(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,i.existsSync)("/.running-in-container"))))},29325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const i=r(76760),n=r(19851),s=r(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,i.join)("core","platform","IsPacked"))))},43334:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(22573),a=r(38639),l=r(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=i(r(73024)),s=r(19851),o=r(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const i=r(58587),n=r(59455),s=r(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(i.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,i.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=r(58587),d=u(r(31421)),h=u(r(1708)),f=r(40958),m=r(22573),g=r(42659),p=r(55835),y=r(31586),v=r(97790),w=r(59455),S=r(54993),b=r(54557),P=r(19851),_=r(50213),E=r(88158),M=r(409),C=r(78406),T=r(25764),x=r(99331),D=r(56519),k=r(46292),O=r(8769),I=r(83278),A=r(32144),F=r(29882),N=r(43334),L=r(24399),R=r(58261),j=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),B=10*g.secondMs;function V(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const r=(0,p.map)(t.start,(e=>e.getTime())),i=e.startTime;return(0,y.gt0)(r)&&(0,y.gt0)(i)&&Math.abs(r-i){const e=Date.now()-2*g.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,A.isJsonExt)(t)&&(0,F.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:g.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,r=e.force??N.isWin,i=await this.pidfiles(),n=await this.pids(i??[]);if((0,f.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,R.pidInfos)(n);if(null!=a){for(const n of i){const i=await n.readJson();if(null==i){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=i.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:i,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!V(i,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:i,pidEntry:u}),await n.unlink("debug"),s.push(i);continue}const c=(0,y.gt0)(i.timeoutMs)?i.startTime+i.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(i.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:i}),o.push(W(l,r,!1)),s.push({...i,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,r=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(r&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const r=a(this,i,"m",s).call(this,e.pid),n=(0,v.opt)((0,E.Try)((()=>(0,F.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await r.writeJson_(l),j().debug("addPid() wrote "+r,l),r}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,i,"m",s).call(this,e);return(0,D.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,g.ago)(g.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new C.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*g.minuteMs,rank:T.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=q,n=new WeakMap,o=new WeakMap,i=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},q.instance=(0,P.lazy)((()=>(0,p.map)((0,k.configDir)(),(e=>new q(I.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return q.instance()?.addPid_(e,t)}},58261:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=r(31421),s=r(48161),o=i(r(1708)),a=r(40958),l=r(22573),u=r(42659),c=r(31586),d=r(68708),h=r(59455),f=r(54993),m=r(48884),g=r(53507),p=r(19851),y=r(50213),v=r(84968),w=r(48963),S=r(56519),b=r(84777),P=r(8103),_=r(45879),E=r(43334),M=r(24399),C=r(45643),T=(0,p.lazy)((()=>(0,y.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){if(E.isLinux)return async function(e){const t=[];for(const r of e)t.push(z(await(0,_.readFileMaybe)("/proc/"+r+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,C.existingPids)(e),r=(await(0,m.collectBatchedAsync)(t,20,E.isWin?A:R)).filter((e=>x(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:r,meta:{pids:e}})}t.isProcEntry=x,t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,C.existingPids)(e),(t=>{const r=[o.default.pid,...t];return e.filter((e=>!r.includes(e)))}))},t.pidInfos=D;const k="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function A(e){if(M.PowerShell.instance().ended)return L(e);const t=[k,"-Id",I(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},N=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const r=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",r)}t.push("get",N.join(","));const r=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),i=(0,d.onlyReqValued)((0,g.parseFixed)(N,r.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return i.find((e=>e.pid===o.default.pid))||i.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),i}async function R(e){return t=(await(0,b.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,g.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=L;const j=(0,p.lazy)((()=>{try{if(E.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){T().warn("clk_tck failed",{error:e})}return 100})),B=(0,p.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),V=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function z(e){const t=V.exec((0,f.toS)(e))?.groups,r=(0,c.toInt)(t?.pid),i=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(r)&&!(0,l.blank)(i)&&(0,c.gt0)(n)?{pid:r,cmd:i,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},24399:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const i=r(58587),n=r(19851),s=r(22573),o=r(42659),a=r(41400),l=r(55835),u=r(13538),c=r(36557),d=r(14121),h=r(50213),f=r(7282),m=r(45255),g=r(81168),p=r(25764),y=r(38836),v=r(99331),w=r(56519),S=r(31562),b=r(84777),P=r(34102),_=r(43334),E=r(28874),M=r(63870),C="{ready}",T=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),p.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new i.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",E.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${C}"}`,...(0,s.mapNotBlankOr)(E.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:C,fail:"Error",exitCommand:"exit",maxProcs:E.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),p.EndableRanks.postdb),E.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(E.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,g.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const r=this.mockResults.get(e);return t(r.stdout,r.stderr,r.passed)}try{const r=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new i.Task(e,((r,i,n)=>t((0,l.map)(r,(t=>(0,g.stripPrefix)(t,e))),i,n)))));return this.logger.tap({msg:"execute()",result:r.result,meta:{elapsedMs:r.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,g.ensureSuffix)(e,T),((e,t,r)=>({stdout:e,stderr:t,passed:r})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const r=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,g.ellipsize)(t.stdout),after:(0,g.ellipsize)(r)}),JSON.parse(r)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,n.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const i=r(50989);t.AggregateTypes=(0,i.strEnum)("union","intersection")},71988:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const i=r(50989);t.AssetFileSortCriteria=(0,i.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const i=r(22573),n=r(38639),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(i.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const i=r(50989);t.ColorDistanceFunctions=(0,i.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const i=r(36507),n=r(22573),s=r(45599),o=r(50213),a=r(81168),l=r(98314),u=r(8769),c=r(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,i.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,r){try{return(0,n.blank)(t)?void 0:(0,i.Cron)(t,{name:e,unref:!0,protect:!0,catch:r=>(0,u.onError)(r,{name:e,crontab:t}),...r})}catch(r){return void d().warn("invalid cron",{name:e,crontab:t,error:r})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const i=r(70488),n=r(91655),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration})}get valueOrDefault(){return(0,i.decodeDuration)(super.valueOrDefault)}get value(){return(0,i.decodeDuration)(super.value)}set value(e){super.userValue=(0,i.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,i.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,i.decodeDuration)(this.defaultValue)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const i=r(22573),n=r(53265),s=r(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,i.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const i=r(51926),n=r(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,i.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=r(19851),a=r(40958),l=r(79666),u=r(50357),c=r(57924),d=r(98553),h=r(55835),f=r(68708),m=r(39926),g=r(46891),p=r(42279),y=r(59455),v=r(40583),w=r(81168),S=r(44198),b=r(96706),P=r(34102),_=r(28283),E=r(81075),M=r(98778),C=r(10357);t.settingsToObj=function(e){const t={};for(const r of e)r.hasValue()&&(t[r.name]=r.value);return t},t.Setting=class{constructor(e){i.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,i,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const r=this.opts.whyInvalid?.(e);return null!=r?s(this,i,"m",n).call(this,e??t)+": "+r:null==this.fromEnv(e)?s(this,i,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const r=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=r)return r}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const r=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(r)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return E.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,p.tot)(this.optsOverrides.defaultValue)??(0,p.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,p.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const r=e??(0,S.env)(),i=t??this.value;return null!=i&&(r[this.key]=this.toEnv(i)),null==e&&b.caseInsensitiveEnv.unset(),r}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const r=e??(0,S.env)(),i=this.toEnvValue(t);return null!=i&&(r[this.key]=i,null==e&&b.caseInsensitiveEnv.unset()),r}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const r of t.delete(e)??[])delete process.env[r];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],C.WrapComments);function r(e,r){(0,a.isEmpty)(r)||t.push(...(0,w.wrap)(["",(1===r.length?e:(0,g.pluralize)(e))+": "+(0,c.orList)(r.map((e=>(0,d.stringify)(e))))],C.WrapComments))}r("alias",this.opts.aliases),r("environment alias",this.altKeys);for(const[e,r]of(0,f.entries)(this.addToJSON())){const i=Array.isArray(r)?(0,c.orList)(r.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(r);t.push(...(0,w.wrap)(["",e+": "+i],C.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Example value:"],key:this.name,value:(0,p.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Default value:"],key:this.name,value:(0,p.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,p.tot)(this.fileValue)}),e}},i=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const i=r(50989);t.SettingCategories=(0,i.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const i=r(58587),n=r(51168),s=r(76760),o=r(19851),a=r(40958),l=r(76790),u=r(22573),c=r(42659),d=r(73722),h=r(68708),f=r(50989),m=r(12168),g=r(54993),p=r(37975),y=r(9092),v=r(40583),w=r(79840),S=r(7282),b=r(12801),P=r(4328),_=r(70488),E=r(84248),M=r(5531),C=r(99315),T=r(34365),x=r(34580),D=r(96706),k=r(50274),O=r(33866),I=r(52086),A=r(48584),F=r(45969),N=r(43334),L=r(24540),R=r(70379),j=r(71300),B=r(33209),V=r(48987),z=r(68268),W=r(61208),q=r(99023),U=r(30577),G=r(1485),H=r(19861),J=r(55111),K=r(30933),$=r(22859),Y=r(71988),Z=r(38483),X=r(90536),Q=r(75164),ee=r(10546),te=r(90967),re=r(67958),ie=r(55948),ne=r(57039),se=r(9945),oe=r(74589),ae=r(844),le=r(96093),ue=r(23561),ce=r(69005),de=r(87652),he=r(81075),fe=r(58305),me=r(57571),ge=r(72564),pe=r(80372),ye=r(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new pe.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new pe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new pe.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,p.noColor)()}),logContextLimit:new oe.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new pe.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>G.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:G.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>G.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>N.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new pe.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new pe.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,F.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new ge.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:J.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!N.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new i.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>N.isMac?"100ms":N.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new pe.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:E.AutoVacuumModes,defaultValue:E.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:C.RepairModes,defaultValue:C.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,F.isDocker)()}),skipHealthCheckIds:new ge.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new pe.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>N.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new pe.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:U.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new pe.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new pe.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new pe.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,K.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:k.SidecarExts,defaultValue:k.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new pe.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ie.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:re.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,K.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:I.CropStrategies.attention,strEnum:I.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(N.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:A.SharpFailOns.truncated,strEnum:A.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>V.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:R.DateTagFormats.ym,strEnum:R.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:q.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,F.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,r]of(0,h.entries)(t.Settings))r._setName(e);function be(e){const r=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,F.isDocker)()&&r.unshift("/opt/photostructure/tools/bin"),r.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(r).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,D.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const r of(0,t.persistedSettings)()){for(const t of r.names)e.set(t,r);for(const t of r.keys)e.set(t,r)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,g.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const i=r(19851),n=r(31586),s=r(7282),o=r(49776),a=r(46292),l=r(32774),u=r(55086),c=r(46296),d=r(55939),h=r(96706),f=r(83278),m=r(92234),g=r(45969),p=r(60865),y=r(30933),v=r(15674),w=r(28874);t.setSettingsDefaults=(0,i.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,g.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=p.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const i=r(76760),n=r(40958),s=r(22573),o=r(98553),a=r(55835),l=r(59455),u=r(19851),c=r(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function h(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",i.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const r=t.split("|");for(const t of r)e.set(t,r)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const i=r(40958),n=r(98553),s=r(55835),o=r(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,i.uniq)(e)))),fromEnv:t=>{return r=t,n=e.strEnum,(0,i.compact)((0,o.splitStringArray)(r)?.map((e=>n.getCI(e))));var r,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const i=r(22573),n=r(81168),s=r(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,i.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const i=r(76760),n=r(55835),s=r(46292),o=r(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,i.join)(e,o.SettingsToml)))}},80496:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const i=r(50989);t.TagInferenceSettingValues=(0,i.strEnum)("never","always","auto")},6707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const i=r(90858),n=r(44652),s=r(22573),o=r(76850),a=r(50213),l=r(81168),u=r(84542),c=r(17217),d=r(68284),h=r(98778);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,i.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const i=r(22573),n=r(96249),s=r(98553),o=r(68708),a=r(51926);function l(e,t,r){if((0,i.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,i.blank)(r?.prefix)?[n]:(0,a.wrap)(n.split("\n"),r)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,i.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},65162:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const i=r(4001),n=r(81168);t.bname=function(e,t=!0){let r=(0,n.isString)(e)?e:e.name;return t&&(r=(0,i.stripCopySuffixFromName)(r)),r=(0,n.trimLeftPadding)((0,i.stripDSC)(r)),r.toLowerCase().normalize()}},70379:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const i=r(50989);t.DateTagFormats=(0,i.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},68268:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const i=r(50989);t.KeywordReparentingStrategies=(0,i.strEnum)("move","copy","retain")},61208:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const i=r(50989);t.NameTagFormats=(0,i.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const i=r(50989);t.NameTagOrders=(0,i.strEnum)("western","eastern")},60865:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const i=r(37805),n=r(30577);t.channel=function(){return(0,n.extractUpdateChannel)(i.version)},t.baseVersion=()=>[i.versionMajor,i.versionMinor,i.versionPatch].join("."),t.versionMajorMinor=i.versionMajor+"."+i.versionMinor},30577:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const i=r(50989);t.UpdateChannels=(0,i.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const r of t.UpdateChannels.values)if(e.includes("-"+r))return r;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},1485:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const i=r(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,i.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69375:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const i=r(19851),n=r(22573),s=r(50213),o=r(9103),a=r(7282),l=r(29882),u=r(43334),c=r(28874),d=(0,i.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,g=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function p(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),r=t[0],i=t[t.length-1];return c.Settings.excludedRootDirectories.has(r)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(i)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===r&&!1===m?.test(e)?"LinuxRunRE":!0===g?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=p(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=p},63870:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const i=r(42659),n=r(12168),s=r(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/i.secondMs},55111:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const i=r(50989);t.HelmetPlugins=(0,i.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},30933:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=i(r(48161)),s=r(19851),o=r(42659),a=r(31586),l=r(50213),u=r(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),r=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??r)),meta:{availableParallelism:e,cpuInfoLength:r}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=i(r(48161)),s=r(19851),o=r(31586),a=r(12168),l=r(50213),u=r(45879),c=r(70417),d=r(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),r=(2*e+t)/3;if((0,d.isDocker)()){const i=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(i))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([i,r]),meta:{freemem:e,totalmem:t,cgroupMem:i}})}return h().tap({msg:"estimatedFreeMem() ",result:r,meta:{result:(0,a.fmtBytes)(r),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},15674:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const i=r(19851),n=r(42659),s=r(41400),o=r(31586),a=r(12168),l=r(50213),u=r(7282),c=r(34102),d=r(57902),h=r(28874),f=r(30933),m=r(58444),g=r(22751),p=(0,i.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,i.lazy)((()=>{const e=(0,o.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*a.MB;return p().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,r=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return p().tap({msg:"timeoutPenalization()",level:r>1?d.LogLevels.warn:d.LogLevels.debug,result:r,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,i.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const r=g.timeoutRate.prior()?.eventsPerMinute??0,i=w();if(1!==i){const e=t;t*=i,p().warn("Recent timeouts! Throttling down.",{penalization:i,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),p().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:i,timeoutsPerSecond:r,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,i.lazy)((function(){return(0,o.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const i=r(58587),n=r(87997),s=r(19851),o=r(42659),a=r(41400),l=r(50213),u=r(7282),c=r(45255),d=r(34102),h=r(976),f=r(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new i.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const g=(0,s.lazy)((()=>(0,n.setInterval)(p,o.minuteMs).unref()));function p(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),g()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),p()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const i=r(76790),n=r(22573),s=r(50357),o=r(98553),a=r(49769),l=r(34666),u=r(30976),c=r(42279),d=r(32639),h=r(59455),f=r(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function g(e){return null==e||0===(0,h.toA)(e).length}function p(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,r)=>e===t[r]))}function v(e,t){for(let r=0;r=e.length||r>=e.length)return e;const i=e[t];return e.splice(t,1),e.splice(r,0,i),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&(0,a.getOrSet)(r,e,(()=>i))}return[...r.values()]}function P(e,t,r=1,i=(e=>e)){const n=[];if(et;s-=r)n.push(i(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=g,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,r){return m(e)?t(e):(0,c.tot)(r)},t.toPrimitive=p,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let r=0;rt.includes(e)))},t.includesAll=function(e,t){if(g(e)||g(t))return!1;for(const r of t)if(!e.includes(r))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const r=(0,i.sortBy)(e,p),n=(0,i.sortBy)(t,p);return r.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const r of t)null==r||e.some((e=>(0,s.eql)(e,r)))||e.push(r);return e},t.pushUniqBy=function(e,t,r){const i=e.map(r);for(const n of t){const t=r(n);i.includes(t)||(e.push(n),i.push(t))}return e},t.insertAt=function(e,t,...r){return e.splice(t,0,...r),e},t.insertUniq=function(e,t,r){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let i=0;i0)return e.splice(i,0,t),e}return e.push(t),e},t.remove=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),r!==e.length},t.removeSame=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>e!==t)))),r!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const r of e)null==r||(0,s.eql)(t[t.length-1],r)||t.push(r);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const r=[];for(const e of(0,i.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))r.some((t=>t.includes(e)))||r.push(e);return(0,i.sortBy)(r,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&r.set(e,i)}return[...r.values()]},t.uniqBy2=function(e,t){const r=[];for(const i of e)null!=i&&r.every((e=>!t(i,e)))&&r.push(i);return r},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,r,i)=>e+(t(r,i)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,r,i)=>e+t(r,i)),0)},t.firstMatch=function(e,t){for(const r of S(t)){const t=e.exec(r);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let r=0;for(;e[r]===t[r];)r++;return r},t.anneal=function({array:e,expense:t,allowedDelta:r}){const i=Math.round(r);if(i<2)return e;for(let r=0;re)){return P(e,t,1,r)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,r,i=t.primitiveValueOfOrElse){const n=new Set(r.map(i));return e.filter((e=>!n.has(i(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const i=r(40958),n=r(36783),s=r(41801),o=r(98553),a=r(49769),l=r(55835),u=r(34666),c=r(59455);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const r=new Map;for(const i of e)(0,a.getOrSet)(r,(0,o.stringify)(t(i)),(()=>i));return f(r.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,l.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,i.compact)(e),i.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,r)=>0===r||t>=e[r-1]))},t.sortedBy=function(e,t){return e.every(((r,i)=>0===i||t(r)>=t(e[i-1])))},t.sortBy=f,t.deepSortBy=function e(t,r){return f(t,r).map((t=>(0,s.isIterable)(t)?e(t,r):t))},t.pushSorted=function(e,t,r){const i=e.findIndex((e=>r(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const i=r(32639);t.asPromise=async function(e){const t=await e;return(0,i.isFunction)(t)?t():t}},5233:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const i=r(41400),n=r(31586),s=r(13538),o=r(41583);t.retryOnReject_=async function(e,t){const r=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return r();const a=t.onRetryWaitUntil??(e=>(0,i.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await r()}catch(e){const r=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(r)||l>t.maxRetries)throw r;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},22573:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const i=r(55835),n=r(42279),s=r(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const r=(0,s.toS)(e);return a(r)?t(r):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const r=(0,s.toS)(e).trim();return r.length>0?r:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,r){return(0,i.orElse)(l(e,t),r)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function r(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function i(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const r=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(r)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=r,t.toBoolean=function(e){return!!r(e)||!i(e)&&void 0},t.toNotBoolean=function(e){return!r(e)&&(!!i(e)||void 0)},t.boolToInt=function(e){return r(e)?1:0},t.isFalse=i,t.isDisabled=function(e){return i(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>r(e)))},t.and=function(e){return e.every((e=>r(e)))},t.maybeAnd=function(e){let t;for(const r of e){if(!1===r)return!1;!0===r&&(t=!0)}return t},t.mapBoolean=function(e,t){return r(e)?t(!0):i(e)?t(!1):void 0},t.mapTrue=function(e,t){return r(e)?t():void 0}},79666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const i=r(98553);t.clone=function(e){return null==e?e:JSON.parse((0,i.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const i=r(40958),n=r(22573),s=r(30301),o=r(55835),a=r(31586),l=r(39926),u=r(51926),c=r(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function g(e){return e instanceof Date}function p(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=g,t.thisYear=function(){return(new Date).getFullYear()},t.ago=p,t.hence=function(e,t){return p(-e,t)},t.unixtime=function(e){const r=g(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(r/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,r={includeMs:!0}){const i=Math.floor(e/t.hourMs);e-=i*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(i)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(r.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const r=()=>{const e=t%100;return t=Math.floor(t/100),e},i=10*r(),n=r(),s=r(),o=r(),a=r(),l=r();return new Date(t,l-1,a,o,s,n,i)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,r="ago"){return e<1e3?"just now":(r=(0,n.blank)(r)?"":(0,u.ensurePrefix)(r," "),et.ms<=e)))){const s=Math.floor(e/i.ms);e-=s*i.ms,s>0&&(i.ms>=t.dayMs?r:n).push(s+i.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+r.join("")+((0,i.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=g(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const i=r(38639),n=r(73872);function s(e,t,r){if(null==r||y(e)||y(t))return null;const i=r.get(e)?.get(t);return"boolean"==typeof i?i:null}function o(e,t,r,i){if(null==r||y(e)||y(t))return;let n=r.get(e);null!=n?n.set(t,i):(n=new WeakMap,n.set(t,i),r.set(e,n))}function a(e,t,r,i){if(null!=r?.comparator)return u(e,t,r,i);const n=l(e,t);return null!==n?n:u(e,t,r)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,r,i){r??(r={});const u=!1===r.memoize?void 0:r.memoize??(r.memoize=new WeakMap),d=r?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const r=d(e,t,i);if(!1===r||!0===r)return o(e,t,u,r),r;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,r,i){switch(r){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return g(e,t,["name","message","code"],i);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,i);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,r){return c(h(e),h(t),r)}(e,t,i);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),i);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),i);case"Set":case"Map":return function(e,t,r){if(e.size!==t.size)return!1;if(0===e.size)return!0;const i=[],n=[];return e.forEach((function(e,t){i.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(i.sort(),n.sort(),r)}(e,t,i);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return p(e,t,i)}}(e,t,y,r);return o(e,t,u,v),v}function c(e,t,r){const i=e.length;if(i!==t.length)return!1;if(0===i)return!0;let n=-1;for(;++n{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,r,i=!1;const n=function(){if(i){if(null!=r)throw r;return t}try{return i=!0,t=e()}catch(e){throw r=e,e}};return n.prior=()=>t,n.hasPrior=()=>i,n}},41400:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const i=r(42659),n=r(35556),s=r(31586),o=r(68708);function a(e,t=!0){return new Promise((r=>{if(e<=0)r();else{const s=setTimeout((()=>r()),Math.ceil(e+.5));e>i.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const r=Math.max(1,Math.ceil(t)),s=n.isNode&&r<=1?setImmediate(e):setTimeout(e,r);return n.isBrowser||t<=i.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},50357:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const i=r(12487),n=r(68708),s=r(34666),o=r(32639);function a(e,t){return(0,i.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const r of(0,n.keys)(e))if(!a(e[r],t[r]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,r){if(null==e||null==t)return e===t;if(null!=r){const i=d.get(r);if(null!=i)return i(e,t)??null}for(const r of c){const i=r(e,t);if(null!=i)return i}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(31586),a=r(68708),l=r(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const r=[];for(const t of e)null!=t&&(t instanceof Error?r.push(u(t),c(t),t?.message):r.push((0,l.toS)(t)));return(0,i.uniq)((0,i.compactBlankish)((0,s.flatten)((0,i.compact)(r).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const r=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,i.isEmpty)(r)?["(missing stack)"]:r}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},96249:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const i=r(59455);t.flatten=function(e,t=[]){for(const r of(0,i.toA)(e))if(null!=r)for(const e of(0,i.toA)(r))null!=e&&t.push(e);return t}},57924:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const i=r(40958);function n(e,t){return null==(e=(0,i.uniq)((0,i.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},73722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const i=r(50989);t.FitSizes=(0,i.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,i.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const i=r(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,r){if((0,i.lt0)(t))return[...e].slice(t,r);const n=e[Symbol.iterator]();if((0,i.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,r){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(r))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],r=[];return function e(i,n){if((0,isFunction_1.isFunction)(i))return;let s,o,a,l=toJSON(i);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(i===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let i=0;t.Latch=class{constructor(e=i++){this.id=e,this[r]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},r=Symbol.toStringTag},30301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const i=r(40958),n=r(50357),s=r(31586),o=r(65812);t.lazy=function(e,t){let r,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return r=Date.now(),async function(e,r){if((0,i.isEmpty)(l))return;const s=await e,a=await r;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==r||(0,s.gt0)(t)&&r+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,r){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const i=r();return null!=i&&e.set(t,i),i}},t.deleteIf=function(e,t){for(const[r,i]of e.entries())t(r,i)&&e.delete(r)}},55835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const i=r(42279),n=r(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,r){return null==e||null==t?void 0:r(e,t)}function a(e,t){return null!=e?e:(0,i.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,r,i){return null==e||null==t||null==r?void 0:i(e,t,r)},t.orElse=a,t.mapOr=function(e,t,r){return null!=e?t(e):(0,i.tot)(r)},t.map2Or=function(e,t,r,i){return a(o(e,t,r),i)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const i=r(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,i.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const i=r(40958),n=r(76790),s=r(50357),o=r(98553),a=r(49769),l=r(55835),u=r(51926),c=r(59455);class d{static fromJSON(e){const t=new d;for(const[r,i]of Object.entries(e))t.add(r,...i);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,i.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const r=(0,a.getOrSet)(this.store,e,(()=>[]));return r.push(...t),r}addUniq(e,...t){return(0,i.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const r=this.store.get(e);if(null==r)return!1;{const i=r.filter((e=>!(0,s.eql)(e,t)));return 0===i.length?this.store.delete(e):this.store.set(e,i),r.length!==i.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,i.uniq)(t))){for(const t of this.keys()){const r=this.store.get(t),n=null==r?[]:e(t,r);(0,i.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,i.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield[t,r])}()}tuples(){const e=this;return function*(){for(const[t,r]of e.store.entries())for(const e of(0,c.toA)(r))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[r,n]of this.store.entries()){const s=(0,i.findIndexes)(n,(t=>!e(r,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(r)}return t}inverse(){const e=new d;for(const[t,r]of this.store.entries())for(const i of r)e.add(i,t);return e}findKeyByTuple(e){for(const[t,r]of this.tuples())if(e(t,r))return t}filterKeysByTuple(e){const t=[];for(const[r,i]of this.entries())i.some((t=>e(r,t)))&&t.push(r);return t}toJSON(){const e={};for(const[t,r]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=r;return e}}function h(e,t){const r=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>r.add(t,e))))),r}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const r=h(e,t);return(0,n.sortBy)((0,c.toA)(r.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const r=globalThis;t.isBrowser="object"==typeof r?.window&&"object"==typeof r?.document,t.isNode="string"==typeof r?.process?.versions?.node},31586:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const i=r(76790),n=r(22573),s=r(42279),o=r(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,r)=>a(t)&&a(r)&&e(t,r);function f(e,r,n){return!(null==n||!a(n))&&([e,r]=(0,i.sort)([e,r]),(0,t.lte)(e,n)&&(0,t.gte)(r,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function p(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return p(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const r=Math.pow(10,t);return P(e*r)/r}function E(e,t,r){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${r})`);return a(r)?rt?t:r:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,r=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(r>=1)return!1;const i=(0===t?1e-5:t)*(1-r);return f(t-i,t+i,e)},t.within=f,t.max_=function(...e){let t;for(const r of e)a(r)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const r=y(e);return null==r?void 0:t(r)},t.mapFloat=function(e,t){const r=v(e);return null==r?void 0:t(r)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,r){return b(e,(e=>b(t,(t=>r(e,t)))))},t.mapNumericOr=function(e,t,r){return a(e)?t(e):r},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const r=t-P(Math.ceil(Math.log10(Math.abs(e)))),i=Math.pow(10,Math.abs(r));return r<0?P(e/i)*i:P(e*i)/i},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!w(e))return[];const r=Math.round(e);return r<=0?[]:[...Array(r)].map(((e,r)=>t(r)))},t.pct=function(e,t){return E(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const r=Math.round(e??-1);return null==t||f(0,t,r)?r+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const r of e){if(!a(r))return;t+=r}return t}},68708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(32639),a=r(55835),l=r(31586),u=r(34666),c=r(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function g(e){return h(e).map((t=>e[t]))}function p(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const r of e)if(null!=r&&Array.isArray(r)){const[e,i]=r;null!=e&&void 0!==i&&("object"!=typeof t&&(t={}),t[e]=i)}return t}function v(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>null!=e)))return e;const r=t.filter((([,e])=>null!=e));return(0,i.isEmpty)(r)?void 0:y(r)}function w(e,t,r={}){return y((0,i.compact)((0,n.sort)(h(e)).map((r=>t(r,e[r])))).filter((([e,t])=>null!=e&&void 0!==t)),r)}function S(...e){const t=(0,i.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const r=t.filter(d);if(t.length!==r.length)return t;const n={};for(const e of(0,i.uniq)((0,i.flatMap)(r,h)))n[e]=S(...r.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const r=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(r.test(t))return{key:t,value:e[t]}}function P(e){return g(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const r=v(e);return m(r)?t(r):void 0},t.values=g,t.entries=p,t.fromEntries=y,t.assignFields=function(e,t,r){if(null==t)return e;for(const[i,n]of p(t))!0!==r?.omitKeys?.includes(i)&&(null==n&&!0!==r?.assignNullish||(e[i]=n));return e},t.assignUndefinedFields=function(e,t,...r){if(null==t)return e;for(const i of r){const r=t[i];void 0!==r&&void 0===e[i]&&(e[i]=r)}return e},t.assignAllFields=function(e,t){for(const[r,i]of p(t??{}))e[r]=i;return e},t.definedValues=function(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>void 0!==e)))return e;const r=t.filter((([,e])=>void 0!==e));return(0,i.isEmpty)(r)?void 0:y(r)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,i.compact)(t.map(e));{const r=(0,i.compact)(p(t).map((([t,r])=>(0,a.map)(e(r),(e=>[t,e])))));return 0===r.length?void 0:y(r)}}},t.compactBlankValues=function(e){if(null==e)return;const t=p(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,i.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickCompact=function(e,...t){if(null==e)return;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickNonBlank=function(e,...t){if(null==e)return e;const r={};for(const i of t){const t=e[i];(0,s.notBlank)(t)&&(r[i]=t)}return r},t.pickFirst=function(e,t,r=a.defined){if(null!=e)for(const i of t)if(r(e[i]))return e[i]},t.pickDeep=function e(t,...r){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...r)));const i={};function n(e,t){if(null==t)return;const r=i[e];i[e]=null==r?t:S(r,t)}for(const i of r){const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const i of h(t))((0,l.toInt)(i)??-1)>=0&&n(i,e(t[i],...r));return i},t.pluck=b,t.pluckDeep=function e(t,r){if(null==t||(0,s.blank)(r))return;if(Array.isArray(t)){const n=(0,i.compact)(t.map((t=>e(t,r))));return(0,i.isEmpty)(n)?void 0:{key:n[0].key,value:(0,i.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(r,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const r=p(e).filter((([e])=>!t.includes(e)));return(0,i.isEmpty)(r)?void 0:y(r)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(p(e).filter((([e,r])=>t(e,r))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,i.uniq)(t)},t.maybeCall=function(e,t,...r){const i=e?.[t];return(0,o.isFunction)(i)?i.bind(e)(...r):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const r=t.toLowerCase().normalize();for(const t of h(e))if(r===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const r=w(t,((t,r)=>[t,e(r)])),i=g(r);return 1===i.length?i[0]:r}},97790:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(r||(r={})),t.None=r;class i{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new i(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,r){return s(e).flatMap((e=>s(t).flatMap((t=>r(this.a,e,t)))))}zip3(e,t,r,i){return s(e).flatMap((e=>s(t).flatMap((t=>s(r).flatMap((r=>i(this.a,e,t,r)))))))}}function n(e){return e instanceof i||e===t.None}function s(e){return n(e)?e:null!=e?new i(e):t.None}t.Some=i,t.isOpt=n,t.opt=s},39926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const i=r(31586),n=r(54993),s={};function o(e,t){if(t<1)return"";if(!(0,i.gte)(s[e]?.length,t)){let r=s[e]??e;for(;r.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const i=r(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,i.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const i=r(40958),n=r(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,r){return o(e)?t(e):r()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,r){if(null==e&&null==r)return 0;if(null==e)return-1;if(null==r)return 1;const i=typeof e,s=typeof r;if(!("string"!==i&&"symbol"!==i||"string"!==s&&"symbol"!==s)){const i=(0,n.toS)(e),s=(0,n.toS)(r),o=i.localeCompare(s);return i[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(r)?u(e,r):i!==s?a.indexOf(i)-a.indexOf(s):e>r?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const i=r(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const r=await e;return null==r?void 0:t(r)},t.thenCollect=async function(e,t){const r=[];for(const n of(0,i.toA)(await e))if(null!=n){const e=await n;if(null!=e){const i=await t(e);null!=i&&r.push(i)}}return r},t.thenTap=async function(e,t=console.dir.bind(console)){const r=await e;return await t(r),r},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:r}){const i=await e;return t(i)?r(i):void 0}},57153:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const i=r(50989);t.PromiseStates=(0,i.strEnum)("pending","resolved","rejected")},30976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const i=r(40958),n=r(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,r){return null==r||0===r.length?s(e,t):a(e,t,1,r)[0]}function a(e,t,r,i){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(i??[]);if(t===e&&0===n&&0===o.size&&1===r)return[e];const a=n-o.size;if(r>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:r,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const r=Math.floor(Math.random()*(e+1));e!==r&&([t[e],t[r]]=[t[r],t[e]])}return t},t.sample=function(e,t){const r=[];for(const i of a(0,e.length,t))r.push(e[i]);return r},t.pickWeightedRandom=function(e){if((0,i.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let r=l(0,(0,i.sum)(t,(e=>e.priority)));return t.find((e=>(r-=e.priority,r<=0)))}},5670:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const i=r(50989);t.ServiceNames=(0,i.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const r=e.indexOf(t);return-1===r?[e]:[e.slice(0,r),e.slice(r+t.length)]}},50989:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const i=r(68708),n=r(42279);t.strEnum=function(...e){const t=Object.freeze(e),r=(0,i.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?r[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const r=o(e),i=o(t);return null==r||null==i?void 0:r>i?1:r{const r=o(e);return null==r?void 0:t[r]}}}},51926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const i=r(40958),n=r(17586),s=r(22573),o=r(96249),a=r(41801),l=r(31586),u=r(59455),c=r(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,r){if(d(e))return t<0&&(t+=e.length),e.slice(t,r);{const i=f();return null!=i?(0,a.sliceIterable)(i.segment(e),t,r).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,r).join("")}}function g(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function p(e,t){const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.startsWith(i)?r.slice(i.length):r}function y(e,t){if(null==t)return e;const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.endsWith(i)?r.slice(0,-i.length):r}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,r){null==r&&(r=e.length);for(let i=r;i>=0;i--)if(m(e,i).startsWith(t))return i;return-1}function b(e,t,{normalize:r=!0}={}){if(null==e||null==t)return!1;const i=(0,c.toS)(e),n=(0,c.toS)(t);return i.length===n.length&&(i===n||i.toLowerCase()===n.toLowerCase()||"function"==typeof i.localeCompare&&0===(r?i.normalize():i).localeCompare(r?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,i.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,r){return d(e)?e.slice(t,null==r?void 0:t+r):m(e,t,null==r?void 0:t+r)},t.charArr=g,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=p,t.stripPrefixes=function e(t,r){if(null==t)return"";const i=(0,c.toS)(t);for(const t of r)if(null!=t&&t.length>0&&i.startsWith(t))return e(i.slice(t.length),r);return i},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:r}){return y(p(e,t),r)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:r}){return w(v(e,t),r)},t.ellipsize=function(e,t=80,r=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),r=(0,l.clamp)(0,t-1,(0,l.round)(r));const i=g(e);return i.length<=t?i.join(""):i.slice(0,t-1-r).join("")+"…"+(r>0?i.slice(-r).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,r){const i=r?.maxLineLen??80,n=r?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const i=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(i.map((t=>e(t,r))))}if((t=v((0,c.toS)(t),n).trim()).length<=i)return[t];const s=S(t," ",i);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),r)];{const i=t.indexOf(" ",n.length+1);return i>0&&i{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const i=r(42659),n=r(68708),s=r(42279),o=r(83104),a=r(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,r=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(r,i)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,r(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,r(t))}catch(e){n&&(n=!1,i(e))}finally{clearTimeout(s)}}))}async function c(e,t,r=!0){const n=await u(e,t,r);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,r=!0){return u(e,t,r).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,r=!0){const i=t-Date.now();return i<=0?o.Timeout:u(e,i,r)},t.thenOrOnTimeout=async function(e,t,r){return t<=0?e:new Promise((async(i,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{i(await r())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),i(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,r=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(n)+")");return c(e,n,r)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:r,unref:i=!0}){if(null==e)return(0,s.tot)(r);const n=await u(e,t,i);return n===o.Timeout?(0,s.tot)(r):n}},42279:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const i=r(32639);t.tot=function(e){return(0,i.isFunction)(e)?e():e},t.tol=async function(e){return(0,i.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class r extends Error{}t.TimeoutError=r},12168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const i=r(22573),n=r(30301),s=r(31586),o=r(46891),a=r(50989),l=r(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let r=0;for(const i of e)(0,s.isNumber)(i)&&(r+=i/t.MB);return(0,s.round)(r)},t.fmt=c,t.fmtToInt=function(e){return(0,i.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const r=Math.floor(Math.log10(e)),i=Math.floor(r/3),n=Math.pow(10,3*i),o=d[i];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,r=3){return f(e*t.MB,r)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const r=Math.floor(Math.log2(e)),i=Math.floor(r/10),n=Math.pow(2,10*i),o=h[i];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,r){return null==e?"":(0,i.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(r??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,r){return r??(r=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:r}}},65812:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const i=r(68708);t.setUnrefTimeout=function(e,t){const r=setTimeout(e,t);return(0,i.maybeCall)(r,"unref")??r}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const i=r(41801),n=r(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,i.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const i=r(40958),n=r(23541),s=r(59455),o=r(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,i.compact)((0,s.toA)(e).map(a))}},54993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const i=r(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,i.stringify)(e)}}t.toStr=s},92636:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(6858),s=i(r(73024)),o=i(r(76760)),a=r(1708),l=r(37805),u=r(41269),c=r(80061),d=r(94361);function h(e){for(const t of["bin",__dirname]){const r=o.default.join(t,e);if(s.default.existsSync(r))return r}return console.error("failed to find command "+e),e}n.program.version(l.version),n.program.description("Welcome to PhotoStructure, your new home for all your photos and videos.\nSee https://photostructure.com/server/tools/ for details about these tools."),(0,d.verifyUidGid)(),(0,c.addHelpFooter)(n.program).command("main",u.CliDesc.main+" (default)",{isDefault:!0,executableFile:h("main.js")}).command("info",u.CliDesc.info,{executableFile:h("info.js")}).command("list",u.CliDesc.list,{executableFile:h("list.js")}).command("logcat",u.CliDesc.logcat,{executableFile:h("logcat.js")}).command("logtail",u.CliDesc.logtail,{executableFile:h("logtail.js")}).command("web",u.CliDesc.web,{executableFile:h("web.js")}).command("sync",u.CliDesc.sync,{executableFile:h("sync.js")}).parse(a.argv)},90858:e=>{e.exports=require("@iarna/toml")},58587:e=>{e.exports=require("batch-cluster")},6858:e=>{e.exports=require("commander")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}var __webpack_exports__=__webpack_require__(92636);module.exports=__webpack_exports__})(); \ No newline at end of file +(()=>{"use strict";var __webpack_modules__={37975:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=t.isColorEnabled=t.setColorEnabled=t.noColor=void 0;const i=r(1708),n=r(22573),s=r(38639);function o(){return(0,s.toNotBoolean)(i.env.PS_LOG_COLOR)??(!(0,n.blank)(i.env.NO_COLOR)||["dumb","unknown"].includes(i.env.TERM))}t.noColor=o;let a=!o();function l(){return a}function u(e,t){return function(r){return l()?`[${e}m${r}[${t}m`:r}}t.setColorEnabled=function(e){a=e??!o()},t.isColorEnabled=l,t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const i=r(19851),n=r(7282),s=r(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,i.lazy)((()=>t.SimpleAppName+((0,n.isProd)()?"":`-${(0,n.nodeEnv)()}`))),t.AppNameVersion=(0,i.lazy)((()=>(0,t.AppName)()+" "+s.version))},48884:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reverse=t.leastByCtx=t.greatestBy=t.least=t.leastBy=t.greatestIndexBy=t.leastIndexBy=t.greatestIndex=t.max=t.leastIndex=t.min=t.ancestry=t.unFlatZip=t.flatZip=t.zip=t.retainFirstN=t.retainLastN=t.toMapEntries=t.compactRight=t.mapCompact=t.uniqCount=t.isUniq=t.partition=t.uniqInPlace=t.removeFirst=t.eqlUnordered=t.diceCoeff=t.intersection=t.moveIndexToEnd=t.moveToEnd=t.concat=t.findLastIndex=t.findLast=t.findFromIndex=t.firstNonEmptyThunk=t.firstAsync=t.first=t.findLastAsync=t.findAsync=t.anyDefined=t.anyNotDefined=t.allNotBlank=t.allNotDefined=t.mapAll=t.mapAllDefined=t.allDefined=t.diffEql=t.remove=t.flatMap=t.diff=void 0,t.leftPadArray=t.dupes=t.firstIndexNearest=t.everyAsync=t.someAsync=t.clusterAsync=t.clusterEvery=t.clusterSome=t.contextFilter=t.collectBatchedAsync=t.collectBatched=t.batches=t.reverseG=void 0;const i=r(40958),n=r(36783),s=r(76790),o=r(22573),a=r(50357),l=r(98553),u=r(55835),c=r(31586),d=r(68708),h=r(34666),f=r(59455),m=r(84885);var g=r(40958);function p(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,r=i.primitiveValueOfOrElse){const n=new Set(t.map(r));return e.filter((e=>n.has(r(e))))}function v(e){if(null==e||0===e.length)return[];const t=e[0],r=e.lastIndexOf(t);return[{t,count:r+1},...v(e.slice(r+1))]}function w(...e){const t=[],r=Math.max(...e.map((e=>e?.length??0)));for(let i=0;ie?.[i])));return t}function S(e){return P(e,(e=>e.valueOf()))}function b(e){return _(e,(e=>e.valueOf()))}function P(e,t){return M(e,t,((e,t)=>(0,h.lt)(e,t)))}function _(e,t){return M(e,t,((e,t)=>(0,h.gt)(e,t)))}function E(e,t){return(0,i.isEmpty)(e)?void 0:e[P(e,t)]}function M(e,t,r){return C(e,t,r).index}function C(e,t,r){if((0,i.isEmpty)(e))return{index:-1,value:void 0};let n,s=-1;for(let i=0;ie.slice(r,r+t)))}async function x(e,t){return(0,i.isEmpty)(e)||(await Promise.all(e.map(t))).every((e=>e))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return g.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return g.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return g.remove}}),t.diffEql=function(e,t){return e.filter((e=>!t.some((t=>(0,a.eql)(e,t)))))},t.allDefined=p,t.mapAllDefined=function(e,t){return p(e)?t(e):void 0},t.mapAll=function(e,t){return p(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every((e=>null==e))},t.allNotBlank=function(...e){return null!=e&&e.every(o.notBlank)},t.anyNotDefined=function(e){return null==e||e.some((e=>null==e))},t.anyDefined=function(e){return null!=e&&e.some((e=>null!=e))},t.findAsync=async function(e,t){for(const r of(0,f.toA)(e))if(null!=r&&!0===await t(r))return r},t.findLastAsync=async function(e,t){for(let r=(e=(0,f.toA)(e)).length-1;r>=0;r--){const i=e[r];if(null!=i&&!0===await t(i))return i}},t.first=function(e,t){if(null!=e)for(const r of(0,f.toA)(e))if(null!=r){const e=t(r);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null!=i){const e=await t(i,r);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,i.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,r){for(let i=r;i<=e.length-1;i++)if(t(e[i]))return i},t.findLast=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},t.findLastIndex=function(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},t.concat=function(...e){const t=[];for(const r of e)if(Array.isArray(r))for(const e of r)null!=e&&t.push(e);else null!=r&&t.push(r);return t},t.moveToEnd=function(e,t){return(0,i.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const r=e[t];if(null==r)return e;e.push(r);for(let r=t;r(0,a.eql)(e,t)))},t.removeFirst=function(e,t){const r=e.findIndex(t);return r>=0?e.splice(r,1)[0]:void 0},t.uniqInPlace=function(e,t=(e=>(0,l.stringify)(e))){(0,n.copyArrayTo)((0,i.uniqBy)(e,t),e)},t.partition=function(e,t){const r=[],i=[];let n=0;for(const s of e)(t(s,n++)?r:i).push(s);return[r,i]},t.isUniq=function(e){return e.every(((t,r)=>e.indexOf(t)===r))},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,i.compact)((0,i.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=w,t.flatZip=function(...e){const t=Math.max(...e.map((e=>e?.length??0))),r=[];return(0,c.times)(t,(t=>e.map((e=>r.push(e?.[t]))))),r},t.unFlatZip=function(e,t){const r=e.length/t;if(r!==Math.round(r))throw new Error("unFlatZip(): bad input array length "+(0,l.stringify)({arr_length:e.length,n:t}));const i=(0,c.times)(t,(()=>new Array(r)));for(let n=0;ne.slice(0,t+1)))},t.min=function(e){return e[S(e)]},t.leastIndex=S,t.max=function(e){return e[b(e)]},t.greatestIndex=b,t.leastIndexBy=P,t.greatestIndexBy=_,t.leastBy=E,t.least=function(e){return E(e,(e=>e))},t.greatestBy=function(e,t){return(0,i.isEmpty)(e)?void 0:e[_(e,t)]},t.leastByCtx=function(e,t){const r=C(e??[],t,h.lt);return null==e||null==r||r.index<0||null==r.value?void 0:{result:e[r.index],index:r.index,value:r.value}},t.reverse=function(e){const t=[];for(let r=e.length-1;r>=0;r--)t.push(e[r]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=T,t.collectBatched=function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(r(s)));return n},t.collectBatchedAsync=async function(e,t,r){const n=[];for(const s of T((0,i.compact)((0,f.toA)(e)),t))n.push(...(0,i.compact)(await r(s)));return n},t.contextFilter=function(e,t){let r;return e.filter(((e,i)=>(0,d.tap)(t(e,i,r),(t=>{t&&(r=e)}))))},t.clusterSome=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.some((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterEvery=function(e,t){const r=[];for(const i of e){const e=r.find((e=>e.every((e=>t(i,e)))));e?e.push(i):r.push([i])}return r},t.clusterAsync=async function(e,t){const r=[];e:for(const i of e){for(const e of r)if(null!=i&&await x(e,(e=>t(i,e)))){e.push(i);continue e}null!=i&&r.push([i])}return r},t.someAsync=async function(e,t){if(null!=e)for(let r=0;r=0&&!0===(0,u.map)(e[i],(e=>r(e,i))))return i}{const i=t+n;if(ie+1),1));return(0,f.toA)(t.entries()).filter((([,e])=>e>1))},t.leftPadArray=function(e,t,r){return e.lengthr))),e}},36557:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.batchClusterOptions=t.BatchClusterObserver=void 0;const a=r(77988),l=o(r(1708)),u=r(19851),c=r(42659),d=r(55835),h=r(31586),f=r(85556),m=r(54993),g=r(50213),p=r(79089),y=r(45255),v=r(25764),w=r(38836),S=r(99331),b=r(95937),P=r(98314),_=r(38835),E=r(70025),M=r(8769),C=r(43334),T=r(95402),x=r(28874),D=r(63870);class k extends w.EndableWrapper{constructor(e,t,r=v.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,(()=>s(this,i,"m",n).call(this)),r,"worker"===e?(0,D.commandTimeoutMs)():y.ShortCommandTimeoutMs),i.add(this),this.t=t;const o=t;o.on("childStart",(async r=>{null!=r.pid?(this.logger.info("Started child process",{pid:r.pid}),(0,p.renice)(r.pid).catch((e=>this.onError("renice failed",e))),(0,T.addPid)({pid:r.pid,ppid:l.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+c.minuteMs},new Date)?.catch((t=>this.onError("addPid failed for "+e,t)))):this.onError("No PID returned for "+e,new f.TimeoutError)})),o.on("startError",(e=>{this.lastStartError=e,this.onError("failed to start",e)})),o.on("taskError",((e,t)=>{null!=(0,P.errorToS)(e).match(/timeout/)&&(0,b.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,d.map)(t,(e=>e.command)),e)})),o.on("fatalError",(e=>{this.onError("on(fatalError)"+_.FatalErrorFlag,e)})),o.on("internalError",(e=>{this.lastInternalError=e,this.onError("internal error",e)})),o.on("noTaskData",((e,r,i)=>{const n=t.options.streamFlushMillis;n{this.logger.error("observeBatchCluster.endError()",e)})),o.on("childEnd",(e=>{this.logger.info("on(childEnd)",{pid:e?.pid,name:e?.name}),(0,h.gt0)(e?.pid)&&T.Pids.instance()?.onKill(e.pid)}))}childEndCounts(){return this.t instanceof a.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}onError(e,t){this.t.ended||(0,S.ending)()||!0===(0,E.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,M.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=k,i=new WeakSet,n=function(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)},t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:(C.isWin?3:1)*c.minuteMs,maxTasksPerProcess:x.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:x.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:x.Settings.streamFlushMs.valueOrDefault,logger:(0,u.lazy)((()=>(0,g.mkLogger)(t))),spawnTimeoutMillis:(0,D.commandTimeoutMs)(),taskTimeoutMillis:x.Settings.taskTimeoutMs.valueOrDefault}}},89788:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const c=r(92460),d=r(31586);class h{constructor(e){if(i.add(this),this.maxLength=e,n.set(this,void 0),s.set(this,0),o.set(this,0),e>1e3)throw new Error("BoundedList.maxLength of "+e);l(this,n,new Array(...(0,d.times)(e,(()=>null))),"f")}at(e){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]))}get last(){return this.at(-1)}set(e,t){return u(this,i,"m",a).call(this,e,(e=>u(this,n,"f")[e]=t))}get length(){return u(this,s,"f")}set length(e){l(this,s,(0,d.clamp)(0,u(this,s,"f"),e),"f")}clear(){this.length=0}[(n=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakSet,a=function(e,t){return(e=Math.trunc(e)??0)<0&&(e+=u(this,s,"f")),e<0||e>=u(this,s,"f")?void 0:t((e+u(this,o,"f")+this.maxLength)%this.maxLength)},Symbol.iterator)](){const e=this;return function*(){for(let t=0;tu(e,n,"f")[t]))}()}push(...e){var t,r;for(const c of e.slice(-this.maxLength))u(this,s,"f"){u(this,n,"f")[e]=c}));return u(this,s,"f")}pop(){return u(this,i,"m",a).call(this,u(this,s,"f")-1,(e=>{var t;return l(this,s,(t=u(this,s,"f"),--t),"f"),u(this,n,"f")[e]}))}unshift(...e){var t,r;for(const c of e.reverse())u(this,s,"f"){u(this,n,"f")[e]=c,l(this,o,e,"f")}));return u(this,s,"f")}shift(){return u(this,i,"m",a).call(this,0,(e=>{var t,r;return l(this,o,(t=u(this,o,"f"),++t),"f"),l(this,s,(r=u(this,s,"f"),--r),"f"),u(this,n,"f")[e]}))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t{u(this,i,"m",a).call(this,u(this,s,"f")-1-e,(e=>{const r=u(this,n,"f")[e];u(this,n,"f")[e]=u(this,n,"f")[t],u(this,n,"f")[t]=r}))}));return this}[c.inspect.custom](){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=h},76850:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferStartsWith=t.bufferToString=t.debom=void 0;const i=r(54993),n=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function s(e){for(const{bom:t,encoding:r}of n)if(o(e,t))return e.subarray(t.length).toString(r);return e.toString()}function o(e,t){return t.every(((t,r)=>e[r]===t))}t.debom=s,t.bufferToString=function(e){return Buffer.isBuffer(e)?s(e):(0,i.toS)(e)},t.bufferStartsWith=o},9092:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Map;for(const[t,r]of e)this.set(t,r)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const r=this.normalizer(e);return null!=e&&null!=r&&this.store.set(r,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t[1],t[0],this)))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map((e=>e[0]))[Symbol.iterator]()}values(){return[...this.store.values()].map((e=>e[1]))[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=n},36638:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const i=r(94863);class n{constructor(e=[],t=i.DefaultNormalizer){this.normalizer=t,this.store=new Set;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&this.store.add(t),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach((t=>e(t,t,this)))}has(e){if(null==e)return!1;if(this.store.has(e))return!0;const t=this.normalizer(e);return null!=t&&this.store.has(t)}get size(){return this.store.size}entries(){return this.store.entries()}keys(){return this.store.keys()}values(){return this.store.values()}[Symbol.iterator](){return this.store[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=n},40583:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const o=r(40958),a=r(23838),l=s(r(68708)),u=r(59455),c=r(96859);t.CaseInsensitiveValued=class{constructor(e,t=(()=>{})){this.obj=e,this.synonyms=t,this.m=new a.MultiMap,this.vacuum()}vacuum(){this.m.clear();for(const[e,t]of l.entries(this.obj))for(const r of(0,o.uniq)([e,...(0,u.toA)(this.synonyms(e,t))].map((e=>e.toLowerCase()))))this.m.add(r,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}lookupNearest(e,t=.4){const r=this.lookup(e);if(null!=r)return r;let i,n=-1;for(const[r,s]of this.m.entries()){const o=(0,c.diceCoeff)(r,e);if(o>t&&o>n){const e=this.getFirst(s);null!=e&&(i=e,n=o)}}return i}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.vacuum()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=e.toLowerCase(),r=this.m.get(t);if(null!=r){for(const e of r)delete this.obj[e];this.m.delete(t)}return r}pick(...e){const t={};for(const r of e){const e=this.lookup(r);null!=e?.key&&(t[e.key]=e.value)}return t}}},22454:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const i=r(76790),n=r(31586),s=r(68708),o=r(54993),a=r(82647),l=r(70417);class u{constructor(){this.m=new Map}incr(e,t=1){const r=this.get(e)+t;return 0===r?this.m.delete(e):this.m.set(e,r),r}get(e){return this.m.get(e)??0}max(...e){return Math.max(...0===e.length?this.m.values():e.map((e=>this.get(e))))}has(e){return this.m.has(e)}delete(e){return this.m.delete(e)}get size(){return this.m.size}get countSum(){return(0,l.sum)(this.m.values())}keys(){return this.m.keys()}keyAvg(){const e=new a.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.m.entries()}toJSON(){return this.toRecord()}toRecord(){const e={};for(const[t,r]of this.m.entries())e[(0,o.toS)(t)]=r;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,i.sortBy)([...this.entries()],(([t,r])=>[-r,(0,n.mapNumericOr)(e,(e=>Math.abs(t-e)),0)]))}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map((e=>e[0]))}get averageCounts(){return(0,s.tap)(new a.Average(this.size),(e=>[...this.m.values()].forEach((t=>e.push(t)))))}forEach(e){this.m.forEach(e)}clear(){this.m.clear()}sortedByKey(){const e=new u;for(const[t,r]of(0,i.sortBy)(this.m.entries(),(e=>e[0])))e.incr(t,r);return e}addAll(e){for(const[t,r]of e.entries())this.incr(t,r);return this}get toS(){return(0,i.sort)([...this.keys()]).map((e=>e+" "+this.get(e))).join("\n")}valuesToA(e){const t=[];t.length=(0,l.sum)(this.m.values());let r=0;for(const[i,n]of this.m.entries()){const s=e(i);t.fill(s,r,r+n),r+=n}return t}}t.CountingSet=u},79840:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["keys?","aws","npm","pass","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const i=r(19851),n=r(72993),s=r(45969),o=r(43334);t.EditionType=(0,i.lazy)((()=>o.isElectron?"Desktops":(0,s.isDocker)()?"Docker":"Servers")),t.EditionName=(0,i.lazy)((()=>n.SimpleAppName+" for "+(0,t.EditionType)()))},14121:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenElapsed=t.elapsed=t.Elapsed=void 0;const i=r(55835);t.Elapsed=class{constructor(e,t){this.l=e,this.listener=t,this.ts=Date.now()}elapsed(e){const t=Date.now(),r=t-this.ts;this.ts=t,(0,i.map)(this.listener,(t=>t(e,r))),r>2&&this.l.log(r>500?"warn":r>100?"info":"debug",e,{elapsedMs:r})}},t.elapsed=function(e){const t=Date.now(),r=e();return{elapsedMs:Date.now()-t,result:r}},t.thenElapsed=async function(e){const t=Date.now(),r=await e;return{elapsedMs:Date.now()-t,result:r}}},23467:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eqlAsyncPicked=t.eqlOmit=t.eqlPicked=t.eqlAsync=t.definedAndNotEql=t.definedAndEql=t.eql=void 0;const i=r(50357),n=r(55835),s=r(68708);var o=r(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return o.eql}}),t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,i.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,i.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,n.map2Or)(await e,await t,i.eql,(()=>!1))},t.eqlPicked=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))},t.eqlOmit=function(e,t,...r){return null!=e&&null!=t&&(0,i.eql)((0,s.omit)(e,...r),(0,s.omit)(t,...r))},t.eqlAsyncPicked=async function(e,t,...r){return(0,n.map2Or)(await e,await t,((e,t)=>(0,i.eql)((0,s.pick)(e,...r),(0,s.pick)(t,...r))),(()=>!1))}},62344:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPlaceholder=t.FifoCache=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(31586),a=r(54993),l=r(77377),u=r(73614);function c(e){return null==e?[]:Object.keys(e)}class d{constructor(e,t){if(this.maxSize=e,this.clearEveryMs=t,this.setsSinceLastSpill=0,this.expireListeners=[],e>3e4)throw new Error("maxSize is too big");this.clear(),(0,o.gt0)(t)&&(this.clearInterval=(0,u.setUnrefInterval)((()=>{this.spill()}),(0,o.round)(t/2)))}spill(){if(null!=this.priorCache&&null!=this.currentCache&&(0,n.isNotEmpty)(this.expireListeners))for(const e in this.priorCache)if(null==this.currentCache[e]){const t=this.priorCache[e];if(null!=t)for(const r of this.expireListeners)r(e,t)}this.priorCache=this.currentCache??Object.create(null),this.currentCache=Object.create(null),this.setsSinceLastSpill=0}[i.inspect.custom](){return{...this.priorCache,...this.currentCache}}end(){null!=this.clearInterval&&clearInterval(this.clearInterval)}clear(){return this.visit(((e,t)=>{for(const r of this.expireListeners)r(e,t)})),this.currentCache=Object.create(null),this.priorCache=Object.create(null),this.setsSinceLastSpill=0,this}get size(){if(null==this.currentCache||null==this.priorCache)return 0;let e=0;for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache)))this.has(t)&&e++;return e}has(e){return void 0!==this.currentCache[e]||void 0!==this.priorCache[e]}keys(){return(0,n.uniq)([...c(this.priorCache),...c(this.currentCache)]).filter((e=>null!=this.currentCache[e]??this.priorCache[e]))}delete(e){const t=this.currentCache[e];if(void 0!==t){this.currentCache[e]=void 0;for(const r of this.expireListeners)r(e,t)}const r=this.priorCache[e];if(void 0!==r&&(this.priorCache[e]=void 0,null==t))for(const t of this.expireListeners)t(e,r)}visit(e){for(const t of(0,l.union)(c(this.priorCache),c(this.currentCache))){const r=this.currentCache[t]??this.priorCache[t];null!=r&&e(t,r)}}deleteIf(e){for(const t of this.keys()){const r=(0,s.orElse)(this.currentCache[t],this.priorCache[t]);null!=r&&e(t,r)&&this.delete(t)}}get(e){return e=(0,a.toS)(e),this.currentCache[e]??this.priorCache[e]}set(e,t){this.maxSize<=0||(e=(0,a.toS)(e),null==this.currentCache[e]&&(this.setsSinceLastSpill>=this.maxSize&&this.spill(),this.setsSinceLastSpill++),this.currentCache[e]=t)}getOrSet(e,t){if(e=(0,a.toS)(e),this.has(e))return this.get(e);const r=t();return this.set(e,r),r}on(e,t){this.expireListeners.push(t)}}t.FifoCache=d,t.isPlaceholder=function(e){return null!=e&&(0,o.isNumber)(e.__uid)&&(0,o.isNumber)(e.__start)}},80049:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},u=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCacheAsync=void 0;const c=r(31586),d=r(85556),h=r(54993),f=r(54557),m=r(22911);t.FifoCacheAsync=class{constructor(e){this.opts=e,i.set(this,0),n.set(this,0),s.set(this,0),o.set(this,0),a.set(this,0),this.cache=new f.FifoCache(e.maxSize,e.clearEveryMs)}get name(){return this.opts.name}get size(){return this.cache.size}mergeStats(e){u(this,i,l(this,i,"f")+e.cacheHitsSync,"f"),u(this,n,l(this,n,"f")+e.cacheHitsAsync,"f"),u(this,s,l(this,s,"f")+e.cacheMisses,"f"),u(this,o,l(this,o,"f")+e.rejections,"f"),u(this,a,l(this,a,"f")+e.timeouts,"f")}stats(){return{size:this.size,cacheHitsSync:l(this,i,"f"),cacheHitsAsync:l(this,n,"f"),cacheMisses:l(this,s,"f"),rejections:l(this,o,"f"),timeouts:l(this,a,"f")}}has(e){return this.cache.has(e)}get_(e){var t,r,o,a;if(!this.cache.has(e))return void u(this,s,(t=l(this,s,"f"),t++,t),"f");const c=this.cache.get(e);if(c instanceof m.Deferred){if(c.isRejected)throw c.error;return c.isPending?(u(this,n,(r=l(this,n,"f"),++r),"f"),c.promise):(u(this,i,(o=l(this,i,"f"),++o),"f"),c.value)}if(c instanceof Error)throw c;return u(this,i,(a=l(this,i,"f"),++a),"f"),c}get(e){var t,r;const n=this.cache.get(e);return null==n||n instanceof m.Deferred&&n.isPending?u(this,s,(t=l(this,s,"f"),++t),"f"):u(this,i,(r=l(this,i,"f"),++r),"f"),n instanceof m.Deferred?n.value:n}clear(){this.cache.clear(),u(this,i,0,"f"),u(this,n,0,"f"),u(this,s,0,"f"),u(this,o,0,"f"),u(this,a,0,"f")}delete(e){return this.cache.delete(e)}deleteIf(e){for(const t of this.cache.keys())e(t)&&this.delete(t)}set(e,t){return this.cache.set(e,t),t}getOrSet(e,t){const r=this.get(e);if(null!=r){if(r instanceof Error)throw r;return r}return this.set(e,t())}getOrSetAsync(e,t){const r=(0,h.toS)(e);{const e=this.get_(r);if(null!=e)return e instanceof m.Deferred?e.promise:e}const i=new m.Deferred(this.opts.name).observe(t());return this.cache.set(r,i),(0,c.gt0)(this.opts.timeoutMs)&&i.setTimeout(this.opts.timeoutMs),i.promise.then((e=>{this.set(r,e)}),(e=>{var t,i;this.cache.set(r,e),u(this,o,(t=l(this,o,"f"),++t),"f"),e instanceof d.TimeoutError&&u(this,a,(i=l(this,a,"f"),++i),"f")})),i.promise}},i=new WeakMap,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap},54127:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.FifoSet=void 0;class i{constructor(e){this.maxSize=e,this[r]="FifoSet",this.values=()=>this.delegate.values(),this.keys=this.values,this.delegate=new Set}get size(){return this.delegate.size}add(e){return this.delegate.add(e),this.vacuum(),this}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){this.delegate.forEach(e)}has(e){return this.delegate.has(e)}entries(){return this.delegate.entries()}[(r=Symbol.toStringTag,Symbol.iterator)](){return this.values()}vacuum(){if(this.size>this.maxSize){const e=this.delegate.entries();for(;this.size>this.maxSize;)this.delete(e.next().value[0])}}}t.FifoSet=i},53507:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=t.parseFixed=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(31586),a=r(68708),l=r(50213),u=r(68852),c=r(81168),d=r(84542);class h{constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,i.lazy)((()=>(0,l.mkLogger)("Fixed")));t.parseFixed=function(e,t,r=!0){return new m(e,t,r).entries};class m{constructor(e,t,r=!0){this.warnIfMissingHeaders=r,this.skippedHeaders=[],this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const i=(0,o.max_)(...this.rows.map((e=>e.length)));this.blankColumns=new Set((0,n.range)(0,i).filter((e=>this.rows.every((t=>(0,s.blank)(t[e])))))),this.headers=this.extractHeaders(e.map((e=>new h(e)))),this.entries=this.rows.map((e=>this.headers.map((t=>t.toEntry(e))))).map((e=>(0,a.fromEntries)(e))).filter((e=>(0,a.values)(e).some(s.notBlank)))}firstBlankColumn(e,t){for(let r=e;r!==t;t>e?r++:r--)if(this.blankColumns.has(r))return r;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map((e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b")).join("|"),"gi"),r=[];let i,a=0;for(;null!=(i=t.exec(this.headerRow));){const l=this.headerRow.substring(a,i.index);(0,s.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:i.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(i.index,t.lastIndex),d=i.index+((0,c.indexOfNonSpace)(u)??0),h=i.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),g=e.find((e=>e.text===m));if(null==g||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:i,left:d,right:h});else{const e=(0,n.last)(r);if(r.push(g),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=g.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,o.max_)(e?.rightIdx,i.index-((0,c.lastIndexOfNonSpace)(l)??l.length));g.leftIdx=g.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),g.rightIdx=h}a=t.lastIndex}const l=(0,n.last)(r);return null!=l&&((0,s.blank)(this.headerRow.slice(a))?l.rightIdx=(0,o.max_)(...this.rows.map((e=>e.length))):l.rightIdx=a),r}}t.Fixed=m},73913:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},80875:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readJson_=t.mapParsed=t.parseJSON=void 0;const i=r(51455),n=r(98553);var s=r(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return s.parseJSON}}),t.mapParsed=function(e,t){const r=(0,n.parseJSON)(e);return null==r?void 0:t(r)},t.readJson_=async function(e){return(0,n.parseJSON)((await(0,i.readFile)(e)).toString())}},19851:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.rolazy=t.lazy=void 0;const o=r(57975),a=r(40958),l=r(50357),u=r(31586),c=r(65812),d=r(62344);t.lazy=function(e,t){return new h(e,t)};class h extends d.ExtensibleFunction{constructor(e,t){super(),i.add(this),this.thunk=e,this.ttlMs=t,this.watchers=[]}_call(){return this.isStale()&&s(this,i,"m",n).call(this,this.thunk()),this.result}async onSetResult(e,t){if((0,a.isEmpty)(this.watchers))return;const r=await e,i=await t;if(!(0,l.eql)(r,i))for(const e of this.watchers)e(i);null!=this.ttlMs&&this.ttlMs>0&&void 0!==i&&(0,c.setUnrefTimeout)((()=>this.vacuum()),this.ttlMs)}vacuum(){this.isStale()&&this.unset()}isStale(){return null==this.lastSetTs||(0,u.gt0)(this.ttlMs)&&this.lastSetTs+this.ttlMs{Object.defineProperty(t,"__esModule",{value:!0}),t.childProcLocale=t.localePosix=t.localeMac=t.localeWin=t.lc2locale=t.envLocale=t.locale=t.localeSync=t.DefaultLocale=void 0;const i=r(19851),n=r(40958),s=r(22573),o=r(42659),a=r(50213),l=r(81168),u=r(5916),c=r(56519),d=r(84777),h=r(44198),f=r(6012),m=r(43334),g=r(24399),p=r(63870);t.DefaultLocale="en";const y=(0,i.lazy)((()=>(0,a.mkLogger)("Locale")));function v(e=(0,h.env)()){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=S(t);if(null!=e)return e}}t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(v()??await(m.isWin?P():m.isMac?E():M()).catch((e=>(y().warn("Failed to get locale",{error:e}),t.DefaultLocale)))),timeoutMs:(0,p.commandTimeoutMs)()}),t.envLocale=(0,i.lazy)(v);const w=/^(?[a-z]{2,3})(?:[_-](?[a-z]{2,3}))?\b/i;function S(e){if((0,s.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const r=w.exec(e.trim())?.groups;return null==r?void 0:(0,n.compact)([r.lang,r.country]).join("-")}function b(e){return S(e)??t.DefaultLocale}function P(){return(0,c.thenMap)(g.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name"),(e=>e.Name))}t.lc2locale=b,t.localeWin=P;const _={timeoutMs:10*o.secondMs};async function E(){return S(await(0,d.stdout_)("defaults",["read","-globalDomain","AppleLocale"],_))}async function M(){return b(v((0,f.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,d.stdout_)("locale",[],_)})))}t.localeMac=E,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}}},50213:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mkConsoleLogger=t.mkLogger=t.rootLoggers=void 0;const i=r(19851),n=r(32105),s=r(14593);t.rootLoggers=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));const o=(0,i.lazy)((()=>[n.ConsoleLogger.instance()]));t.mkLogger=function(e){return new s.ContextualLogger(e,t.rootLoggers)},t.mkConsoleLogger=function(e){return new s.ContextualLogger(e,o)}},9103:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=void 0;const i=r(98553),n=r(54557);t.memoize=function(e,t){let r=0;const s=new n.FifoCache(t.maxSize,t.ttlMs),o=t=>{if(null!=t)return r++,s.getOrSet((0,i.stringify)(t),(()=>e(t)))};return o.clear=e=>null==e?s.clear():s.delete((0,i.stringify)(e)),o.size=()=>s.size,o.callCount=()=>r,o}},7282:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setSingleSpecTests=t.isSingleSpecTests=t.isProd=t.isTest=t.isDev=t.nodeEnv=void 0;const n=i(r(1708)),s=r(38639),o=r(54993),a=r(19851),l=r(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,a.lazy)((()=>n.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,o.toS)(n.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return n.default.argv.some((e=>null!=u.exec(e)))?"test":"development"}}())),t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,s.isTrue)(n.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){n.default.env.SINGLE_SPEC_TESTS=e?"true":"false"}},97352:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multiply=t.sqrt=t.hammRatioIntArrays=t.valuesToBigInt=t.hammRatioBinaryString=t.hammRatioBigInt=t.hammingDistanceBigInt=t.Array2D=t.assertPositive=t.extractFraction=t.extractInt=t.extractFloat=t.map2Gt0=t.mapGt0=t.mapGt0f=t.mapGte0f=t.mapGte0Or=t.mapGte0=t.firstNonZero=t.firstGt0=t.within=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(55835),a=r(31586),l=r(39926),u=r(54993),c=r(20014);var d=r(31586);function h(e,t){return(0,a.mapInt)(e,(e=>e>=0?t(e):void 0))}Object.defineProperty(t,"within",{enumerable:!0,get:function(){return d.within}}),t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=h,t.mapGte0Or=function(e,t,r){return(0,o.orElse)(h(e,t),r)},t.mapGte0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>=0?t(r):void 0},t.mapGt0f=function(e,t){const r=(0,a.toFloat)(e);return null!=r&&r>0?t(r):void 0},t.mapGt0=function(e,t){const r=(0,a.toInt)(e);return null!=r&&r>0?t(r):void 0},t.map2Gt0=function(e,t,r){const i=(0,a.toInt)(e),n=(0,a.toInt)(t);return null!=i&&i>0&&null!=n&&n>0?r(i,n):void 0};const f=/[+-]?[\d,.]+/;function m(e){if((0,a.isNumber)(e))return e;if((0,n.blank)(e))return;const t=String(e);return(0,o.map)(f.exec(t),(e=>(0,a.toFloat)(t.substr(e.index))))}function g(e){return(0,a.toInt)(m(e))}function p(e,t){if(null==e||null==t)return;const r=[e,t].map((e=>e.toString(2))),i=Math.max(...r.map((e=>e.length)));return r.map((e=>(0,l.leftPad)(e,i,"0")))}function y(e,t){if(e===t)return 1;if(e.length!==t.length)throw new Error(`hammRatioBinaryString(${e}, ${t}): invalid lengths`);let r=0;for(let i=0;ie/t))}return m(t)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.Array2D=class{constructor(e){this.columns=e,this.store=[]}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,r){this.store[e*this.columns+t]=r}},t.hammingDistanceBigInt=function(e,t){return(0,o.map)(p(e,t),(([e,t])=>(0,i.count)([...e],((e,r)=>e!==t.charAt(r)))))},t.hammRatioBigInt=function(e,t){return null==e||null==t?0:(0,o.map)(p(e,t),(([e,t])=>y(e,t)))},t.hammRatioBinaryString=y,t.valuesToBigInt=function(e,t){return(0,i.isEmpty)(e)?BigInt(0):BigInt("0b0"+e.map((e=>(0,l.leftPad)(e.toString(2),t-1,"0"))).join(""))},t.hammRatioIntArrays=function(e,t,r){if(e.length!==t.length)throw new Error("hammRatioIntArrays(): inequal arrays");let i=0;const n=r*e.length;for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.zipPojos=t.pairToObject=t.pluckCaseInsensitive=t.deepDelete=t.sortedKeys=t.mapNullEntries=t.mapEntries=t.pickMap=t.assignNullishFields=t.assignMissingPrimitives=t.spread=t.primitiveEntries=t.hasKeys=t.ctor=t.identity=t.tryEach=t.Try=t.mapOrThrow=t.mapAnd=t.ornull=t.firstFieldLike=t.firstDefinedField=t.firstDefined=t.firstTrueThunk=t.firstThunk=t.definedThunks=void 0;const i=r(40958),n=r(42659),s=r(96249),o=r(55835),a=r(31586),l=r(68708),u=r(34666),c=r(41583),d=r(48884),h=r(81168);function f(e,t){try{return e()}catch(e){return t?.((0,c.toErr)(e))}}function m(e){return(0,l.keys)(e).filter((t=>(0,u.isPrimitive)(e[t])||(0,n.isDate)(e[t]))).map((t=>[t,e[t]]))}function g(e,t){const r={};for(const[i,n]of(0,l.entries)(e)){const e=t(i,n);null!=e&&(r[i]=e)}return r}t.definedThunks=function(...e){return e.every((e=>(0,o.defined)(e())))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const r of e){const e=r();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find((t=>null!=e[t])),(t=>e[t]))},t.firstFieldLike=function(e,t){return(0,d.first)((0,l.keys)(e),(r=>t(r,e[r])?e[r]:void 0))},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,r){if(null!=e)return t(e);throw new Error(r)},t.Try=f,t.tryEach=function(e,t){[...e].forEach((e=>f((()=>t(e)))))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,(e=>e.name))},t.hasKeys=function(e){return Object.keys(e).some((t=>"string"==typeof t&&e.propertyIsEnumerable(t)))},t.primitiveEntries=m,t.spread=function(e,...t){return Object.assign({},e,...(0,i.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[r,i]of m(t))null==e[r]&&(e[r]=i);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[r,i]of(0,l.entries)(t))null==e[r]&&(e[r]=i);return e},t.pickMap=function(e,t,r){const i={};for(const n of t)i[n]=r(n,e[n]);return i},t.mapEntries=g,t.mapNullEntries=function(e,t,r){const i={};let n=0;for(const s of(0,l.keys)(e))if(i[s]=t(s,e[s]),n++,(0,a.gt)(n,r))break;return i},t.sortedKeys=function e(t){if(null==t||(0,u.isPrimitive)(t))return t;if(Array.isArray(t))return t.map((t=>e(t)));if("object"==typeof t){const r={};for(const i of(0,h.sortIgnoreCase)((0,l.keys)(t)))r[i]=e(t[i]);return r}return t},t.deepDelete=function e(t,...r){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map((t=>e(t,...r))):g(t,((t,i)=>r.includes(t)?void 0:e(i,...r)))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const r of(0,l.keys)(e).filter((e=>(0,h.equalsIgnoreCase)(e,t))))if(void 0!==e[r])return e[r]}},t.pairToObject=function(e,t){const r={};return r[e]=t,r},t.zipPojos=function(...e){const t={};for(const r of(0,i.uniq)((0,s.flatten)(e.map(l.keys))))t[r]=e.map((e=>e?.[r]));return t}},12801:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.priorityPosixToClass=t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0;const n=i(r(48161)),s=r(50989);t.PriorityClasses=(0,s.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:n.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:n.default.constants.priority.PRIORITY_NORMAL,BelowNormal:n.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:n.default.constants.priority.PRIORITY_LOW,Low:n.default.constants.priority.PRIORITY_LOW}),t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e{Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=void 0;const i=r(41400),n=r(56409),s=r(31586),o=r(22911),a=r(73614),l=r(57159);t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:r,nullOnBusy:u,name:c}){let d,h,f=!1,m=0;t=Math.ceil(t);const g=[];function p(){return f||m>Date.now()}function y(){if(null!=h){const e=h;h=void 0,w(...e)}}async function v(...i){f=!0,m=Date.now()+(0,s.max_)(t,r);const n=d=new o.Deferred(c);(0,s.gt0)(r)&&n.setTimeout(r);try{n.resolve(await e(...i))}catch(e){n.reject(new l.WrappedError("RateLimited("+c+") failed",{cause:e}))}finally{f=!1,m=Date.now()+t,(0,a.setUnrefTimeout)(y,t+1),g.forEach((e=>e.resolve())),g.length=0}return n.promise}const w=(...e)=>{if(p()){if(!0===u)return null;const t=d?.promise;return h=e,(0,i.delay)(1).then((()=>t))}return v(...e)};return w.clear=()=>{h=void 0},w.donePromise=()=>{if(!f)return Promise.resolve();const e=new n.Latch;return g.push(e),e},w.force=async(...e)=>(h=void 0,f&&await w.donePromise(),v(...e)),w.isRateLimited=()=>p(),w.status=()=>({running:f,needToDelay:m>Date.now(),minNextDelayMs:Math.max(0,Date.now()-m)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w}},68852:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatRegexp=t.RegExpOptional=t.RegExpEscaped=t.orRegExpPatterns=t.matchQuotes=t.escapeRegExp=t.captures=t.NothingRegExp=void 0;const i=r(68708),n=r(54993);function s(e){return e instanceof o?e.source:(0,n.toS)(e).replace(/[-.,\\^$*+?()|[\]{}]/g,"\\$&")}t.NothingRegExp=/$^/,t.captures=function(e,t){const r=[];if(!e.global)throw new Error("must provide global regex");let n;for(;null!=(n=e.exec(t));)n.index===e.lastIndex?e.lastIndex++:r.push((0,i.pick)(n,"index","groups"));return r},t.escapeRegExp=s,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,r){const i=[];for(const t of e)try{i.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{i.push(s(t))}const n=0===i.length?t.NothingRegExp:i.map((e=>"(?:"+e+")")).join("|");return new RegExp(n,r)};class o{constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class a extends o{static from(...e){const t=l(e);return new a("(?:"+t.source+")?",t.flags)}}function l(e,t){let r="",i=t?.includes("g")??!1,a=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(r+=t.source,i||(i=t.global),a||(a=t.ignoreCase),l||(l=t.multiline)):r+=s((0,n.toS)(t));return new RegExp(r,t??(i?"g":"")+(a?"i":"")+(l?"m":""))}t.RegExpOptional=a,t.concatRegexp=l},79089:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.renice=t.niceable=void 0;const n=i(r(48161)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(42659),u=r(41400),c=r(96249),d=r(31586),h=r(51926),f=r(54993),m=r(50213),g=r(12801),p=r(22277),y=r(84777),v=r(34102),w=r(43334),S=r(24399),b=r(28874),P=(0,o.lazy)((()=>(0,m.mkLogger)("Renice")));(0,u.later)((()=>(0,v.ee)().on("clearCache",(()=>M.prior()?.clear()))));const _=(0,o.lazy)((()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu",s.default.basename(b.Settings.ffmpegPath.valueOrDefault)].map((e=>w.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e)))]));t.niceable=function(e,t){return(0,a.compactBlanks)([s.default.basename(e),...t.map((e=>s.default.basename(e)))]).some((e=>_().includes(e.toLowerCase())))};let E=!0;const M=(0,o.lazy)((()=>new p.TTLSet(l.minuteMs)));t.renice=async function(e,t){if(!(0,d.gt0)(e)||M().has(e))return;M().add(e);const r=(0,g.priorityPosixToClass)(t)??b.Settings.processPriority.valueOrDefault;if(t??(t=g.PriorityClassToNode[r]),E)try{return n.default.setPriority(e,t),t}catch(r){const i=-13===r?.errno||"EACCES"===r?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:i,error:r}),i)return;E=!1}try{return await(w.isWin?async function(e,t){(0,d.gt0)(e)&&g.PriorityClasses.includes(t)&&await S.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,(e=>e)).catch((e=>P().info("reniceWin() failed",e)))}(e,r):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch((e=>P().info("renicePosix() failed",e)))}(e,g.PriorityClassToPosix[r]??g.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+r),t}catch(t){return void P().info("Failed to renice pid "+e,t)}}},23560:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTaskListManager=t.isDbJanitorService=t.isDbManager=t.isTestService=t.isInfoService=t.isSyncService=t.isWorkerService=t.isBillingService=t.isWebService=t.isMainService=t.isPermaService=t.isLibraryRequiredService=t.isDbService=t.DbServices=t.MainServices=t.serviceNameIndex=t.processName=t.serviceName=void 0;const n=i(r(1708)),s=r(19851),o=r(40958),a=r(5670),l=r(54993),u=r(7282),c=r(29325);function d(e){return t.MainServices.includes(e??(0,t.serviceName)())}function h(e){return(e??(0,t.serviceName)())===a.ServiceNames.web}function f(e){return(e??(0,t.serviceName)())===a.ServiceNames.worker}function m(e){return(e??(0,t.serviceName)())===a.ServiceNames.sync}function g(){return(0,t.serviceName)()===a.ServiceNames.test}t.serviceName=(0,s.lazy)((()=>{if((0,c.isPacked)())throw Error("serviceName() is unset");return""})),t.processName=(0,s.lazy)((()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,l.toS)(n.default.pid)]).join("-"))),t.serviceName.watchLater((()=>{t.processName.unset()})),t.serviceNameIndex=function(e){return a.ServiceNames.indexOf(e)??a.ServiceNames.length+1},t.MainServices=[a.ServiceNames.main,a.ServiceNames.desktop],t.DbServices=[a.ServiceNames.sync,a.ServiceNames.info,a.ServiceNames.web,a.ServiceNames.list,a.ServiceNames.test],t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[a.ServiceNames.sync,a.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return d(e)||h(e)},t.isMainService=d,t.isWebService=h,t.isBillingService=function(e){return(e??(0,t.serviceName)())===a.ServiceNames.billing},t.isWorkerService=f,t.isSyncService=m,t.isInfoService=function(){return(0,t.serviceName)()===a.ServiceNames.info},t.isTestService=g,t.isDbManager=function(){return m()||h()||((0,u.isTest)()||g())&&!f()},t.isDbJanitorService=(0,s.lazy)((()=>m()||g())),t.isTaskListManager=function(){return!h()&&!d()&&!f()}},77377:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diff=t.intersection=t.union=t.getOrAdd=t.setEql=t.asSet=void 0;const i=r(59455);function n(e){return e instanceof Set?e:new Set((0,i.toA)(e))}t.asSet=n,t.setEql=function(e,t){return(0,i.toA)(e.keys()).every((e=>t.has(e)))&&(0,i.toA)(t.keys()).every((t=>e.has(t)))},t.getOrAdd=function(e,t,r){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),r())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const r=n(t);return new Set([...e].filter((e=>r.has(e))))},t.diff=function(e,t){const r=n(t);return new Set([...e].filter((e=>!r.has(e))))}},12089:function(e,t,r){var i,n,s,o,a,l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.shim1=void 0;const c=r(98553),d=r(34666),h=r(54993),f=r(62344),m=r(56038);t.shim1=function(e){return new g(e.name,e.impl,e.cache,e.toKey)};class g extends f.ExtensibleFunction{constructor(e,t,r,o){super(),i.add(this),this.impl=t,this.cache=r,this.toKey=o,n.set(this,void 0),s.set(this,void 0),l(this,n,e,"f")}async _call(e){return null==this.cache?u(this,i,"m",a).call(this,e):this.cache().getOrSetAsync(u(this,i,"m",o).call(this,e),(()=>u(this,i,"m",a).call(this,e)))}setShim(e){l(this,s,e,"f")}hasShim(){return null!=u(this,s,"f")}clearShim(){l(this,s,void 0,"f")}cacheDelete(e){this.cache?.().delete(u(this,i,"m",o).call(this,e))}}n=new WeakMap,s=new WeakMap,i=new WeakSet,o=function(e){return this.toKey?.(e)??((0,d.isPrimitive)(e)?(0,h.toS)(e):(0,c.stringify)(e))},a=function(e){return(0,m.time)(u(this,n,"f")+(null==u(this,s,"f")?"(local)":"(remote)"),null==u(this,s,"f")?this.impl(e):u(this,s,"f").call(this,e))}},45255:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const i=r(42659);t.ShortCommandTimeoutMs=7*i.secondMs},92322:function(e,t,r){var i,n=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const s=r(76790),o=r(17586);class a{constructor(e,t){this.valueOf=e,this.diff=t,i.set(this,[])}[(i=new WeakMap,Symbol.iterator)](){return n(this,i,"f")[Symbol.iterator]()}get length(){return n(this,i,"f").length}addAll(...e){for(const t of e)this.add(t)}findIndex(e){return this.findValueIndex(null==e?void 0:this.valueOf(e))}findValueIndex(e){if(null==e)return;let t=0,r=n(this,i,"f").length-1;for(;t<=r;){const s=t+Math.floor((r-t)/2),o=this.valueOf(n(this,i,"f")[s]);if(e===o)return{found:!0,index:s};e>o?t=s+1:r=s-1}return{found:!1,index:t}}add(e){const t=this.findIndex(e);return!1===t?.found&&n(this,i,"f").splice(t.index,0,e),t}nearest({t:e,limit:t,diff:r}){if(t>=this.length)return[...n(this,i,"f")];const o=t=>t<0||t>n(this,i,"f").length-1?null:(r??this.diff)(n(this,i,"f")[t],e),a=this.findIndex(e);if(null==a)return;let l=a.index-1,u=o(l),c=a.index,d=o(c);const h=[];for(;h.lengththis.valueOf(e)))}shift(){return n(this,i,"f").shift()}at(e){return(0,o.at)(n(this,i,"f"),e)}toA(){return[...n(this,i,"f")]}shiftLte(e){const t=this.findValueIndex(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===n(this,i,"f").length-1){const e=[...n(this,i,"f")];return n(this,i,"f").length=0,e}return n(this,i,"f").splice(0,t.index+(t.found?1:0))}splice(e,t){return n(this,i,"f").splice(e,t)}retainLastN(e){return e{Object.defineProperty(t,"__esModule",{value:!0}),t.runtimeMs=t.StartTs=void 0,t.StartTs=Date.now(),t.runtimeMs=function(){return Date.now()-t.StartTs}},82328:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=void 0;const i=r(1708),n=r(95705);t.stdoutEnded=function(){return(0,n.streamEnded)(i.stdout)}},71567:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.isMigrationEvent=t.stdoutWriteMigration=t.stdoutWriteSettings=t.writeTTY=t.stderrWrite=t.stdoutWrite=t.stdoutWriteReady=t.ReadyStr=void 0;const n=i(r(1708)),s=r(22573),o=r(98553),a=r(23560),l=r(82328),u=r(38835),c=r(70025),d=r(95705);function h(e,t){return f({obj:e,ready:t,stream:n.default.stdout})}function f({obj:e,ready:r,stream:i}){if(null==i||(0,d.streamEnded)(i))return;const n=(0,o.stringify)(e,void 0,(0,a.isInfoService)()||(0,a.isMainService)()?2:void 0);i.write(n+"\n"),(0,a.isWorkerService)()&&null!=r&&(n.includes(u.FailStr)||(0,c.isFatalError)(n)||(0,c.isHealthCheckError)(n)?i.write(u.FailStr+"\n"):i.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||n.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=h,t.stderrWrite=function(e){return f({obj:e,stream:n.default.stdout})},t.writeTTY=f,t.stdoutWriteSettings=function(...e){const t={};for(const r of e)r.addToEnv(t);h(t)},t.stdoutWriteMigration=function(e){return h({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,s.notBlank)(e.migration)},t.StdoutWrite={shutdownSync:()=>h({shutdownSync:!0}),restartSync:()=>h({restartSync:!0}),forceRestartSync:()=>h({forceRestartSync:!0}),rebuildLibrary:()=>h({rebuildLibrary:!0}),shutdown:()=>h({shutdown:!0})}},81168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.commonPrefixLengthIgnoreCase=t.commonPrefixIgnoreCase=t.commonPrefix=t.uniqSubstr=t.stripEmoji=t.stripDiacritics=t.sortNatural=t.sortNaturalBy=t.splitUp=t.splitKeep=t.zipStrings=t.wbrPath=t.trimQuotes=t.stripQuotes=t.dumbquote=t.stripAnsiEsc=t.longestPrefix=t.reverse=t.firstSubstringIgnoreCase=t.startsWithIgnoreCase=t.sortByCaseInsensitive=t.sortIgnoreCase=t.uniqIgnoreCase=t.compareIgnoreCase=t.capitalize=t.isFirstCharAZ=t.isUpperCase=t.isLowerCase=t.gist=t.stripSuffixIgnoreCase=t.stripPrefixIgnoreCase=t.spliceCapture=t.splitEvery=t.trim=t.maybeToS=t.countChars=t.contains=t.padReplace=t.rightPad=t.ensureSuffixIgnoreCase=t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.splitUniq=t.dedupeNeedle=t.uniqPath=t.stripComments=t.unoctal=t.trimLeftPadding=t.lastIndexOfNonSpace=t.indexOfNonSpace=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(55835),a=r(31586),l=r(39926),u=r(34666),c=r(51926),d=r(59455),h=r(54993),f=r(48884),m=r(68852),g=r(38835);var p=r(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return p.splitFirst}});var y=r(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return y.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return y.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return y.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return y.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return y.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return y.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return y.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return y.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return y.wrap}});const v=r(28787);t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,h.toS)(e),t=(0,h.toS)(t),e.endsWith(t)||(0,c.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,r){if(0===r.length)throw new Error("rightPad() given empty pad");const i=String(e);return i+(0,l.padding)(r,t-i.length)},t.padReplace=function(e,t,r,i){return(0,c.strslice)(e,0,t)+(0,l.padding)(i,r)+(0,c.strslice)(e,t+r)},t.contains=function(e,t,r){return(0,h.toS)(e).indexOf((0,h.toS)(t),r)>-1},t.countChars=function e(t,r,i=0){if(null==r||0===r.length)return 0;const n=t.indexOf(r,i);return-1===n?0:1+e(t,r,n+r.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(h.toS).filter((e=>(0,s.notBlank)(e)))},t.splitEvery=function(e,t,r){const i=Math.min(Math.ceil(e.length/t),r??e.length)-1;return i<=0?[e]:[...(0,a.times)(i,(r=>e.slice(r*t,(r+1)*t))),e.slice(i*t)]},t.spliceCapture=function(e,t){const r=t.exec(e);if(null==r||null==r[1])return;const i=r[0].indexOf(r[1])+r.index;return{captured:r[1],uncaptured:e.substring(0,i)+e.substring(i+r[1].length),unmatched:e.substring(0,r.index)+e.substring(r.index+r[0].length),matchedIndex:i}},t.stripPrefixIgnoreCase=function(e,t){return P(e=(0,h.toS)(e),t=(0,h.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,r={}){if(null==t)return e;const i=(0,h.toS)(e),n=(0,h.toS)(t);return n.length>0&&(0,c.equalsIgnoreCase)(i.slice(-n.length),n,r)?i.slice(0,-n.length):i},t.gist=function(e,t=80,r=80){const i=(0,h.toS)(e),n=i.length-(t+r);return n<=0?i:i.slice(0,t).trim()+" …(+"+n+" chars)…"+i.slice(-r).trim()},t.isLowerCase=function(e){return(0,h.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,h.toS)(e).toLocaleUpperCase()===e};const w=/^[A-Z]/;function S(e,t){const r=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===r?e.localeCompare(t):r}function b(e){return(0,d.toA)(e).sort(S)}function P(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,c.equalsIgnoreCase)(e.substring(0,t.length),t)}t.isFirstCharAZ=function(e){return w.test((0,h.toS)(e))},t.capitalize=function(e){return e=(0,h.toS)(e),(0,s.blank)(e)?e:(0,c.strslice)(e,0,1).toLocaleUpperCase()+(0,c.strslice)(e,1)},t.compareIgnoreCase=S,t.uniqIgnoreCase=function(e){return(0,i.uniqBy2)(e,c.equalsIgnoreCase)},t.sortIgnoreCase=b,t.sortByCaseInsensitive=function(e,t){return(0,d.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,o.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>{const r=S(e.cmp[0],t.cmp[0]);return 0!==r?r:(0,u.cmp)(e.cmp[1],t.cmp[1])})).map((e=>e.item))},t.startsWithIgnoreCase=P,t.firstSubstringIgnoreCase=function(e,t){if((0,i.isEmpty)(e)||(0,s.blank)(t))return;for(const r of e)if((0,c.equalsIgnoreCase)(r,t))return{index:0,match:r};for(const r of e){const e=t.indexOf(r);if(e>=0)return{index:e,match:r}}const r=t.normalize();for(const t of e){{const e=r.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=r.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=r.toLowerCase(),i=e.toLowerCase(),n=t.indexOf(i);if(n>=0)return{index:n,match:i}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,f.greatestBy)(t.filter((t=>e.startsWith(t))),(e=>e.length))},t.stripAnsiEsc=function(e){return(0,h.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")};const _=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function E(e){return _.reduce(((e,[t,r])=>e.replace(t,r)),e).normalize()}t.dumbquote=E;const M=/^(['"]).+\1$/;t.stripQuotes=function(e){return(0,s.blank)(e)||(e=(0,h.toS)(e).trim(),null!=M.exec(E(e))&&(e=e.slice(1,-1).trim())),e};const C=/^['‘’].*['‘’]$/,T=/^["“”„«»〃].*["“”„«»〃]$/;function x(e,t){const r=D(e,t);return(0,f.flatZip)(r.nonSeparators,r.separators).filter((e=>null!=e&&e.length>0))}function D(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+g.NonRetriableErrorFlag);const r=[],i=[];let n,s=0;for(;null!=(n=t.exec(e));)n.index===t.lastIndex?t.lastIndex++:(t.lastIndex=n[0].length+n.index,r.push(e.substring(s,n.index)),i.push(e.substring(n.index,t.lastIndex)),s=t.lastIndex);return s(0,a.toFloat)(e.trim())??e))}t.trimQuotes=function(e){return e=(0,h.toS)(e).trim(),C.test(e)||T.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map((e=>v.escape(e.normalize()))).join("")},t.zipStrings=function(...e){let t="";const r=(0,i.compactBlanks)(e),n=Math.max(...r.map((e=>e.length)));for(let e=0;e(0,o.map)(r[e],(e=>t+=e))));return t},t.splitKeep=x,t.splitUp=D,t.sortNaturalBy=k,t.sortNatural=function(e){return(0,n.sortBy)(e,(e=>k(e)))},t.stripDiacritics=function(e){return(0,h.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.stripEmoji=function(e){return(0,h.toS)(e).replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,"")},t.uniqSubstr=function(e){const t=b((0,i.compactBlanks)(e)),r=t.filter(((e,r)=>!P(t[r+1],e)));return(0,n.sortBy)(r,(t=>e.indexOf(t)))},t.commonPrefix=function(e,t){if((0,s.blank)(e)||(0,s.blank)(t))return"";const r=Math.min(e.length,t.length);for(let i=0;i4===e?.length?(0,a.mapNumeric)(parseInt(e.slice(1),8),String.fromCharCode):void 0))).map(h.toS).join("")};const O=/#.*$/gm;t.stripComments=function(e){return e.replace(O,"")},t.uniqPath=function(e,t=":"){const r=new Set;for(const i of(0,d.toA)(e))if(null!=i&&!(0,s.blank)(i))for(const e of i.split(t))(0,s.blank)(e)||r.add(e);return[...r].join(t)},t.dedupeNeedle=function(e,t,r){if((0,s.blank)(t))return e;const i=new RegExp("(['\"]?)"+(0,m.escapeRegExp)(t)+"\\1","gm"),n=e.findIndex((e=>i.test(e))),o=new RegExp("("+(0,m.escapeRegExp)(r)+"[,:\\s]*){2,}","gim");if(n<0)return e;for(let t=n+1;te.trim()))))}},83556:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.asObjectKey=t.snake2camel=t.camel2words=t.camel2snake=void 0;const i=r(54993);function n(e){return(0,i.toS)(e).replace(/_([A-Z])/gi,((e,t)=>t.toUpperCase()))}t.camel2snake=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>"_"+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>"_"+e)).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,i.toS)(e).replace(/([A-Z])([a-z])/g,((e,t,r)=>" "+t.toLowerCase()+r)).replace(/[A-Z]+|\d+/g,(e=>" "+e)).trim()},t.snake2camel=n,t.asObjectKey=function(e){return n(e.replace(/^[A-Z]+/,(e=>e.toLowerCase())).replace(/[^a-z]+/gi,"_"))}},37628:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shortFsStringSha=t.shortStringSha=t.stringShaToBuffer=void 0;const n=i(r(77598)),s=r(73913),o=r(55222);function a(e,t=s.HashBits){return n.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,r=o.Radix58,i=224){return r.encodeBuffer(a(e,i)).substring(0,t)}t.stringShaToBuffer=a,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,r=o.GeoRadix,i=224){return l(e,t,r,i)}},94863:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultNormalizer=void 0;const i=r(54993);t.DefaultNormalizer=function(e){return null==e||""===e?void 0:(0,i.toS)(e).toLowerCase().normalize()}},96859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.paddedPositionalDiff=t.positionalDiff=t.lcdiff=t.str=t.radixDiff=t.lnsDiff=t.nonUniqIntersection=t.bigrams=t.diceCoeff=t.hamming=t.lcs=t.commonSubstringRatio=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(31586),a=r(39926),l=r(51926),u=r(54993),c=r(55222),d=r(97352),h=r(88158),f=r(77377),m=r(81168);function g(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const r=new d.Array2D(e.length);let i=0,n="";for(let s=0;s=i&&(i=r.get(s,o),n=(0,l.substr)(e,s-i+1,i)));return n}function p(e,t){if(null==e||null==t)return;if(e===t)return 0;const r=y(e,t);if(null!=r)return r;const i=e.normalize(),n=t.normalize();return e!==i||t!==n?y(i,n):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce(((e,r,i)=>r===t.charAt(i)?e:e+1),0)}function v(e,t){const r=e.toUpperCase().normalize(),i=t.toUpperCase().normalize();return(0,h.firstThunk)((()=>r===i?1:void 0),(()=>(0,s.blank)(e)!==(0,s.blank)(t)?0:void 0),(()=>1===e.length&&1===t.length?0:void 0),(()=>{const e=w(r),t=w(i);return 2*S(e,t).length/(e.length+t.length)}))}function w(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map(((e,r)=>e+t[r+1]))}function S(e,t){const r=(0,f.intersection)(e,t),n=[];return r.forEach((r=>{const s=Math.min((0,i.count)(e,(e=>e===r)),(0,i.count)(t,(e=>e===r)));(0,o.times)(s,(()=>n.push(r)))})),n}function b(e,t,r){const n=(0,i.commonPrefixLength)(e,t);return r((0,l.strslice)(e,n))-r((0,l.strslice)(t,n))}function P(e){const t=(0,i.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,n.sortBy)(t,(e=>-e.length))[0]}function _(e,t){const[r,i]=[e,t].map(P).map((e=>(0,s.blank)(e)?"":e));return b(r,i,(e=>(0,o.toInt)(e,{defaultValue:0})))}t.commonSubstringRatio=function(e,t){return[e,t].some(s.blank)?0:g(e,t).length/Math.max(e.length,t.length)},t.lcs=g,t.hamming=p,t.diceCoeff=v,t.bigrams=w,t.nonUniqIntersection=S,t.lnsDiff=_;const E=/[^\da-z]+/gi;function M(e,t){const[r,i]=[e,t].map((e=>(0,m.stripDiacritics)(e).replace(E,"").toLowerCase()));return b(r,i,(e=>c.RadixAlphaNum.decode(e)))}function C(e,t){let r;for(let i=Math.max(e.length,t.length);i>=0;i--){const n=(0,o.mapNumericOr)(e.charCodeAt(i),(e=>e),256),s=(0,o.mapNumericOr)(t.charCodeAt(i),(e=>e),256),a=(0,o.clamp)(-256,256,n-s);r=null==r?a:(r+a)/2}return r}t.radixDiff=M,t.str=function(e,t){return{pref:(0,i.commonPrefixLength)(e,t),ham:p(e,t),dice:v(e,t),lns:_(e,t),radixDiff:M(e,t)}},t.lcdiff=function(e){return(0,i.count)([...e.normalize()],(e=>0!==e.toLowerCase().localeCompare(e)))},t.positionalDiff=C,t.paddedPositionalDiff=function(e,t,r=8){return C((0,a.leftPad)(e,r," "),(0,a.leftPad)(t,r," "))}},84885:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=void 0;const i=r(98553),n=r(88158);t.stringifySorted=function(e){return(0,i.stringify)((0,n.sortedKeys)(e))}},22277:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const l=r(73614);class u{constructor(e,t=!1){i.add(this),this.ttlMs=e,this.scheduleExpirationTimers=t,this[o]="TTLSet",this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return a(this,i,"m",s).call(this),this.delegate.size}add(e){return this.delegate.set(e,Date.now()),this.scheduleExpirationTimers&&(0,l.setUnrefTimeout)((()=>a(this,i,"m",s).call(this)),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const r=this.delegate.get(e);return null==r||a(this,i,"m",n).call(this,e,r)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,r]of this.delegate)a(this,i,"m",n).call(this,t,r)||e(t,t,this)}has(e){return null!=e&&!a(this,i,"m",n).call(this,e)}values(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield t)}()}entries(){const e=this;return function*(){for(const[t,r]of e.delegate)a(e,i,"m",n).call(e,t,r)||(yield[t,t])}()}toA(){return a(this,i,"m",s).call(this),[...this.delegate.keys()]}[(i=new WeakSet,o=Symbol.toStringTag,Symbol.iterator)](){return this.values()}on(e,t){this.expireListeners.push(t)}}t.TTLSet=u,n=function(e,t){if(t??(t=this.delegate.get(e)),null==t||!this.delegate.has(e))return!0;const r=t<=Date.now()-this.ttlMs;if(r){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return r},s=function(){for(const[e,t]of this.delegate)a(this,i,"m",n).call(this,e,t)}},94174:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=t.groupid=t.groupids=t.userid=t.userids=t.userDesc=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(38639),c=r(31586),d=r(50213),h=r(45255),f=r(84777),m=r(96706),g=r(43334),p=r(24399),y=(0,o.lazy)((()=>(0,d.mkLogger)("UserInfo")));t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,c.gte0)((0,t.userid)())&&(e+=" (userid "+(0,t.userid)()+")"),e},t.userids=(0,o.lazy)((()=>(0,a.uniq)([s.default.geteuid?.(),s.default.getuid?.(),n.default.userInfo().uid]))),t.userid=(0,o.lazy)((()=>(0,t.userids)()[0])),t.groupids=(0,o.lazy)((()=>(0,a.uniq)([s.default.getegid?.(),s.default.getgid?.(),n.default.userInfo().gid]))),t.groupid=(0,o.lazy)((()=>(0,t.groupids)()[0])),t.usernameFromEnv=(0,o.lazy)((()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,l.blank)(t))return t}})),t.usernameFromUserInfo=(0,o.lazy)((()=>(0,l.toNotBlank)(n.default.userInfo()?.username))),t.userNameFromWhoami=(0,o.lazy)((async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:h.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(l.toNotBlank).catch((e=>y().warn("$(whoami) failed",{error:e}))))),t.userNameFromWindowsAccessToken=(0,o.lazy)((async()=>g.isWin?p.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",l.toNotBlank):void 0)),t.username=(0,o.lazy)((async()=>(0,t.usernameFromEnv)()??(0,t.usernameFromUserInfo)()??await(0,t.userNameFromWhoami)()??await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,o.lazy)((async()=>g.isWin?g.isWin?p.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",u.toBoolean):void 0:(0,t.userids)().includes(0)))},37805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2024.3.3-prealpha",t.versionMajor=2024,t.versionMinor=3,t.versionPatch=3,t.versionPrerelease=["prealpha"],t.release="2024.3.3-prealpha+20240320221341",t.gitSha="84e58c788ce0a6315415da9cb73a807d535433f6",t.gitDate=new Date(1710998021e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48963:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=t.wmiDate=void 0;const i=r(42659),n=r(55835),s=r(31586),o=r(97790),a=r(97352),l=/((?:19|20)\d\d)([01]\d)([0-3]\d)([012]\d)([0-5]\d)([0-5]\d)\.(\d{6})([+-]\d{3})?/;t.wmiDate=function(e){const t=l.exec(e);if(null==t)return;const r=t.slice(1,8).map((e=>(0,s.toInt)(e)));if(!(0,n.allDefined)(r))return;const[o,a,u,c,d,h,f]=r,m=(0,s.toInt)(t[8],{defaultValue:0});return new Date(Date.UTC(o,a-1,u,c,d,h,f/1e3)-m*i.minuteMs)};const u=/Date\((\d+)\)/;t.pwshJsonDate=function(e){return(0,o.opt)(e).flatMap((e=>u.exec(e))).flatMap((e=>e[1])).flatMap(s.toInt).filter((e=>(0,a.within)(0,Date.now()+i.dayMs,e))).map((e=>new Date(e))).get()}},73568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0;class r extends Error{}t.AbortError=r},76740:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const a=r(45599),l=r(56409),u=r(73568);t.Abortable=class{constructor(){this._aborted=!1,i.set(this,void 0),n.set(this,(0,a.defer)((()=>new l.Latch)))}abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,s(this,n,"f").call(this).reject(new u.AbortError(e)).catch((()=>{})))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new u.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return s(this,n,"f").call(this).promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,s(this,n,"f").call(this).promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),o(this,i,setTimeout((()=>this.abort(t)),e).unref(),"f")}clearAbortTimeout(){null!=s(this,i,"f")&&clearTimeout(s(this,i,"f")),o(this,i,void 0,"f")}observeRejections(e){e.catch((e=>this.abort(e.message)))}observeResolutions(e,t){e.then((()=>this.abort(t)))}},i=new WeakMap,n=new WeakMap},22911:function(e,t,r){var i,n,s,o,a,l,u,c,d,h,f,m,g=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},p=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},y=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const v=y(r(87997)),w=y(r(57975)),S=r(45599),b=r(26905),P=r(55835),_=r(31586),E=r(68708),M=r(20214),C=r(57153),T=r(85556),x=r(50213),D=r(70025),k=r(95937),O="TIMEOUT",I=(0,S.defer)((()=>(0,x.mkLogger)("async.Deferred")));class A{static async*toAsyncIterable(e,t){const r=[...e].reverse(),i=(0,_.gt0)(t)?new n(O).setTimeout(t):void 0;for(null!=i&&r.push(i);;){for(let i=r.length-1;i>=0;i--){const n=r[i];if(n.isSettled){if(n.name===O)return void I().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:e.map((e=>e.name))});r.splice(i,1),yield n.value}}if(r.every((e=>e.name===O)))break;try{await Promise.race(r)}catch{}}i?.clearTimeout()}static resolve(e,t){return new n(".resolved()",t).resolve(e)}constructor(e,t){var r,m,y;i.add(this),this.name=e,this.startedAt=Date.now(),o.set(this,void 0),a.set(this,C.PromiseStates.pending),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),h.set(this,void 0),f.set(this,void 0),this.id=(p(r=n,n,(y=g(r,n,"f",s),m=y++,y),"f",s),m),this.promise=new Promise(((e,t)=>{p(this,u,e,"f"),p(this,c,t,"f")})),this.payload=t?.payload,this.serialId=t?.serialId}get logger(){return g(this,f,"f")??(0,x.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof n&&e.id===this.id}toLogJSON(){return{_ctor:"Deferred",name:this.name,state:g(this,a,"f"),value:this.value,serialId:this.serialId,payload:this.payload,elapsedMs:this.elapsedMs}}toJSON(){return(0,E.omit)(this.toLogJSON(),"value","elapsedMs")}get settledAt(){return g(this,o,"f")}get elapsedMs(){return(g(this,o,"f")??Date.now())-this.startedAt}get[(o=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,h=new WeakMap,f=new WeakMap,i=new WeakSet,Symbol.toStringTag)](){return"async.Deferred("+this.name+")"}[w.default.inspect.custom](){return this.toJSON()}observeQuietly(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)})):this.maybeResolve(e),this}observe(e){return(0,M.isPromise)(e)?e.then((e=>{this.maybeResolve(e)})).catch((e=>{this.maybeReject(e)})):this.maybeResolve(e),this}clearTimeout(){return null!=g(this,h,"f")&&(v.default.clearTimeout(g(this,h,"f")),p(this,h,void 0,"f"),!0)}setTimeout(e){return this.clearTimeout(),(0,_.gt0)(e)&&(p(this,h,v.default.setTimeout((()=>{this.isPending&&(this.reject(new T.TimeoutError("Timeout "+this.name+" after "+(Date.now()-this.startedAt)+"ms")),(0,k.onTimeout)())}),e),"f"),g(this,h,"f").unref()),this}get stateStr(){return this.isPending?"pending":this.isResolved?"resolved":"rejected"}get isPending(){return g(this,a,"f")===C.PromiseStates.pending}get value(){return this.isResolved?g(this,l,"f"):void 0}get error(){return g(this,d,"f")}get isSettled(){return g(this,a,"f")!==C.PromiseStates.pending}get isResolved(){return g(this,a,"f")===C.PromiseStates.resolved}get isRejected(){return g(this,a,"f")===C.PromiseStates.rejected}get settledMs(){return null==g(this,o,"f")?void 0:g(this,o,"f")-this.startedAt}resolve(e){return g(this,i,"m",m).call(this,(()=>{p(this,a,C.PromiseStates.resolved,"f"),p(this,l,e,"f"),g(this,u,"f").call(this,e)}))}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){this.logger.log(!0===(0,D.isIgnorableError)(e)?"info":"warn",".reject()",e);const t=(0,b.asError)(e);return g(this,i,"m",m).call(this,(()=>{p(this,d,t,"f"),p(this,a,C.PromiseStates.rejected,"f"),g(this,c,"f").call(this,t)}))}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch((()=>{})),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch((t=>e(t)))}}t.Deferred=A,n=A,m=function(e){if(g(this,a,"f")===C.PromiseStates.pending){(0,P.map)(g(this,h,"f"),v.default.clearTimeout),e(),p(this,o,Date.now(),"f");const t=this.settledMs;this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:g(this,l,"f")});return this},s={value:0}},27395:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.endablesStats=t.endAllEndables=t.endEndables=t.end=t.endAll=t.addEndable=void 0;const i=r(19851),n=r(40958),s=r(42659),o=r(23838),a=r(13538),l=r(50213),u=r(7282),c=r(97352),d=r(77740),h=r(25764),f=r(99331),m=r(73614),g=(0,i.lazy)((()=>(0,l.mkLogger)("async.Endable"))),p=new o.MultiMap;(0,m.setUnrefInterval)((()=>w()),10*s.minuteMs);const y=5*s.secondMs;async function v(e,t){const r=await e;if(null==r||!0===r?.ended)return;const i=(0,u.isTest)()&&(0,d.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,c.firstGt0)(t,r.endTimeoutMs,y);g().trace(r.name+" ending...",{timeoutMs:i});try{await(0,a.thenOrTimeoutError)(r.end(),i,(0,u.isTest)())}catch(e){try{g().warn(r.name+".end() failed",e)}catch{}}}function w(){p.filterInPlace(((e,t)=>!0!==t.ended)),g().debug("vacuumEndables()",p.entriesArray().map((([e,t])=>[e,t.map((e=>e.name))])))}t.addEndable=function(e,t){return h.EndableRanks.validOrElse(e,(()=>{throw new Error("internal error: invalid rank "+e)})),p.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map((e=>v(e))))},t.end=v,t.endEndables=(0,i.lazy)((async()=>{const e=(0,u.isSingleSpecTests)()?500:void 0;g().info("endEndables()",{isTest:(0,u.isTest)(),isSingleSpecTests:(0,u.isSingleSpecTests)()}),(0,u.isTest)()||(0,f.setEnding)(!0),w();for(const t of h.EndableRanks.values){const r=p.get(t)??[];(0,n.isNotEmpty)(r)&&(g().debug("endEndables(): ending "+t),await Promise.allSettled(r.map((t=>v(t,e)))))}})),t.endAllEndables=async function(){return(0,f.setEnding)(!0),Promise.all((0,n.compact)(p.valuesFlat()).map((e=>v(e))))},t.endablesStats=function(){const e={};for(const t of h.EndableRanks.values){const r=p.get(t)??[];e[t]=r.map((e=>({name:e.name,ended:e.ended})))}return e}},78406:function(e,t,r){var i,n,s,o,a,l,u=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const d=r(87997),h=r(55835),f=r(31586),m=r(68708),g=r(25764),p=r(38836),y=r(99331);class v extends p.EndableWrapper{constructor(e){super(e.name,(()=>u(this,i,"m",o).call(this)),e.rank??g.EndableRanks.first,e.endTimeoutMs),i.add(this),this.opts=e,n.set(this,void 0),s.set(this,void 0),a.set(this,(()=>{(0,y.ending)()||this.ended||this.opts.callback()})),null!=e.onEnd&&this.onEnds.push(e.onEnd),this.setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}hasTimer(){return null!=u(this,n,"f")}hasTimeout(){return null!=u(this,s,"f")}get timingOpts(){return(0,m.pick)(this.opts,"intervalMs","initialDelayMs")}setIntervalMs(e,t,r=!1){if((0,y.ending)()||this.ended)return!1;if(e=(0,f.toInt)(e)??0,t=(0,f.toInt)(t)??0,!r&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t)return!1;this.opts.intervalMs=e,this.opts.initialDelayMs=t,u(this,i,"m",o).call(this);const h=()=>{u(this,i,"a",l)&&(0,f.gt0)(this.opts.intervalMs)&&(c(this,n,(0,d.setInterval)(u(this,a,"f"),this.opts.intervalMs),"f"),!0===this.opts.unref&&u(this,n,"f").unref())};return(0,f.gt0)(this.opts.initialDelayMs)?(c(this,s,(0,d.setTimeout)((()=>{u(this,i,"a",l)&&(u(this,a,"f").call(this),h())}),this.opts.initialDelayMs),"f"),!0===this.opts.unref&&u(this,s,"f").unref()):h(),!0}}t.EndableInterval=v,n=new WeakMap,s=new WeakMap,a=new WeakMap,i=new WeakSet,o=function(){(0,h.map)(u(this,n,"f"),d.clearInterval),c(this,n,void 0,"f"),(0,h.map)(u(this,s,"f"),d.clearTimeout),c(this,s,void 0,"f")},l=function(){return!(0,y.ending)()&&!this.ended}},25764:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const i=r(50989);t.EndableRanks=(0,i.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const a=r(19851),l=r(45599),u=r(56409),c=r(50213),d=r(27395),h=r(25764),f=r(99331),m=r(56519);t.EndableWrapper=class{constructor(e,t,r=h.EndableRanks.first,o){this.endTimeoutMs=o,i.set(this,void 0),this.onEnds=[],n.set(this,(0,a.lazy)((()=>new u.Latch))),this.end=(0,l.defer)((async()=>{this.logger.abortable.abort((0,f.ending)()?"service ending":"onEnd()"),await(0,m.awaitSettled)(this.onEnds.map((e=>e()))),s(this,n,"f").call(this).resolve()})),this.setName(e),null!=t&&this.onEnds.push(t),(0,d.addEndable)(r,this)}setName(e){o(this,i,e,"f"),this.logger=(0,c.mkLogger)(e)}get name(){return s(this,i,"f")}get ended(){return this.end.hasPrior()}awaitEnd(){return s(this,n,"f").call(this)}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},i=new WeakMap,n=new WeakMap},99331:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setEnding=t.ending=void 0;const i=r(7282);let n=!1;t.ending=function(){return n},t.setEnding=function(e){n=(0,i.isTest)()?e:e||n}},45608:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.exit=t.onFatalHandlers=void 0;const n=i(r(1708)),s=r(22573),o=r(45599),a=r(37975),l=r(50213),u=r(71567),c=r(57159),d=r(57902),h=r(28874),f=r(27395),m=r(99331),g=r(56038),p=(0,o.defer)((()=>(0,l.mkLogger)((0,a.magenta)("Exit"))));t.onFatalHandlers=[];const y=(0,o.defer)((()=>{h.Settings.emitTimingsOnExit.valueOrDefault&&(0,u.stdoutWrite)(g.PromiseTimer.instance().report())}));async function v(e){p().log(0===e.status?d.LogLevels.info:d.LogLevels.warn,"exit()",{...e,ending:(0,m.ending)()}),y();const r=(0,c.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==r.errno||!0===r.fatal||0!==e.status){(0,u.stderrWrite)({fatal:!0,...e});const i=(0,s.toNotBlank)(e?.reason)??r.toString();for(const e of t.onFatalHandlers)await e(i)}(0,m.ending)()||(await(0,f.endEndables)(),n.default.exit(e.status))}t.exit=v,t.exitOnStdStream=(0,o.defer)((()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])n.default[e].on(t,(r=>{v({reason:`${e}:${t}`,status:0,error:r})}))}))},5916:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},d=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=void 0;const h=r(45599),f=r(50357),m=r(31586),g=r(41583),p=r(62344),y=r(50213),v=r(22911),w=(0,h.defer)((()=>(0,y.mkLogger)("async.LazyAsync")));t.lazyAsync=function({later:e,desc:t,ttlMs:r,timeoutMs:i}){return new S(e,t,r,i)};class S extends p.ExtensibleFunction{constructor(e,t,r,l){super(),i.add(this),this.later=e,this.desc=t,this.ttlMs=r,this.timeoutMs=l,n.set(this,void 0),s.set(this,0),o.set(this,void 0),a.set(this,[])}_call(){return this.isStale()?c(this,i,"m",u).call(this,this.later()):c(this,o,"f")}unset(){d(this,s,0,"f"),d(this,n,void 0,"f"),d(this,o,void 0,"f")}set(e){return c(this,i,"m",u).call(this,v.Deferred.resolve(e))}refresh(){return c(this,i,"m",u).call(this,this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,m.gt0)(e)?e:void 0}watchLater(e){c(this,a,"f").push(e)}prior(){return this.isStale()?void 0:c(this,o,"f")}lastValue(){return c(this,o,"f")?.value}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return c(this,s,"f")}isStale(){return null==c(this,n,"f")||(0,m.gt0)(this.ttlMs)&&Date.now()-c(this,n,"f")>this.ttlMs}lastSetAgoMs(){return null==c(this,n,"f")?void 0:Date.now()-c(this,n,"f")}elapsedMs(){return c(this,o,"f")?.settledMs??c(this,o,"f")?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=async function(e,t){var r;try{const r=await t;if(!(0,f.eql)(e?.value??await(e?.promise),r))for(const e of c(this,a,"f"))await e.onChange(r)}catch(e){const t=(0,g.toErr)(e);if(w().warn(this.desc+": onSetResult failed",{error:t}),null!=t)for(const e of c(this,a,"f"))e.onError(t)}finally{d(this,s,(r=c(this,s,"f"),++r),"f")}},u=function(e){d(this,n,Date.now(),"f");const t=c(this,o,"f");return d(this,o,e instanceof v.Deferred?e:new v.Deferred(this.toString()).observe(e),"f"),(0,m.gt0)(this.timeoutMs)&&c(this,o,"f").setTimeout(this.timeoutMs),c(this,i,"m",l).call(this,t,c(this,o,"f")),c(this,o,"f")}},56519:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortByAsync=t.firstTruePromise=t.firstResolvedDefinedPromise=t.firstDefinedPromise=t.first=t.thenOrElse=t.thenAnd=t.thenMap2Or=t.thenMapOr=t.thenMap2=t.thenNot=t.thenFinally=t.tryAll=t.DefaultTryAllTimeoutMs=t.tryAsync=t.partitionAsync=t.filterAsync=t.mapAsync=t.thenCollectParallel=t.mapAsyncSerial=t.thenCollectSerial=t.asyncFind=t.thenUniq=t.thenFlatten=t.awaitSettled=t.awaitAll=t.allSerial=t.thenDefined=t.rejected=t.resolved=t.resolvedWithin=t.thenMapResolved=t.thenCollectBatched=t.thenCompact=t.someOrTimeout=t.thenMap=void 0;const i=r(40958),n=r(76790),s=r(38639),o=r(42659),a=r(41400),l=r(31586),u=r(20214),c=r(13538),d=r(42279),h=r(32639),f=r(59455),m=r(41583),g=r(48884),p=r(50213),y=r(88158),v=r(15674),w=r(42638);var S=r(20214);async function b(e){if(null==e)return[];const t=(0,i.compact)(await e);return(0,i.isEmpty)(t)?[]:(0,i.compact)(await Promise.all(t))}async function P(e){try{return await e,!0}catch(e){return!1}}async function _({name:e,arr:t,f:r,timeoutMs:n}){const s=[];for(const o of(0,i.compact)(await t))try{const e=await((0,l.gt0)(n)?(0,c.thenOrTimeoutError)(r(o),n):r(o));null!=e&&s.push([e,o])}catch(t){(0,p.mkLogger)(e).warn("failed to apply",{ea:o,error:t})}return s}async function E({arr:e,f:t,name:r,maxConcurrent:n,timeoutMs:s,promises:o}){if(null==e)return[];const a=(0,i.compact)(await e);if((0,i.isEmpty)(a))return[];if((n=Math.round(n??(0,v.maxCpus)()))<=1)return _({arr:e,f:t,name:r,timeoutMs:s});const u=o??(a.length<=n?w.PermissivePromises:new w.Promises(r,(()=>n))),d=(0,l.gt0)(s)?e=>(0,c.thenOrTimeoutError)(t(e),s):t,h=await u.enqueueAll(r,a.map((e=>async()=>{try{return[await d(e),e]}catch(t){return void(0,p.mkLogger)(r).warn("failed to apply",{ea:e,error:t})}})));return(0,i.compact)(h).filter((([e,t])=>null!=e&&null!=t))}Object.defineProperty(t,"thenMap",{enumerable:!0,get:function(){return S.thenMap}}),t.someOrTimeout=async function(e,t){return Promise.all(e.map((e=>(0,c.thenOrTimeoutError)((0,d.tol)(e),t.timeoutMs).catch((e=>e)))))},t.thenCompact=b,t.thenCollectBatched=async function(e,t,r){const i=[];for(const n of(0,g.batches)((0,f.toA)(await e),t)){const e=await b(n);i.push(...await b(r(e)))}return i},t.thenMapResolved=async function(e,t){if(null==e)return Promise.resolve(void 0);try{return await(0,u.thenMap)(e,t)}catch(e){return}},t.resolvedWithin=function(e,t){return Promise.race([e.then((()=>!0)),(0,a.delay)(t).then((()=>!1))]).catch((()=>!1))},t.resolved=P,t.rejected=async function(e){return!await P(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const r of(0,i.compact)(e)){const e=await r();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;if(null!=e)if(Array.isArray(e))for(const r of e){const e=await r;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const r of(0,f.toA)(await e)){const e=await r;null!=e&&t.push(e)}return(0,i.uniq)(t)},t.asyncFind=async function(e,t){for(const r of e)if(await t(r))return r},t.thenCollectSerial=_,t.mapAsyncSerial=async function(e){return(await _(e)).map((e=>e[0]))},t.thenCollectParallel=E,t.mapAsync=async function({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s}){return(await E({arr:e,f:t,name:r,maxConcurrent:i,timeoutMs:n,promises:s})).map((e=>e[0]))},t.filterAsync=async function({name:e,arr:t,f:r,maxConcurrent:n,timeoutMs:s}){return(await E({name:e,arr:(0,i.compact)(t),f:r,maxConcurrent:n,timeoutMs:s})).filter((([e])=>e)).map((([,e])=>e))},t.partitionAsync=async function(e,t){const r=await E({name:"partitionAsync",arr:e,f:t});return[r.filter((([e])=>(0,s.isTrue)(e))).map((([,e])=>e)),r.filter((([e])=>(0,s.isFalse)(e))).map((([,e])=>e))]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.DefaultTryAllTimeoutMs=30*o.secondMs,t.tryAll=async function(e,r=(e=>console.error(e)),i=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,c.thenOrTimeout)(t,i)}catch(e){r((0,m.toErr)(e))}},t.thenFinally=async function(e,t=(()=>{}),r=(()=>{})){let i,n=null;try{i=await((0,h.isFunction)(e)?e():e)}catch(e){n=(0,m.toErr)(e);try{await t(e)}catch{}}try{await r(n??i)}catch{}if(null!=n)throw n;return i},t.thenNot=async function(e,t=!0){if(null==e)return t;const r=await e;return null==r?t:!(0,s.isTrue)(r)},t.thenMap2=async function(e,t,r){const i=await e;if(null==i)return;const n=await t;return null!=n?r(i,n):void 0},t.thenMapOr=async function(e,t,r){const i=await e;if(null==i)return r();const n=await t(i);return null==n?r():n},t.thenMap2Or=async function(e,t,r,i){const n=await e;if(null==n)return i();const s=await t;if(null==s)return i();const o=await r(n,s);return null==o?i():o},t.thenAnd=async function(e,t){return null!=e&&(0,s.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let r=-1;for(const i of e){r++;try{if(null==i)continue;const e=await t(i,r);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const r of e){const e=await r();if(null!=e){const r=await t(e);if(null!=r)return r}}},t.firstResolvedDefinedPromise=async function(e,t){for(const r of e)try{const e=await r();if(null!=e)return e}catch(e){t((0,m.toErr)(e))}},t.firstTruePromise=async function(e,...t){for(const r of t)try{const t=await r();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({name:e,arr:t,f:r}){const i=await E({name:e,arr:t,f:r});return(0,n.sortBy)(i,(e=>e[0])).map((e=>e[1]))}},56038:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timedLazy=t.timeStatsWithName=t.timeStatsWithPrefix=t.pushTime=t.timeSync=t.time=t.mkElapsed=t.PromiseTimer=void 0;const i=r(19851),n=r(40958),s=r(76790),o=r(42659),a=r(49769),l=r(31586),u=r(68708),c=r(42279),d=r(41583),h=r(22454),f=r(14121),m=r(50213),g=r(7282),p=r(34102),y=r(82647),v=r(25764),w=r(38836),S=r(73614);function b(e){return e.split(":")[0].trim()}class P{constructor(){this.errors=new h.CountingSet,this.times=new Map}clear(){this.errors.clear(),this.times.clear()}async time(e,t,r){const i=Date.now(),n=(0,l.clamp)(10*o.secondMs,o.minuteMs,Math.round(this.times.get(e)?.p98??0)),s=(0,S.setUnrefTimeout)((()=>{(0,m.mkLogger)("time("+e+")").warn("unsettled for "+(Date.now()-i)+"ms")}),n);try{const n=await(0,c.tot)(t),s=Date.now()-i;return r?.(n,s),this.push(e,s),n}catch(t){throw this.errors.incr(e),r?.((0,d.toErr)(t),Date.now()-i),t}finally{clearTimeout(s)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.times.entries()],(([,e])=>-e.sum))}statsWithName(e){return this.times.get(b(e))?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter((([t])=>t.startsWith(e))),r=t.reduce(((e,t)=>y.Average.merge(t[1],e)),new y.Average),i=t.map((([e,t])=>[e,t.stats()]));return(0,u.fromEntries)([["merged",r.stats()],...i])}mkElapsed(e){return new f.Elapsed(e,((e,t)=>this.push(e,t)))}push(e,t){t>15&&(0,a.getOrSet)(this.times,b(e),(()=>new y.Average)).push(t)}weightedAvg(e){return this.times.get(b(e))?.weightedSampleAvg}errorCounts(){return this.errors.top(10)}callCounts(){return[...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:r.n})),{})}weightedAvgs(){return(0,u.compactValues)([...this.times.entries()].reduce(((e,[t,r])=>({...e,[t]:(0,l.mapFinite)(r.weightedSampleAvg,l.round)})),{}))}toJSON(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:r.toJSON()})),{})}report(){return this.entriesBySumDesc.reduce(((e,[t,r])=>({...e,[t]:{sumSec:(0,l.sigFigs)(r.sum/o.secondMs,3),...(0,u.omit)(r.stats(),"sum")}})),{})}}function _(e,t,r){return P.instance().time(e,t,r)}function E(e,t){P.instance().push(e,t)}t.PromiseTimer=P,P.instance=(0,i.lazy)((()=>{const e=new P;return new w.EndableWrapper("PromiseTimer",(()=>{const t=(0,m.mkLogger)("async.PromiseTimer");(0,u.mapCompactObj)(e.report(),(e=>t.info("timings:",e))),(0,n.mapNotEmpty)(e.errorCounts(),(e=>t.warn("error counts:",(0,u.fromEntries)(e))))}),v.EndableRanks.stats),(0,g.isTest)()&&(0,p.ee)().on("clearCache",(()=>e.clear())),e})),t.mkElapsed=function(e){return P.instance().mkElapsed((0,m.mkLogger)(e))},t.time=_,t.timeSync=function(e,t){const r=Date.now(),i=t();return E(e,Date.now()-r),i},t.pushTime=E,t.timeStatsWithPrefix=function(e){return P.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return P.instance().statsWithName(e)},t.timedLazy=function(e,t,r){return(0,i.lazy)((async()=>_(e,t)),r)}},42638:function(e,t,r){var i,n,s,o,a,l,u,c=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.withBoundedConcurrency=t.maybeRun=t.Promises=t.toName=void 0;const f=h(r(66261)),m=r(40958),g=r(55835),p=r(31586),y=r(42279),v=r(54993),w=r(89788),S=r(82647),b=r(15674),P=r(22911);t.toName=function(e){return e?.name??(0,v.toS)(e)};class _{constructor(e,t){i.add(this),this.name=e,this.ee=new f.default.EventEmitter,n.set(this,void 0),this.lastWorkTs=0,this.settleMsAvg=new S.Average,s.set(this,0),o.set(this,[]),a.set(this,[]),this.lastPushedNames=new w.BoundedList(16),c(this,n,t,"f")}get maxConcurrency(){return Math.floor((0,p.clamp)(1,(0,b.maxCpus)(),d(this,n,"f")?.call(this)??(0,b.maxCpus)()))}end(){return d(this,a,"f").length=0,this.awaitAll()}vacuum(){return(0,m.filterInPlace)(d(this,o,"f"),(e=>e.isPending))}get running(){return this.vacuum()}get settledCount(){return d(this,s,"f")}stats(){return{maxConcurrency:this.maxConcurrency,lastPushMsAgo:Date.now()-this.lastWorkTs,freeSlots:this.freeSlots(),unsettledCount:this.unsettledCount(),runningNames:d(this,o,"f").map((e=>e.name)),pendingNames:d(this,a,"f").map((e=>e.d.name)),totalWorkCount:d(this,s,"f")}}enqueue({name:e,l:t,payload:r,serialId:n}){const s=d(this,i,"m",l).call(this,{name:e,l:t,payload:r,serialId:n});return this.laterPop(),s}enqueueAll(e,t){const r=t.map((t=>d(this,i,"m",l).call(this,{name:e,l:t}).promise));return this.laterPop(),Promise.all(r)}serial(e,t,r){return this.enqueue({name:e,l:t,serialId:e,payload:r})}push(e,t,r){return d(this,i,"m",u).call(this,new P.Deferred(e,{payload:r}),t).promise}get runningSerialIds(){return(0,m.compact)(this.vacuum().map((e=>e.serialId)))}laterPop(){setImmediate((()=>this.maybePopPendingWork()))}maybePopPendingWork(){this.vacuum();const e=this.maxConcurrency-d(this,o,"f").length;if(0===e)return;(0,m.isEmpty)(d(this,a,"f"))&&e>0&&this.ee.emit("vacancy"),this.isIdle()&&this.ee.emit("drain");const t=Math.min(d(this,a,"f").length,e),r=this.runningSerialIds,n=[];for(let e=0;et.name===e))}maybeRun(e,t){return this.freeSlots()>0&&!this.isTaskRunning(e)?this.push(e,t):void 0}runningCount(){return(0,m.count)(d(this,o,"f"),(e=>e.isPending))}unsettledCount(){return this.runningCount()+d(this,a,"f").length}hasPending(){return d(this,a,"f").length>0||this.running.length>0}isIdle(){return!this.hasPending()}freeSlots(){return(0,p.clamp)(0,this.maxConcurrency,this.maxConcurrency-this.unsettledCount())}isFull(){return 0===this.freeSlots()}pendingNames(){return[...d(this,a,"f").map((e=>e.d.name)),...this.running.map((e=>e.name))]}get deferreds(){return[...this.running,...d(this,a,"f").map((e=>e.d))]}pendingWithName(e){return this.deferreds.filter((t=>t.name===e))}payloadsWithName(e){return this.pendingWithName(e).filter((e=>null!=e.payload)).map((e=>e.payload))}get pendingPromises(){return this.deferreds.map((e=>e.promise))}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitAll(){await Promise.all(this.pendingPromises)}async awaitAllByName(e){await Promise.all(this.deferreds.filter((t=>t.name===e)).map((e=>e.promise)))}}t.Promises=_,n=new WeakMap,s=new WeakMap,o=new WeakMap,a=new WeakMap,i=new WeakSet,l=function({name:e,l:t,payload:r,serialId:i}){const n=new P.Deferred(e,{payload:r,serialId:i});return d(this,a,"f").push({d:n,l:t}),n},u=function(e,t){const r=Date.now();return this.lastWorkTs=r,e.observe((0,y.tot)(t)).finally((()=>{var t;c(this,s,(t=d(this,s,"f"),++t),"f"),(0,m.remove)(d(this,o,"f"),e),this.settleMsAvg.push(Date.now()-r),this.laterPop()})),this.lastPushedNames.push(e.name),d(this,o,"f").push(e),e},t.maybeRun=function(e,t){const r=new _(e);return()=>r.maybeRun(e,t)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:r}){return new _(e,(0,g.map)(r,(e=>()=>e))).enqueueAll(e,t)},t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map((e=>e())))}},78656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RedoableError=void 0;class r extends Error{}t.RedoableError=r},4867:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeout=t.thenOrTimeoutError=t.timeoutStacks=void 0;const i=r(40958),n=r(34546),s=r(41400),o=r(31586),a=r(83104),l=r(85556),u=r(73568);t.timeoutStacks=[],t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:r}){let a=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>a=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>{if(a)throw new l.TimeoutError})):void 0,r?.abortPromise_().then((()=>{if(a)throw new u.AbortError}))]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:r}){let l=!0;return Promise.race((0,i.compact)([(0,n.asPromise)(e).finally((()=>l=!1)),(0,o.gt0)(t)?(0,s.delay)(t).then((()=>a.Timeout)):void 0,r?.abortPromise_().then((()=>{if(l)throw new u.AbortError}))]))}},95937:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.setTimeoutHandler=void 0;let r=e=>null;t.setTimeoutHandler=function(e){r=e},t.onTimeout=function({soft:e}={}){r(e)}},73614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefInterval=t.setUnrefTimeout=void 0;const i=r(87997);t.setUnrefTimeout=function(e,t,...r){return(0,i.setTimeout)(e,Math.round(t),...r).unref()},t.setUnrefInterval=function(e,t,...r){return(0,i.setInterval)(e,Math.round(t),...r).unref()}},31562:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.untilTrue=t.until=void 0;const i=r(38639),n=r(42659),s=r(41400),o=r(32639),a=r(31586),l=r(45255),u=r(95937);async function c(e,{timeoutMs:t,intervalMs:r,acceptable:i,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+Date.now();let m=1;for(;null==f||Date.now()t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const i=r??(0,a.clamp)(10*m,l.ShortCommandTimeoutMs,(t??n.minuteMs)/5);await(0,s.delay)(i,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:i.isTrue,timeoutResult:!1})}},9727:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.childEnv=t.spawnOptions=t.childProcEnvSettings=t.sanitizedEnv=t.psenv=void 0;const n=i(r(1708)),s=r(45599),o=r(41400),a=r(50357),l=r(68708),u=r(48884),c=r(36638),d=r(44198),h=r(59958),f=r(96706),m=r(34102),g=r(19851),p=r(19043),y=r(66184),v=r(50213),w=r(7282),S=r(88158),b=r(45969),P=r(43334),_=r(28874),E=r(3790);function M(e){return C().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const C=(0,s.defer)((()=>{const e=new c.CaseInsensitiveSet;for(const t of(0,l.values)(_.Settings)){for(const r of t.names)e.add(r);for(const r of t.keys)e.add(r)}return e.add("NODE_ENV"),e.add(h.UV_THREADPOOL_SIZE),e.add("TZ"),e}));t.psenv=function(){return(0,S.sortedKeys)((0,l.filter)((0,d.env)(),(e=>M(e))))},(0,o.later)((()=>{function e(){t.sanitizedEnv.unset()}(0,m.ee)().on("clearCache",e),(0,m.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)}));const T=["HOME","LANG","USER"],x=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],D=(0,g.lazy)((()=>{const e=(0,f.caseInsensitiveEnv)().pick(...P.isPosix?T:x),t=(0,f.caseInsensitiveEnv)().lookup("PATH");return e[t?.key??"PATH"]=(0,_.pathWithDefaults)(),e}));function k(e){const t={NODE_ENV:(0,w.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};t[h.PS_IS_CHILD_PROCESS]="1",t[h.PS_IS_DOCKER]=(0,b.isDocker)()?"1":"0",P.isElectron&&(t[h.ELECTRON_RUN_AS_NODE]="1");for(const r of(0,_.persistedSettings)()){const i=e?r.value:r.envValue;null==i||(0,a.eql)(i,r.defaultValue)||r.addToEnv(t)}return t}t.sanitizedEnv=(0,g.lazy)((()=>(0,l.filter)(n.default.env,(e=>M(e)||!(0,E.isSensitiveEnvKey)(e))))),t.childProcEnvSettings=k,t.spawnOptions=function(e){const t=e??{};return{...(0,l.omit)(t,"forceCLocale"),env:I({overrides:t.env,forceCLocale:t.forceCLocale}),detached:!1,shell:!1}};let O=!1;function I({overrides:e,forceCLocale:r=!0,forWorker:i=!1}={}){const n=(0,l.compactValues)({...(0,t.sanitizedEnv)(),...D(),...r?(0,p.childProcLocale)():{},...k(i),...e??{}});for(const e of(0,_.transientSettings)())e.deleteFromEnv(n);if((0,y.isLogged)("debug")&&!O){O=!0;const e=(0,v.mkLogger)("child.ChildEnv"),t=(0,l.entries)(n).map((([e,t])=>[e,(0,E.isHiddenEnvKey)(e)?"(hidden)":t])),[r,i]=(0,u.partition)(t,(([e])=>M(e)));e.debug("PS env:",(0,l.fromEntries)(r)),e.debug("non PS env:",(0,l.fromEntries)(i))}return n}t.childEnv=I},84777:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stdout_=t.stdoutResult_=t.execFile=t.spawn=t.AddPidAfterMs=t.ReniceAfterMs=t.endProcess=void 0;const n=i(r(31421)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(22573),u=r(42659),c=r(98553),d=r(56409),h=r(31586),f=r(68708),m=r(51926),g=r(50213),p=r(7282),y=r(88158),v=r(79089),w=r(45255),S=r(22911),b=r(4867),P=r(73614),_=r(70025),E=r(57159),M=r(36868),C=r(66184),T=r(45643),x=r(95402),D=r(9727),k=(0,o.lazy)((()=>(0,g.mkLogger)("child.ChildProcess")));function O(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function I(e,t=30*u.secondMs){if(null==e)return!1;k().debug("endProcess()",O(e));const r=e.pid;if(null==r||r<=0)return k().warn("endProcess(): asked to end invalid pid",O(e)),!1;if(r===s.default.pid)return k().warn("endProcess(): asked to end MY pid",O(e)),!1;if(r===s.default.ppid)return k().warn("endProcess(): asked to end my parent pid",O(e)),!1;(0,M.closeStreams)(e);{const t=e.kill();k().debug("endProcess("+r+")",{killResult:t,childGotSigterm:e.killed}),t||await(0,x.killPid)(r).catch((e=>{k().warn("endProcess(): kill("+r+",false) failed: "+e)}))}if((0,y.Try)((()=>e.unref())),(0,p.isSingleSpecTests)())return!0;if(await(0,T.waitForPidExit)(r,t))return k().debug("endProcess(): exitted",O(e)),!0;{x.Pids.instance()?.onKill(r);const t=e.kill("SIGKILL");k().warn("endProcess("+r+") had to resort to SIGKILL",{killResult:t}),t||await(0,x.killPid)(r,!0).catch((e=>{k().warn("endProcess(): kill("+r+",true) failed: "+e)}))}return(0,T.waitForPidExit)(r,5e3)}function A(e,r,i,n=0){const o=new Date,a=[];return(0,v.niceable)(r,i)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)}),(0,t.ReniceAfterMs)())),(0,h.gt)(n,u.secondMs)&&a.push((0,P.setUnrefTimeout)((()=>{(0,h.gt0)(e.pid)&&I(e)}),n-250)),a.push((0,P.setUnrefTimeout)((()=>{if((0,h.gt0)(e.pid))return(0,x.addPid)({pid:e.pid,cmd:r,timeoutMs:n,ppid:s.default.pid},o)}),(0,t.AddPidAfterMs)())),e.on("exit",(()=>a.forEach(clearTimeout))),e}function F(e,t,r,i){const s=(0,D.spawnOptions)(i);return(0,C.isLogged)("trace",k().context)?k().debug("execFile()",{command:e,args:t,timeoutMs:r,opts:s}):k().debug("execFile()",{command:e,args:t,timeoutMs:r}),A(n.default.execFile(e,t,s),e,t,r)}async function N(e,t,r){const i=r.quiet??!1,n=r.ignoreStderr??!1,s=r.ignoreExitCode??!1,o=F(e,t,r.timeoutMs,(0,f.omit)(r,"timeout","quiet","ignoreStderr","ignoreExitCode"));try{if(!0===r.disconnect){try{o.disconnect?.()}catch{}return{result:"",pid:o.pid}}const u=o.pid,f=(0,c.stringify)({pid:u,cmd:e,args:t}),m=[],g=[],p=[],y=new S.Deferred(f);o.on("error",(e=>p.push(e))),o.on("exit",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),o.on("close",(e=>{(0,h.isNumber)(e)&&y.isPending&&y.resolve(e)})),(0,M.endStream)(o.stdin);const v=new d.Latch;null==o.stdout?v.resolve():(o.stdout.on("error",(e=>p.push(e))),o.stdout.on("data",(e=>m.push(e))),o.stdout.on("end",(()=>v.resolve())));const P=new d.Latch;null==o.stderr||n?P.resolve():(o.stderr?.on("error",(e=>p.push(e))),o.stderr?.on("data",(e=>g.push(e))),o.stderr?.on("end",(()=>P.resolve()))),k().debug("stdoutResult_() invoked and waiting for completion...",{name:f}),await(0,b.thenOrTimeoutError)({p:y.promise,timeoutMs:r.timeoutMs,halt:r.halt}),k().debug("stdoutResult_() exitCode settled...",{name:f,exitCode:y.value,stdout:v.state(),stderr:P.state()}),await(0,b.thenOrTimeoutError)({p:v.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt}),await(0,b.thenOrTimeoutError)({p:P.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:r.halt});const C=g.join("");(0,l.notBlank)(C)&&p.push(new Error(C)),!i&&(0,a.isNotEmpty)(p)&&k().warn(f+" resulted in errors:",p);const T=r.isIgnorableError??_.isIgnorableError,x=p.filter((e=>!0!==T(e)));if(x.length>0)throw 1===x.length?x[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:x});if(!s&&0!==y.value)throw new Error(f+": exit code "+y.value);return{result:m.join(""),pid:u,code:y.value,stderr:C}}catch(e){throw k().error("stdoutResult_() failed",e),await(0,x.killPid)(o.pid,!0),e}}t.endProcess=I,t.ReniceAfterMs=(0,o.lazy)((()=>15*u.secondMs)),t.AddPidAfterMs=(0,o.lazy)((()=>30*u.secondMs)),t.spawn=function(e,t,r,i){const s=(0,D.spawnOptions)(i);return k().debug("spawn()",{command:e,args:t,maxAgeMs:r}),A(n.default.spawn(e,t,s),e,t,r)},t.execFile=F,t.stdoutResult_=N,t.stdout_=async function(e,t,r){const i=await N(e,t,r);return k().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(i.result),meta:{cmd:e,args:t,opts:r,result:i}})}},3790:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHiddenEnvKey=t.isSensitiveEnvKey=void 0;const i=r(22573),n=r(41400),s=r(19851),o=r(28874);(0,n.later)((()=>o.Settings.sensitiveEnvRegExp.watchLater((()=>a.unset()))));const a=(0,s.lazy)((()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}}));function l(e){return!(0,i.blank)(e)&&a().test(e)}t.isSensitiveEnvKey=l,t.isHiddenEnvKey=function(e){return l(e)||o.Settings.license.includesEnvKey(e)}},41269:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={main:"PhotoStructure's main process manager. Runs and manages web and sync services.",desktop:"PhotoStructure for Desktops. Manages web and sync services.",info:"Configuration, file metadata and import diagnostics tool.",list:"List items in a PhotoStructure Library.",logcat:"Chronologically sort and pretty-print PhotoStructure logfiles.",logtail:"View the log messages of currently-running PhotoStructure processes as they are emitted. (Like `tail -f`).",web:"PhotoStructure's web service. Automatically started by main. See https://phstr.com/tools for details.",sync:"PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. See https://phstr.com/go/sync for details."}},80061:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addHelpFooter=t.cliWrapWithFooter=t.cliWrapVersion=t.cliWrap=void 0;const i=r(1708),n=r(31586),s=r(51926),o=r(17344),a=r(37805),l=r(84542);function u(e,t){const r=t?.maxLineLen??(0,n.toInt)(i.env.maxLineLen)??i.stdout.columns??75;return(0,s.wrap)(e,{maxLineLen:r,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${(new Date).getFullYear()}, PhotoStructure Inc.`,"","BY USING THIS SOFTWARE, YOU ARE ACCEPTING ALL THE TERMS AND CONDITIONS OF THIS LICENSE: https://photostructure.com/eula/","","User guide: https://photostructure.com/user-guide/","","Questions, bug reports, and feature requests: https://forum.photostructure.com/",""]))}t.cliWrap=u,t.cliWrapVersion=function(){return c((0,o.EditionName)()+" v"+a.version)},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())}},94361:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=t.whyUidGidMismatched=void 0;const i=r(19851),n=r(40958),s=r(55835),o=r(31586),a=r(94174),l=r(44198),u=r(45969);function c(e,t,r){const i=(0,o.toGt0)((0,l.env)()[t]);return null==i||r.includes(i)?void 0:`WARNING: ${e} is running as ${r} but $${t}=${i}`}function d(){const e=(0,n.compactBlanks)([c("user id","PUID",(0,a.userids)()),c("group id","PGID",(0,a.groupids)())]);return 0===e.length?void 0:e}t.whyUidGidMismatched=d,t.verifyUidGid=(0,i.lazy)((()=>{(0,u.isDocker)()&&(0,s.map)(d(),(e=>console.log(["",...e,"This may result in file permission issues!","See https://forum.photostructure.com/t/1597/2 for details.",""].join("\n"))))}))},76596:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateObjectToDateTime=t.utcIsoToTs=t.isoNow=t.durationHMS=t.durationToPaddedHMS=t.fmtMs=t.isRecentMs=t.nowish=t.closeTo=t.msUntil=t.cmpDate=t.isDateObject=void 0;const i=r(51168),n=r(19851),s=r(22573),o=r(42659),a=r(55835),l=r(31586),u=r(68708),c=r(34666),d=r(50213),h=(0,n.lazy)((()=>(0,d.mkLogger)("date.Date")));function f(e,t,r){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=r}t.isDateObject=function(e){return(0,u.isObject)(e)&&["year","month","day"].every((t=>t in e))},t.cmpDate=function(e,t){const r=(0,a.mapOr)(e,(e=>e.getTime()),(()=>0)),i=(0,a.mapOr)(t,(e=>e.getTime()),(()=>0));return(0,c.cmp)(r,i)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),r=Date.now();return t<=r?0:t-r},t.closeTo=f,t.nowish=function(e,t=2500){return null!=e&&((0,o.isDate)(e)?f(e,new Date,t):Math.abs(e-Date.now()){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodeDuration=t.decodeDuration=void 0;const i=r(22573),n=r(31586),s=r(54557),o=r(91655),a=new s.FifoCache(512);function l(e){return(0,n.isNumber)(e)?e:(0,i.blank)(e)?void 0:a.getOrSet(e,(()=>(0,o.parseDuration)(e)))}t.decodeDuration=l;const u=new s.FifoCache(512);t.encodeDuration=function(e){return(0,i.blank)(e)?void 0:u.getOrSet(e,(()=>(0,o.fmtFullDuration)((0,n.isNumber)(e)?e:l(e))))}},91655:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtFullDuration=t.parseDuration=void 0;const i=r(51168),n=r(40958),s=r(22573),o=r(42659),a=r(31586),l=r(51926),u=r(68852),c=r(70417);t.parseDuration=function(e){try{if(null==e||!(0,l.isString)(e)&&!(0,a.isNumber)(e))return;if((0,a.isNumber)(e))return e;if((0,a.isDigits)(e))return(0,a.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=i.Duration.fromISO(e);if(t.isValid)return t.toMillis();const r=/[\s,]*(?-?\d*\.?\d+)\s*(?milliseconds?|msecs?|millis|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?[\s,]*?/gi,d=(0,u.captures)(r,e);if(0===d.length)return;const h=(0,n.compact)(d.map((e=>function(e,t){const r=(0,a.toFloat)(e);if(null!=r){if((0,s.blank)(t))return r;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*o.yearMs;case"weeks":case"week":case"w":return r*o.weekMs;case"days":case"day":case"d":return r*o.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return r*o.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return r*o.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return r*o.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return r;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}(e.groups?.value,e.groups?.type)))),f=(0,a.lt0)(h[0])?[h[0],...h.slice(1).map((e=>-e))]:h;return(0,c.sum)(f)}catch{return}};const d=[{ms:o.yearMs,s:"y"},{ms:o.weekMs,s:"w"},{ms:o.dayMs,s:"d"},{ms:o.hourMs,s:"h"},{ms:o.minuteMs,s:"m"},{ms:o.secondMs,s:"s"},{ms:1,s:"ms"}];t.fmtFullDuration=function e(t,r=""){if(!(0,a.isNumber)(t))return;if(0===t)return"0";if(!(0,a.gte0)(t))return(0,a.isNumber)(t)?"-"+e(Math.abs(t)):void 0;const i=[];for(const e of d.slice(d.findIndex((e=>e.ms<=t)))){const r=Math.floor(t/e.ms);t-=r*e.ms,r>0&&i.push(r+e.s)}return i.join(r)}},84248:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutoVacuumModes=void 0;const i=r(50989);t.AutoVacuumModes=(0,i.strEnum)("NONE","FULL","INCREMENTAL")},5531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CheckpointTypes=void 0;const i=r(50989);t.CheckpointTypes=(0,i.strEnum)("AUTO","PASSIVE","FULL","RESTART","TRUNCATE")},99315:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const i=r(50989);t.RepairModes=(0,i.strEnum)("dump","recover")},34365:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const i=r(50989);t.SynchronousModes=(0,i.strEnum)("OFF","NORMAL","FULL","EXTRA")},49776:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.resetCacheDir=t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=t.tmpDirs=t.tmpCacheDirs=void 0;const o=s(r(76760)),a=r(40958),l=r(22573),u=r(55835),c=r(72993),d=r(19851),h=r(97352),f=r(94174),m=r(44198),g=r(96706),p=r(8769),y=r(57159),v=r(70698),w=r(64680),S=r(29882),b=r(45969),P=r(43334),_=r(28874),E=r(41692),M=r(32774),C=r(80612),T=r(32551),x=(0,d.lazy)((()=>(0,h.mapGte0)((0,f.userid)(),(e=>"-"+e))??""));function D(){if((0,b.isDocker)())return[{dir:"/tmp/.photostructure-cache"+x(),preexistingDir:"/tmp"}];{const e=[],t=P.isWin?[(0,g.getEnv)("TEMP"),(0,g.getEnv)("TMP")]:["/tmp","/var/tmp"];for(const r of t)(0,l.blank)(r)||e.push({dir:(0,o.join)(r,".photostructure-cache"+x()),preexistingDir:r});return e}}function k(){if((0,b.isDocker)())return(0,a.compact)([(0,u.map)((0,m.env)().XDG_CACHE_HOME,(e=>({dir:(0,o.join)(e,c.SimpleAppNameLC),preexistingDir:e}))),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:M.DefaultDockerLibraryDir+"/.photostructure/cache"+x(),preexistingDir:M.DefaultDockerLibraryDir},...D()]);const e=(0,a.compactBlanks)(P.isWin?[(0,g.getEnv)("LOCALAPPDATA"),o.default.resolve((0,T.homeDir)(),"AppData","Local")]:P.isMac?[o.default.resolve((0,T.homeDir)(),"Library","Caches")]:[(0,m.env)().XDG_CACHE_HOME,(0,o.join)((0,T.homeDir)(),".cache")]),t=P.isLinux?c.SimpleAppNameLC:c.SimpleAppName,r=e.map((e=>({dir:(0,o.join)(e,t),preexistingDir:e})));return r.push(...D()),r}t.tmpCacheDirs=D,t.tmpDirs=function(){return(0,C.filterDirs)({dirs:D(),desc:"tmp"})},t.cacheDirs=k,t.defaultCacheDir=(0,d.lazy)((()=>(0,C.firstDir)({dirs:k(),desc:"cache"})));const O=(0,d.lazy)((()=>{(0,E.setSettingsDefaults)(),_.Settings.cacheDir.watchLater(I)}));function I(){_.Settings.cacheDir.refreshEnvValue({broadcastChange:!1}),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}t.cacheDir=(0,d.lazy)((()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,p.onError)("cacheDir_() failed",{error:e})}})),t.cacheDir_=(0,d.lazy)((()=>{O();const e=_.Settings.cacheDir.valueOrDefault;try{return(0,S.mkdirpSync_)(e),(0,v.writeCachedirTag_)(e).then((()=>(0,w.mkNoMedia_)(e))),e}catch(t){throw new y.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}})),t.resetCacheDir=I},46292:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.osConfigDirs=t.resetConfigDir=t.configDir=void 0;const i=r(19851),n=r(45969),s=r(41692),o=r(32774),a=r(10924),l=r(84373),u=r(80612);t.configDir=(0,i.lazy)((()=>((0,s.setSettingsDefaults)(),(0,l.envConfigDir)()??((0,n.isDocker)()?(0,u.firstDir)({dirs:c,desc:"config"}):(0,a.desktopConfigDir)()))));const c=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:o.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:o.DefaultDockerLibraryDir}];t.resetConfigDir=function(){t.configDir.unset()},t.osConfigDirs=function(){return((0,n.isDocker)()?c:(0,a.desktopConfigDirs)()).map((e=>e.dir))}},32774:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library"},55086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultOriginalsDir=t.defaultLibraryDir=void 0;const i=r(66430),n=r(45969),s=r(32774);t.defaultLibraryDir=function(){return(0,n.isDocker)()?s.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,n.isDocker)()&&(0,i.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."}},10924:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDirs=t.desktopConfigDir=void 0;const n=i(r(76760)),s=r(40958),o=r(72993),a=r(44198),l=r(96706),u=r(43334),c=r(80612),d=r(32551);function h(){const e=[];return u.isWin?e.push((0,l.getEnv)("APPDATA"),n.default.resolve((0,d.homeDir)(),"AppData","Roaming")):u.isMac?e.push(n.default.resolve((0,d.homeDir)(),"Library","Application Support")):e.push((0,a.env)().XDG_DATA_HOME,(0,a.env)().XDG_CONFIG_HOME,n.default.resolve((0,d.homeDir)(),".config")),(0,s.compactBlanks)(e).map((e=>({dir:n.default.join(e,(0,o.AppName)()),preexistingDir:e})))}t.desktopConfigDir=function(){return(0,c.firstDir)({dirs:h(),desc:"config"})},t.desktopConfigDirs=h},84373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=void 0;const i=r(22573),n=r(96706),s=r(29882);t.envConfigDir=function(){const e=(0,n.getEnv)("PS_CONFIG_DIR");if(!(0,i.blank)(e))try{return(0,s.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}}},80612:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filterDirs=t.firstDir=void 0;const i=r(44652),n=r(40958),s=r(22573),o=r(66430);function a({dirs:e,desc:t}){for(const{dir:r,preexistingDir:a}of(0,n.compact)(e))if(!(0,s.blank)(r)){if((0,o.isReadWriteableDirectorySync)(r))return r;if((0,s.blank)(a)||(0,o.isReadWriteableDirectorySync)(a))try{return(0,i.mkdirpSync)(r),r}catch(e){console.error("Failed to mkdir for "+t,e)}}}t.firstDir=a,t.filterDirs=function({dirs:e,desc:t}){return(0,n.compact)(e.map((e=>a({dirs:[e],desc:t}))))}},32551:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const i=r(48161),n=r(76760),s=r(1708),o=r(19851),a=r(40958),l=r(68284),u=r(43334);t.homeDir=(0,o.lazy)((()=>{const e=[];u.isWin?e.push(s.env.USERPROFILE):e.push(s.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,n.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,i.homedir)()}))},46296:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=t.defaultLogDir_=t.defaultLogDirs=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(55835),u=r(54993),c=r(72993),d=r(96706),h=r(45969),f=r(43334),m=r(32707),g=r(6707),p=r(49776),y=r(32774),v=r(80612),w=r(32551);function S(){return(0,h.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:y.DefaultDockerLibraryDir+"/.photostructure/logs",preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:f.isMac?[{dir:n.default.resolve((0,w.homeDir)(),"Library","Logs",c.SimpleAppName),preexistingDir:(0,w.homeDir)()}]:(0,o.compact)((0,p.cacheDirs)()).map((e=>({dir:(0,l.map)(e.dir,(e=>n.default.resolve(e,"logs"))),preexistingDir:e.preexistingDir})))}function b(){return(0,v.firstDir)({dirs:S(),desc:"logs"})}t.defaultLogDirs=S,t.defaultLogDir_=b,t.logDir=(0,s.lazy)((()=>{try{const e=(0,d.getEnv)("logDir");if((0,a.notBlank)(e))return e;const t=(0,g.readTomlFileSync)((0,m.systemSettingsFile)()),r=(0,u.toS)(t?.logDir);return(0,a.notBlank)(r)?r:b()}catch(e){return console.error("defaultLogDir_() failed",e),n.default.resolve((0,w.homeDir)(),"logs")}}))},55939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=t.picturesDirWindows=void 0;const i=r(76760),n=r(19851),s=r(22573),o=r(44198),a=r(43334),l=r(24399),u=r(32551);async function c(){return a.isWin?l.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDirWindows=c,t.picturesDir=(0,n.lazy)((async()=>{if(a.isWin){const e=await c();if((0,s.notBlank)(e))return e}return(0,t.defaultPicturesDir)()})),t.defaultPicturesDir=(0,n.lazy)((()=>(0,o.env)().XDG_PICTURES_DIR??(0,i.resolve)((0,u.homeDir)(),"Pictures")))},77740:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setDevEnvFlag=t.getDevEnvFlag=void 0;const i=r(38639),n=r(7282),s=r(29325),o=r(44198);t.getDevEnvFlag=function(e){return!(0,n.isProd)()&&!(0,s.isPacked)()&&((0,i.toBoolean)((0,o.env)()[e])??!1)},t.setDevEnvFlag=function(e,t){process.env[e]=(0,o.env)()[e]=String(t)}},34580:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.doNotTrack=void 0;const i=r(38639),n=r(44198);t.doNotTrack=function(){return(0,i.isTrue)((0,n.env)().DO_NOT_TRACK)}},44198:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.env=void 0;const n=i(r(73024)),s=r(76760),o=i(r(1708)),a=r(19851),l=r(40958),u=r(41400),c=r(68708),d=r(76850),h=r(7282),f=r(23560),m=r(32551),g=r(34102),p=r(53265),y=r(45969),v=r(59958),w=r(6012),S=r(96706);t.env=(0,a.lazy)((()=>{const e=(0,l.uniq)((0,l.compactBlanks)(v.PS_ENV_KEYS.map((e=>o.default.env[e])).join(s.delimiter).split(s.delimiter)));0!==e.length||(0,y.isDocker)()||(0,h.isTest)()&&"lite"===o.default.env.PS_LICENSE||e.push((0,s.join)((0,m.homeDir)(),".psenv"));const t=(0,S.SensitiveEnvRE)(),r={...o.default.env};for(const i of e)try{const e=(0,d.debom)(n.default.readFileSync((0,p.resolve)(i))),s=(0,w.parseEnvTokens)({input:e,lowerCaseKeys:!1});for(const[e,i]of(0,c.entries)(s))t.test(e)||(r[e]=i)}catch(e){"ENOENT"!==e.code&&(0,f.isMainService)()&&console.warn("env(): failed to read .env file, "+i,e)}return r})),(0,u.later)((()=>{(0,g.ee)().on("clearCache",(()=>t.env.unset()))}))},59958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=t.PS_ENV_KEYS=void 0;const i=r(50989);t.PS_ENV_KEYS=["PS_ENV","PS_ENV_FILE","PS_ENV_PATH"],t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.DevEnvFlags=(0,i.strEnum)("PS_BAIL_ON_ERROR","PS_FAIL_DB_HEALTH_CHECK","PS_FAIL_SECURITY_HEALTH_CHECK","PS_FAIL_VOLUMES","PS_FORCE_FULLDISK","PS_FORCE_LITE","PS_FORCE_TRIAL","PS_KEEP_ENV","PS_NO_RANDOM_IMAGE_CACHE","PS_PRIVATE_KEYS","PS_QUICK","PS_SINGLE_SPEC_TESTS","PS_SKIP_ALL_TESTS","PS_SKIP_CLEANUP","PS_SKIP_RUN","PS_SLOMO","PS_TEST_HEALTH_CHECK_LEVEL","PS_FIX_JSON"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_CHILD_PROCESS,...t.DevEnvKeys,...t.PS_ENV_KEYS,...t.DevEnvFlags.values]},83373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnvKeys=void 0;const i=r(50989);t.EnvKeys=(0,i.strEnum)("HOME","NO_COLOR","PATH","PS_CONFIG_DIR","TMP","TEMP","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","USERPROFILE","windir")},6012:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=void 0;const i=r(22573),n=r(84542);t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){const r={};if((0,i.blank)(e))return r;let s;for(const o of(0,n.splitCompactLines)(e)){const e=/#.*$|(?:export\s+)?(?[a-z_]+)=(["'])?(?(?:\\["']|.)*?)\2(?=$|\s|#)/gim;for(;null!=(s=e.exec(o));){if(null==s.groups)continue;const{key:e,val:n}=s.groups;if((0,i.blank)(e)||null==n)continue;const o=n.replace(/\\n/g,"\n").replace(/\\(["'])/g,"$1");r[t?e.toLowerCase():e]=o}}return r}},96706:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isEnvTrue=t.getEnv=t.onEnvChange=t.caseInsensitiveEnv=t.SensitiveEnvRE=t.SensitiveEnvRegexPattern=void 0;const n=i(r(1708)),s=r(19851),o=r(22573),a=r(38639),l=r(41400),u=r(40583),c=r(79840),d=r(83556),h=r(34102),f=r(44198),m=r(83373);function g(){t.caseInsensitiveEnv.unset(),t.SensitiveEnvRegexPattern.unset(),t.SensitiveEnvRE.unset()}function p(e){return(0,t.caseInsensitiveEnv)().get(e)??(m.EnvKeys.includes(e)?void 0:(0,t.caseInsensitiveEnv)().get("PS_"+(0,d.camel2snake)(e)))}t.SensitiveEnvRegexPattern=(0,s.lazy)((()=>(0,o.firstNotBlank)(n.default.env.PS_SENSITIVE_ENV_REGEX_PATTERN,n.default.env.sensitiveEnvRegexPattern,c.DefaultSensitiveEnvRegexPattern))),t.SensitiveEnvRE=(0,s.lazy)((()=>{try{return new RegExp((0,t.SensitiveEnvRegexPattern)(),"i")}catch(e){return console.error(`Invalid setting for "sensitiveEnvRegExp": ${e}. Using default value.`),new RegExp(c.DefaultSensitiveEnvRegexPattern,"i")}})),t.caseInsensitiveEnv=(0,s.lazy)((()=>new u.CaseInsensitiveValued((0,f.env)()))),t.onEnvChange=g,(0,l.later)((()=>{f.env.watchLater(g),(0,h.ee)().on("clearCache",g)})),t.getEnv=p,t.isEnvTrue=function(e){return(0,a.isTrue)(p(e))}},98314:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToVerbose=t.MissingError=t.errorToS=t.joinErrorMessages=t.normalizeErrorMessages=t.splitErrorMessage=t.errorsToPath=t.addMessage=t.throws=t.errorContains=t.mapError=t.lastInternalErrors=t.internalErrorRate=t.fatalErrorRate=t.errorRate=t.logger=t.StartTs=void 0;const i=r(58587),n=r(19851),s=r(40958),o=r(22573),a=r(26905),l=r(96249),u=r(51926),c=r(23541),d=r(54993),h=r(89788),f=r(50213),m=r(81168),g=r(84542),p=r(41954),y=r(38835),v=r(70025),w=r(57159);function S(...e){if((0,s.isEmpty)(e))return[];const t=e.map((e=>(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,d.toS)(e?.message??e)));t.push(...(0,p.getErrorDescriptions)(e));const r=[...e.filter(c.isError).map(a.errorName),...e.map(a.errorCode),...(0,s.compactBlanks)(t).map(m.stripAnsiEsc).flatMap((e=>(0,g.splitCompactLines)(e))).flatMap((e=>e.split(a.ErrorDelimiter)))];return(0,s.uniqSubstrings)(b((0,l.flatten)(r)))}function b(e){return(0,s.compact)(e).filter((e=>!a.IgnoredErrorNames.includes(e))).map((e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim())).filter(o.notBlank)}function P(e,t){const r=(0,s.uniqSubstrings)(b(e)),i=t?.maxLen??400,n=t?.trailingChars??64,o=(0,y.sortErrorFlags)([...t?.flags??[],...(0,v.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,v.stripErrorFlags)(r.join(a.ErrorDelimiter)),i-o.length,n)+o.sort().join("")}function _(e,t){return e instanceof w.WrappedError?e.toString():(0,o.blank)(e)?"":P(S(e),t)}t.StartTs=Date.now(),t.logger=(0,n.lazy)((()=>(0,f.mkLogger)("Error"))),t.errorRate=new i.Rate,t.fatalErrorRate=new i.Rate,t.internalErrorRate=new i.Rate,t.lastInternalErrors=new h.BoundedList(10),t.mapError=function(e,t){return e instanceof Error?t(e):void 0},t.errorContains=function(e,t){return t.test(_(e))},t.throws=function(e){try{return e(),!1}catch{return!0}},t.addMessage=function(e,t){return null==e?new Error(t):((0,o.notBlank)(t)&&(e.message.toLowerCase().includes(t.toLowerCase())||(e.message+=": "+t)),e)},t.errorsToPath=function(...e){for(const t of e)for(const e of["nativePath","path"]){const r=(0,d.toS)(t?.[e]);if((0,o.notBlank)(r))return r}},t.splitErrorMessage=S,t.normalizeErrorMessages=b,t.joinErrorMessages=P,t.errorToS=_,t.MissingError="(missing error)",t.errorToVerbose=function(e,r=256,i=7){return(0,o.blank)(e)&&(e=t.MissingError),_(e,{maxLen:r})+" at "+(0,a.shortStack)(e?.stack,i).join("; ")}},41954:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getErrorDescriptions=t.describeError=void 0;const i=r(40958),n=r(26905),s=r(55835),o=r(54993),a=r(81168);t.describeError=function(e){const t=(0,a.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return l[t]?.description??e},t.getErrorDescriptions=function(...e){const t=[];for(const r of e)(0,s.map)((0,n.errorErrno)(r),(e=>t.push(u.get(e)))),(0,s.map)((0,n.errorCode)(r),(e=>t.push(l[e]?.description)));return(0,i.uniq)(t)};const l={UNKNOWN:{errno:-1,description:"unknown error"},OK:{errno:0,description:"success"},EOF:{errno:1,description:"end of file"},EADDRINFO:{errno:2,description:"getaddrinfo error"},EACCES:{errno:3,description:"permission denied"},EAGAIN:{errno:4,description:"resource temporarily unavailable"},EADDRINUSE:{errno:5,description:"address already in use"},EADDRNOTAVAIL:{errno:6,description:"address not available"},EAFNOSUPPORT:{errno:7,description:"address family not supported"},EALREADY:{errno:8,description:"connection already in progress"},EBADF:{errno:9,description:"bad file descriptor"},EBUSY:{errno:10,description:"resource busy or locked"},ECONNABORTED:{errno:11,description:"software caused connection abort"},ECONNREFUSED:{errno:12,description:"connection refused"},ECONNRESET:{errno:13,description:"connection reset by peer"},EDESTADDRREQ:{errno:14,description:"destination address required"},EFAULT:{errno:15,description:"bad address in system call argument"},EHOSTUNREACH:{errno:16,description:"host is unreachable"},EINTR:{errno:17,description:"interrupted system call"},EINVAL:{errno:18,description:"invalid argument"},EISCONN:{errno:19,description:"socket is already connected"},EMFILE:{errno:20,description:"too many open files"},EMSGSIZE:{errno:21,description:"message too long"},ENETDOWN:{errno:22,description:"network is down"},ENETUNREACH:{errno:23,description:"network is unreachable"},ENFILE:{errno:24,description:"file table overflow"},ENOBUFS:{errno:25,description:"no buffer space available"},ENOMEM:{errno:26,description:"not enough memory"},ENOTDIR:{errno:27,description:"not a directory"},EISDIR:{errno:28,description:"illegal operation on a directory"},ENONET:{errno:29,description:"machine is not on the network"},ENOTCONN:{errno:31,description:"socket is not connected"},ENOTSOCK:{errno:32,description:"socket operation on non-socket"},ENOTSUP:{errno:33,description:"operation not supported on socket"},ENOENT:{errno:34,description:"no such file or directory"},ENOSYS:{errno:35,description:"function not implemented"},EPIPE:{errno:36,description:"broken pipe"},EPROTO:{errno:37,description:"protocol error"},EPROTONOSUPPORT:{errno:38,description:"protocol not supported"},EPROTOTYPE:{errno:39,description:"protocol wrong type for socket"},ETIMEDOUT:{errno:40,description:"connection timed out"},ECHARSET:{errno:41,description:"invalid Unicode character"},EAIFAMNOSUPPORT:{errno:42,description:"address family for hostname not supported"},EAISERVICE:{errno:44,description:"servname not supported for ai_socktype"},EAISOCKTYPE:{errno:45,description:"ai_socktype not supported"},ESHUTDOWN:{errno:46,description:"cannot send after transport endpoint shutdown"},EEXIST:{errno:47,description:"file already exists"},ESRCH:{errno:48,description:"no such process"},ENAMETOOLONG:{errno:49,description:"name too long"},EPERM:{errno:50,description:"operation not permitted"},ELOOP:{errno:51,description:"too many symbolic links encountered"},EXDEV:{errno:52,description:"cross-device link not permitted"},ENOTEMPTY:{errno:53,description:"directory not empty"},ENOSPC:{errno:54,description:"no space left on device"},EIO:{errno:55,description:"i/o error"},EROFS:{errno:56,description:"read-only file system"},ENODEV:{errno:57,description:"no such device"},ESPIPE:{errno:58,description:"invalid seek"},ECANCELED:{errno:59,description:"operation canceled"}},u=new Map(Object.values(l).map((e=>[e.errno,e.description])))},38835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FatalErrorPatterns=t.FailStr=t.ErrorFlagsRE=t.RedoableFlag=t.WebFatalErrorFlag=t.NonFatalErrorFlag=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.InternalErrorFlag=t.HealthCheckWarningFlag=t.RetriableErrorFlag=t.DoNotSendErrorFlag=t.HealthCheckErrorFlag=t.PleaseSendErrorFlag=t.IgnorableErrorFlag=t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag=t.FatalErrorFlag=t.sortErrorFlags=t.ErrorFlags=void 0;const i=r(40958),n=r(76790),s=r(50989),o=r(68852);t.ErrorFlags=(0,s.strEnum)("⁰","¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₃","₄"),t.sortErrorFlags=function(e){return(0,n.sortBy)((0,i.uniq)(e),(e=>t.ErrorFlags.indexOf(e)))},t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotRetryErrorFlag=t.NonRetriableErrorFlag,t.IgnorableErrorFlag=t.ErrorFlags["³"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.WebFatalErrorFlag=t.ErrorFlags["₃"],t.RedoableFlag=t.ErrorFlags["₄"],t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0}),t.FatalErrorPatterns=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr],t.FatalErrorRe=new RegExp(t.FatalErrorPatterns.map(o.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},70025:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInternalError=t.isFatalError=t.isDoNotSendError=t.isNonRetriableError=t.isRetriableError=t.isRedoableError=t.isSqliteConstraintError=t.isSqliteDisconnectedError=t.isSqliteBusyError=t.isIgnorableError=t.isPleaseSendError=t.isHealthCheckError=t.hasErrorFlag=t.extractErrorFlags=t.stripErrorFlags=t.addErrorFlags=void 0;const i=r(40958),n=r(38639),s=r(26905),o=r(54993),a=r(68852),l=r(73568),u=r(78656),c=r(98314),d=r(38835);function h(e){return(0,o.toS)(e).replace(d.ErrorFlagsRE,"").trim()}function f(e){return d.ErrorFlags.values.filter((t=>e.includes(t)))}function m(e){return(0,c.errorToS)(e).includes(d.PleaseSendErrorFlag)}t.addErrorFlags=function(e,...t){const r=(0,o.toS)(e)+(0,i.compact)(t).join("");return h(r)+f(r).join("")},t.stripErrorFlags=h,t.extractErrorFlags=f,t.hasErrorFlag=function(e){return d.ErrorFlags.values.some((t=>e.includes(t)))},t.isHealthCheckError=function(e){return(0,c.errorToS)(e).includes(d.HealthCheckErrorFlag)},t.isPleaseSendError=m;const g=/Can't write [a-z\d]+ files/i,p=(0,a.orRegExpPatterns)([d.IgnorableErrorFlag,"AbortError","0 output files created","debugger attached","debugger listening on","diskutil: interrupted","ECONNRESET","ECONNREFUSED","EPIPE","for help","Format error in file","https://nodejs.org/en/docs/inspector","Missing expected status message","net::ERR_","This socket has been ended by the other party","Unexpected error while trimming",/\bwarning\b/i],"i");t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const r=(0,c.errorToS)(e);return!g.test(r)&&(!!p.test(r)||void 0)};const y=/SQLITE_BUSY|database is locked|busy executing a query/i;function v(e){return"SQLITE_BUSY"===e.code||y.test((0,c.errorToS)(e))}function w(e){return null!=(0,c.errorToS)(e).match(/database .+ not open/i)}function S(e){return null!=(0,c.errorToS)(e).match(/SQLITE_CONSTRAINT|constraint failed/i)}function b(e){return!!((0,n.isFalse)(e.retriable)||e instanceof l.AbortError||(0,c.errorToS)(e).includes(d.NonRetriableErrorFlag)||S(e))||void 0}t.isSqliteBusyError=v,t.isSqliteDisconnectedError=w,t.isSqliteConstraintError=S,t.isRedoableError=function(e){return e instanceof u.RedoableError||(0,c.errorToS)(e).includes(d.RedoableFlag)},t.isRetriableError=function(e){if(null==e)return;if(!0===b(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,s.errorCode)(e)||v(e)||w(e))return!0;const r=(0,c.errorToS)(e);return!(!r.includes("EBUSY")&&!r.includes(d.RetriableErrorFlag))||void 0},t.isNonRetriableError=b;const P=[d.DoNotSendErrorFlag,"BatchCluster has ended","Corrupt JPEG data","ENOSPC","Invalid data found when processing input","premature end of data segment","VipsJpeg"];t.isDoNotSendError=function(e){const t=e?.doNotSend;if("boolean"==typeof t)return t;if(m(e))return!1;const r=(0,c.errorToS)(e).toLowerCase();return!!P.some((e=>r.includes(e)))||void 0},t.isFatalError=function(e){if(null==e)return!1;if((0,n.isTrue)(e.fatal))return!0;const t=(0,c.errorToS)(e);return!!t.includes(d.FatalErrorFlag)||!t.includes(d.NonFatalErrorFlag)&&d.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,n.isTrue)(e.internalError)||d.InternalErrorRe.test((0,c.errorToS)(e)))}},8769:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onInternalError=t.isFatalErrorAllowed=t.onError=void 0;const i=r(22573),n=r(31586),s=r(68708),o=r(7282),a=r(23560),l=r(45608),u=r(34102),c=r(28874),d=r(98314),h=r(38835),f=r(70025),m=r(57159),g=r(5012);function p(e,t){try{if((0,i.blank)(e)&&(0,s.isEmptyObj)(t))return(0,d.logger)().warn("onError() with no args",(0,g.stack)()),!1;const r=(0,m.toWrappedError)(e,t);(0,f.isInternalError)(e)&&(d.internalErrorRate.onEvent(),d.lastInternalErrors.push(e));const n=!0===r.fatal,c=!0===r.ignorable;if(!n&&c)return(0,d.logger)().info("onError(): (ignorable)",{error:e}),!1;d.errorRate.onEvent(),n&&(d.fatalErrorRate.onEvent(),(0,u.ee)().emit("fatal",r));const h=!n||y()?"nonFatal":"fatal";return(0,d.logger)().log("fatal"===h?"error":"warn","onError()",{event:h,error:r}),!n||(0,o.isTest)()||(0,a.isWebService)()||(0,l.exit)({reason:r.toString(),status:r.errno??13}),n}catch{return console.error("onError() threw an error!",{err:e,meta:t}),!1}}function y(){const e=(0,n.lt)(d.fatalErrorRate.eventsPerMinute,c.Settings.fatalErrorRatePerMinute.valueOrDefault),t=!(0,a.isPermaService)();return(0,d.logger)().tap({level:"info",msg:"isFatalErrorAllowed()",result:t&&e,meta:{acceptsFatalErrors:t,lowErrorRate:e,fatalErrorRatePerMin:(0,n.sigFigs)(d.fatalErrorRate.eventsPerMinute,2),errorRatePerMin:(0,n.sigFigs)(d.errorRate.eventsPerMinute,2),fatalErrorRatePerMinuteSetting:c.Settings.fatalErrorRatePerMinute.valueOrDefault}})}t.onError=p,t.isFatalErrorAllowed=y,t.onInternalError=function(e,t,r){return p(e+h.InternalErrorFlag,{cause:t,...r})}},57159:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=t.toWrappedError=void 0;const i=r(40958),n=r(22573),s=r(38639),o=r(26905),a=r(98553),l=r(68708),u=r(59455),c=r(41583),d=r(48884),h=r(81168),f=r(98314),m=r(38835),g=r(70025);t.toWrappedError=function(e,t){const r=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof p&&(null==t||(0,n.blank)(r.message)||e.message.includes(r.message)))return e;const i=(0,n.firstNotBlank)((0,h.isString)(e)?e:void 0,e?.message,r?.message);return new p(i??"(missing error message)",r)};class p extends Error{constructor(e,t={}){super(e),this.causes=(0,i.uniqBy)((0,c.toErrs)(t.cause,t.meta?.error,...(0,u.toA)(t.causes)),(e=>e.message)),this.name=(0,o.errorName)(t)??(0,d.first)(this.causes,o.errorName)??"Error",this.codes=(0,h.splitUniq)([t.code,...this.causes.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,d.first)(this.causes,(e=>(0,o.errorErrno)(e))),this.syscall=t.syscall??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.syscall))),this.path=t.path??(0,d.first)(this.causes,(e=>(0,n.toNotBlank)(e.path))),this.flags=t?.flags??[];const r=[t,this.flags.join(""),...this.causes];this.fatal=t.fatal??r.some(g.isFatalError),this.retriable=t.retriable??(0,s.maybeAnd)(r.map(g.isRetriableError)),this.ignorable=t.ignorable??(0,s.maybeAnd)(r.map(g.isIgnorableError)),this.doNotSend=t.doNotSend??(0,s.maybeAnd)(r.map(g.isDoNotSendError)),this.flags=(0,m.sortErrorFlags)([...this.flags,this.fatal?m.FatalErrorFlag:void 0,!0===this.retriable?m.RetriableErrorFlag:void 0,!1===this.retriable?m.NonRetriableErrorFlag:void 0,!0===this.ignorable?m.IgnorableErrorFlag:void 0,!1===this.doNotSend?m.PleaseSendErrorFlag:void 0,!0===this.doNotSend?m.DoNotSendErrorFlag:void 0]),this.meta=(0,l.mergeObjectsDeep)(...(t.causes??[]).map((e=>e.meta)),t.cause?.meta,(0,l.omit)(t,"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","fatal","doNotSend","flags","meta"),t.meta),this.message=(0,g.stripErrorFlags)(function(e,t){let r=(0,f.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const i=t?.path;return(0,n.blank)(i)||(r=(0,h.dedupeNeedle)(r,i,"file")),(0,f.joinErrorMessages)([r[0],t?.code,...(0,u.toA)(t?.codes),t?.syscall,e,null!=t&&(0,l.notEmptyObj)(t?.meta)?(0,a.stringify)(t.meta):void 0,...r.slice(1)])}(e,this))+this.flags.join(""),this.stack=t.stack??(0,d.first)(this.causes,(e=>e.stack)),null==this.stack&&Error.captureStackTrace(this)}toJSON(){return{_ctor:"WrappedError",...this,message:this.message}}static fromJSON(e){return new p(e.message,e)}toString(){return this.message}toS(e){return null==e?this.message:(0,h.ellipsize)(this.message,e.maxLen,Math.max(e.trailingChars,this.flags.length+1))}}t.WrappedError=p},5012:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stack=void 0,t.stack=function e(){const t={};return Error.captureStackTrace(t,e),t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},15197:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=void 0;const o=r(49769),a=r(55835),l=r(54993),u=r(22911),c=r(89788),d=r(7282);t.CapturingEventEmitter=class{constructor(e,t=((0,d.isTest)()?10:0)){this.target=e,this.eventsToRetain=t,i.set(this,new Map),n.set(this,new Map),this.priorEvents=new c.BoundedList(t)}once(e,t){return this.target.once(e,t),this}watchEvent(e){return(0,o.getOrSet)(s(this,i,"f"),e,(()=>new u.Deferred("watchEvent("+(0,l.toS)(e)+")")))}on(e,t){return this.target.on(e,t),this}off(e,t){return this.target.off(e,t),this}emit(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").delete(e),this.eventsToRetain>0&&this.priorEvents.push({name:e,args:t});const r=this.target.emit(e,...t),o=s(this,i,"f").get(e);return null!=o&&(o.resolve(t),s(this,i,"f").delete(e)),r}emitDebounced(e,...t){(0,a.map)(s(this,n,"f").get(e),clearTimeout),s(this,n,"f").set(e,setTimeout((()=>this.emit(e,...t)),50))}listeners(e){return this.target.listeners(e)}removeAllListeners(e){return this.target.removeAllListeners(e),this}},i=new WeakMap,n=new WeakMap},34102:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const i=r(78474),n=r(19851),s=r(15197);t.ee=(0,n.lazy)((()=>{const e=new i.EventEmitter;return e.setMaxListeners(70),new s.CapturingEventEmitter(e)}))},64660:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.access=t.canRWXFirstExistingAncestor=t.isStatRX=t.isStatRWX=t.canAccessSync=void 0;const n=i(r(73024)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(65843),u=r(16287),c=r(43334),d=(0,o.lazy)((()=>s.default.geteuid?.())),h=(0,o.lazy)((()=>s.default.getgroups?.()));function f(e,t){try{return!(0,a.blank)(e)&&(n.default.accessSync(e,t),!0)}catch{return!1}}function m(e,t){return c.isWin?f(t,n.default.constants.R_OK|n.default.constants.W_OK):p({stat:e,r:!0,w:!0,x:!0})}function g(e,t){return c.isWin?f(t,n.default.constants.R_OK):p({stat:e,r:!0,x:!0})}function p({stat:e,r:t=!1,w:r=!1,x:i=!1,processUid:n,processGid:s}){if(null==e)return!1;const o=n??d(),a=null!=s?[s]:h()??[],l=0===o,u=l||e.uid===o,f=l||a.includes(e.gid);return!(t&&!(((u?256:0)|(f?32:0)|4)&e.mode))&&(!(r&&!(((u?128:0)|(f?16:0)|2)&e.mode))&&!!(!i||c.isWin||((u?64:0)|(f?8:0)|1)&e.mode))}t.canAccessSync=f,t.isStatRWX=m,t.isStatRX=g,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const r of(0,l.selfAndAncestorG)(e)){const i=await(0,u.statMaybe)(r);if(null!=i){if(!i.isDirectory())return!1;if(t){if(!g(i,e))return!1}else if(t=!0,!m(i,e))return!1}}return!0},t.access=p},21144:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath_=t.actualPath=void 0;const n=i(r(76760)),s=r(19851),o=r(81168),a=r(57159),l=r(43334),u=r(88561),c=r(29882),d=r(65238),h=r(53265);t.actualPath=async function(...e){try{return await m(...e)}catch(t){return(0,c.logger)().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,h.resolve)(...e)}};const f=(0,s.lazy)((()=>new u.FileCache({name:"fs.Path.actualPathCache"})));async function m(...e){const t=(0,h.resolve)(...e);return l.isLinux||(0,c.pathIsRoot)(t)?t:f().getOrSetAsync(t,(async()=>{const r=(0,c.parseNativePath)((0,h.resolve)(...e)),i=await m(r.dir);for(const e of await(0,d.readdir_)(i))if((0,o.equalsIgnoreCase)(e.basename,r.base))return n.default.join(i,e.basename);throw new a.WrappedError(t+" not found",{code:"ENOENT",path:t})}))}t.actualPath_=m},65843:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ancestorWithChildren=t.hasChildrenSync=t.childrenSync=t.selfAndAncestorG=t.ancestorG=t.ancestors=void 0;const i=r(73024),n=r(76760);function s(e){return[...o(e)]}function*o(e){for(;e!==(0,n.dirname)(e);)e=(0,n.dirname)(e),yield e}function a(e){try{return(0,i.readdirSync)(e)}catch(e){return[]}}function l(e,t){const r=a(e);return t.every((e=>r.includes(e)))}t.ancestors=s,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=a,t.hasChildrenSync=l,t.ancestorWithChildren=function(e,t){return s(e).find((e=>l(e,t)))}},83278:function(e,t,r){var i,n,s,o,a,l=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),u=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),c=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&l(t,e,r);return u(t,e),t},d=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},h=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=t.useFsWatch=t.BaseFile=t.isBaseFile=void 0;const m=c(r(44652)),g=c(r(73024)),p=r(51455),y=f(r(76760)),v=f(r(1708)),w=r(46466),S=f(r(57975)),b=f(r(38522)),P=r(19851),_=r(40958),E=r(5233),M=r(22573),C=r(42659),T=r(50357),x=r(96249),D=r(98553),k=r(55835),O=r(31586),I=r(68708),A=r(97790),F=r(39926),N=r(51926),L=r(59455),R=r(54993),j=r(48884),B=r(22911),V=r(99331),z=r(56519),W=r(56038),q=r(31562),U=r(76850),G=r(70025),H=r(34102),J=r(80875),K=r(50213),$=r(70417),Y=r(43334),Z=r(81168),X=r(96859),Q=r(65162),ee=r(94174),te=r(64660),re=r(21144),ie=r(84542),ne=r(89968),se=r(20197),oe=r(88561),ae=r(50597),le=r(33456),ue=r(29882),ce=r(78133),de=r(43899),he=r(65238),fe=r(53265),me=r(17217),ge=r(16287),pe=r(68284),ye=r(66003),ve=r(27794),we=r(73428),Se=r(13047);t.isBaseFile=function(e){return(0,me.isSimpleFile)(e)&&e instanceof Pe};const be=(0,P.lazy)((()=>new oe.FileCache({name:"fs.BaseFile"})));class Pe{constructor(e,t){if(i.add(this),this.dirent=t,this.bflog=(0,P.lazy)((()=>(0,K.mkLogger)("fs.BaseFile("+this.nativePath+")"))),n.set(this,(0,P.lazy)((async()=>(await this.directoryEntry())?.children()))),o.set(this,void 0),null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,ue.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,ce.native2posix)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[(n=new WeakMap,o=new WeakMap,i=new WeakSet,S.default.inspect.custom)](){return this.toJSON()}static async withFastestAccess(e){const t=(0,_.compact)(e),r=await Promise.all(t.map((e=>e.shaMs())));return t[(0,j.leastIndex)(r)]}static forPosix(e){return e instanceof Pe?e:this.for(e.split("/").join(y.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof Pe)return e;const r=(0,me.isSimpleFile)(e)?e.nativePath:(0,R.toS)(e);if((0,M.blank)(r))throw new Error("BaseFile.for(): empty nativePathOrFile");const i=be().get(r);if(null!=i)return i;const n=(0,fe.resolve)(r),s=new Pe(n,t);return be().set(r,s),be().set(n,s),s}static clear(e){(0,H.ee)().emit("fileChanged",e)}for(e,t){return Pe.for(e,t)}forDirectoryEntry(e){return Pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingDirent(e){return this.forDirectoryEntry(ne.DirectoryEntry.fromSimpleDirent(this.dir,e))}clear({emit:e}={}){return!0===e&&(0,H.ee)().emit("fileChanged",this.nativePath),this.dirent=void 0,d(this,n,"f").unset(),h(this,o,void 0,"f"),this}clearThisAndParent(){return(0,H.ee)().emit("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,fe.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}eql(e){return null!=e&&(0,ue.eqlPath)(this,e)}get isUNC(){return(0,ue.isUNC)(this.nativePath)}get baseWithParent(){return(this.isRoot?"/":this.parent().isRoot?"/"+this.base:(this.parent().parent().isRoot?"/":"")+this.parent().base+"/"+this.base).normalize()}ellipsize({maxLength:e=80}={}){return(0,ue.ellipsizePath)({p:this,maxLength:e})}get baseWithParentNoExt(){return(0,Z.stripSuffix)(this.baseWithParent,this.ext)}get baseWithGrandparent(){return(this.isRoot?"/":this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+"/"+this.base).normalize()}posixPathFrom(e){return(0,ue.posixPathFrom)(e,this)+(this.isDirectorySync()?"/":"")}async directoryEntry(){return this.dirent??(this.dirent=await(0,z.thenMap)(this.stat(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}directoryEntrySync(){return this.dirent??(this.dirent=(0,k.map)(this.statSync(),(e=>new ne.DirectoryEntry(this.dir,new ne.StatDirent(this.base,e)))))}async childDirectoryEntries(e){const t=await d(this,n,"f").call(this);if(null==t||null==e||(0,_.isEmpty)(t))return t;const r=[];for(const i of t)!0===await e(i)&&r.push(i);return r}_directoryEntryChild(e){return this.for(y.default.join(this.nativePath,e.base),e)}childNames(){return(0,z.thenMap)(this.childDirectoryEntries(),(e=>e.map((e=>e.base))))}async resolve_(){var e;return await d(this,i,"m",s).call(this)??await d(e=this.clearThisAndParent(),i,"m",s).call(e)}async children_(e){const t=await(0,he.readdir_)(this.nativePath);return null!=e&&await(0,_.filterInPlaceAsync)(t,e),t.map((e=>this.forChildDirent(e)))}async children(e){return(await this.childDirectoryEntries(e))?.map((e=>this._directoryEntryChild(e)))}async childFiles(e){const t=await this.childDirectoryEntries((async t=>t.isFile()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}async childDirectories(e){const t=await this.childDirectoryEntries((async t=>t.isDirectory()&&(null==e||!0===await e(t))));return null==t?void 0:t.map((e=>this._directoryEntryChild(e)))}childrenSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath).map((e=>this.join(e)))))??[]}childFilesSync(){return this.trapSync("childrenSync",(()=>g.default.readdirSync(this.nativePath,{withFileTypes:!0}).filter((e=>e.isFile())).map((e=>this.join(e.name)))))??[]}async hasChildren(e){const t=await this.childNames();return(0,_.isNotEmpty)(e)?(0,_.includesAll)(t,e):(0,_.isNotEmpty)(t)}async hasNoChildren(){return await this.isFile()||(0,_.isEmpty)(await this.childNames())}async visitDescendants(e){return(0,z.thenMap)(this.children(),(async t=>{for(const r of t)await r.visitDescendants(e),await e(r)}))}async descendants(e){const t=[];t.push(...(0,L.toA)(await this.childFiles(e)));const r=await this.childDirectories();if(null==r)return t;for(const i of r)t.push(...(0,L.toA)(await i.descendants(e)));return t}async someDescendant(e,t=0){if(!(0,O.gt0)(t))return;const r=await d(this,n,"f").call(this)??[];for(const t of r)if(!0===await e(t))return this._directoryEntryChild(t);if(t>0)for(const i of r)if(i.isDirectory()){const r=await this._directoryEntryChild(i).someDescendant(e,t-1);if(null!=r)return r}}descendantsSync(e){const t=this.directoryEntrySync(),r=[];return t?.visitDescendantsSync((t=>{!0===e(t)&&r.push(this.forDirectoryEntry(t))})),r}async ancestorWithChildren(e){return await this.hasChildren(e)?this:this.isRoot?void 0:this.parent().ancestorWithChildren(e)}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map((e=>t._directoryEntryChild(e)))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries((async t=>t.base!==this.base&&(null==e||!0===await e(t))))}async selfAndSiblings(){return this.parent().children()}async firstExistingSelfOrAncestor(){return this.isRoot||await this.exists()?this:this.parent().firstExistingSelfOrAncestor()}get pathnames(){return(0,ue.splitNativePath)(this.nativePath)}get pathsForDateParsing(){return[...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,Q.bname)(this.name)]}get pathnamesWithoutDrive(){return Y.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,ue.pathDepth)(this)}get isRoot(){return(0,ue.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ue.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ue.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,me.toNativePath_)(e)||this.isDescendantOf(e))}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:0===e?this:this.parent().ancestor(e-1)}findAncestor(e){return this.isRoot?void 0:e(this)?this:this.parent().findAncestor(e)}parents(){const e=this.parent();return this.isRoot?[]:[...e.parents(),e]}async normalize(){return this.isUNC?this:this.for(await(0,re.actualPath)(this.nativePath))}sibling(e){return this.parent().join(e)}withPrefix(e){return this.sibling(e+this.base)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,_.isEmpty)(e)||(0,T.eql)(["."],e)||e.every(M.blank)?this:(0,ue.isAbsolute)(e[0])?this.for(y.default.join(...e)):this.for(y.default.join(this.nativePath,...e))}joinYMD(e=new Date){return(0,k.map3)(e?.getFullYear(),e?.getMonth(),e?.getDate(),((e,t,r)=>this.join((0,R.toS)(e),(0,F.pad2)(t+1),(0,F.pad2)(r))))}child(...e){if((0,_.isEmpty)(e))return this;const t=(0,x.flatten)(e.map((e=>e.split(y.default.sep)))).filter((e=>".."!==e));return this.join(...t)}async trap(e,t,r="warn"){try{return await(0,W.time)("fs."+e+":"+this.nativePath,t)}catch(t){return void this.bflog().log(r,`trap: ${e}() failed: ${t}`)}}async trapOr(e,t,r="warn"){try{return await(0,W.time)("fs."+e,t),!0}catch(t){return this.bflog().log(r,`trapOr: ${e}() failed: ${t}`),!1}}trapSync(e,t,r){try{return(0,W.timeSync)("fs."+e,t)}catch(t){return void this.bflog().log(r??"warn",`${e}() failed: ${t}`)}}stat_(){return(0,ge.stat_)(this.nativePath)}async stat(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??await(0,ge.statMaybe)(this.nativePath,e?.logLevel??"trace"),"f")}statSync(e){return e?.refresh&&h(this,o,void 0,"f"),h(this,o,d(this,o,"f")??(0,pe.statSync)(this.nativePath),"f")}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||await(0,z.thenDefined)(this.stat(e))}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return(0,z.thenNot)(this.exists(e))}async isDeleted(e=3){if(await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}mtime(){return(0,z.thenMap)(this.stat(),(e=>e.mtime))}mtimeMs(e){return(0,z.thenMap)(this.stat(e),(e=>Math.floor(e.mtimeMs)))}async mtimeSec(){const e=await this.stat();return null==e?void 0:(0,C.unixtime)(e.mtimeMs)}async lastModifiedUtc(){return(await this.stat())?.mtime.toUTCString()}async statTimes(){const e=await this.stat();return null==e?void 0:(0,ge.statTimes)(e)}maxStatMs(){return(0,z.thenMap)(this.statTimes(),j.max)}maxStatDate(){return(0,z.thenMap)(this.maxStatMs(),(e=>new Date(e)))}minStatMs(){return(0,z.thenMap)(this.statTimes(),$.min)}minStatDate(){return(0,z.thenMap)(this.minStatMs(),(e=>new Date(e)))}async size(e){return(0,z.thenMap)(this.stat(e),(e=>e.size))}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,te.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,te.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,z.thenNot)(this.isReadable())}async isReadWritable(){return(0,te.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,z.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,te.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,te.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,te.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,te.isStatRWX)(e,this.nativePath)}async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${Y.isWin?"":"/execute"} by ${await(0,ee.userDesc)()}`)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,ue.isHiddenBasename)(this.base)}async isEmpty(e=0){if(await this.isDirectory())return(0,_.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,z.thenNot)(this.isEmpty(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size=e}async modifiedGTE(e){return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>=(0,C.unixtime)(e)))}async modifiedCloseTo(e,t){return(0,z.thenMap)(this.mtimeMs(),(r=>Math.abs(r-e)<=t))}async isRecent(e){const t=await this.maxStatMs();return null!=t&&t>Date.now()-e}async modifiedGT(e){if(null!=e)return(0,z.thenMap)(this.mtime(),(t=>(0,C.unixtime)(t)>(0,C.unixtime)(e)))}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,z.thenNot)(this.isDirectory())}isDirectorySync(e){return null!=this.dirent?this.dirent.isDirectory():(0,k.mapOr)(this.statSync(e),(e=>e.isDirectory()),(()=>!1))}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",(()=>this.isFile_()))}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,A.opt)(this.statSync()).filter((e=>e.isFile())).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",(async()=>(await m.rmdir(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",(()=>(m.rmdirSync(this.nativePath,{recursive:!1,maxRetries:8,retryDelay:500}),!0)),e)??!1}async mkdirp_(){try{await(0,ue.mkdirp_)(this.nativePath)}catch(e){if("EEXIST"!==e?.code)throw e}if(!1===await(0,q.untilTrue)((()=>this.clear().isDirectory()),{timeoutMs:2*C.secondMs,intervalMs:200}))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}async mkdirp(){return await this.clear().isDirectory()||this.isRoot?this:this.trap("mkdirp",(async()=>this.mkdirp_()))}mkdirpSync_(){return(0,ue.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",(()=>this.mkdirpSync_()))}sha_(){return(0,ae.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",(()=>this.sha_()))}async shaMs(){return this.trap("shaMs",(async()=>(await(0,ae.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs))}async readJson_(){return(0,J.parseJSON)((await m.readFile(this.nativePath)).toString())}async readJson(e="warn"){return await this.isNonEmptyFile()?this.trap("readJson",(()=>this.readJson_()),e):void 0}readJsonSync(e){return this.trapSync("readJsonSync",(()=>(0,J.parseJSON)((0,g.readFileSync)(this.nativePath).toString())),e)}readFileSync_(){return(0,g.readFileSync)(this.nativePath)}readFile_(){return(0,p.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",(()=>this.readFile_()),e)}async readTextFile_(){return(0,U.bufferToString)(await this.readFile_())}readTextFile(e="warn"){return this.trap("readTextFile",(()=>this.readTextFile_()),e)}async zReadFile_(e){return(0,Se.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",(()=>(0,z.thenMap)(this.zReadFile_(e),R.toS)))}readLines(e="warn"){return(0,z.thenMap)(this.readTextFile(e),ie.splitLines)}readFileSync(){try{return g.default.readFileSync(this.nativePath).toString()}catch(e){return void this.bflog().warn("readFileSync() failed",{error:e})}}async writeText_(...e){return await(0,we.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,we.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,we.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",(()=>(0,we.writeFileSync_)(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces))))}async writeJson(e,t){return this.trap("writeJson",(()=>this.writeJson_(e,t)))}async writeJson_(e,t){return await(0,ue.mkdirp_)(this.dir),await m.writeFile(this.nativePath,(0,D.stringify)(e,t?.replacer,t?.spaces),(0,I.omit)(t,"replacer","spaces")),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);return null!=t[0]&&null!=t[1]&&t[0].size===t[1].size&&await this.sha()===await e.sha()}async touch(e={}){return this.trap("touch",(()=>this.touch_(e)))}async touch_(e={}){return await(0,ve.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",(async()=>(await(0,ve.touch_)({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this)))}async rm(e="warn"){return this.unlink(e)}async unlink(e="warn"){return this.trap("unlink",(()=>this.unlink_()),e)}unlinkSync_(){try{m.unlinkSync(this.nativePath)}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",(()=>this.unlinkSync_()),e)}async unlink_(){return await m.unlink(this.nativePath),this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",(()=>this.rmrf_()),e)}async rmrf_(){return(0,E.retryOnReject_)((async()=>{const e=await this.stat({refresh:!0});return null!=e&&await m.rm(this.nativePath,{recursive:e.isDirectory(),force:!0}),this.clearThisAndParent()}),{maxRetries:(0,V.ending)()?1:3,timeoutMs:0,retryDelay:C.secondMs,errorIsRetriable:G.isRetriableError})}async gunzip(){return d(this,i,"m",a).call(this,(0,Z.stripSuffix)(this.base,".gz"),b.default.createGunzip())}async gzip(){return d(this,i,"m",a).call(this,this.base+".gz",b.default.createGzip())}async compressBrotli(){return d(this,i,"m",a).call(this,this.base+".br",b.default.createBrotliCompress())}ensureFile_(){return m.ensureFile(this.nativePath).then((()=>this.clearThisAndParent()))}ensureFile(){return this.trap("ensureFile",(()=>this.ensureFile_()))}ensureFileSync_(){return m.ensureFileSync(this.nativePath),this.clearThisAndParent()}async ensureNewNativePath(e){return(0,se.ensureNewNativePath_)({nativePath:this.nativePath,...e})}ensureNew_(e={}){return this.ensureNewNativePath(e).then((e=>this.for(e)))}ensureNewSync_(e={}){return this.for((0,se.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await m.chmod(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return g.default.chmodSync(this.nativePath,e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}zreadline(){return g.default.createReadStream(this.nativePath).on("error",(e=>{throw new Error("Failed to read from "+this+": "+e)})).pipe(b.default.createGunzip()).on("error",(e=>{throw new Error("Failed to gunzip "+this+": "+e)})).pipe(new le.LineReader)}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,W.time)("fs.childWithSameContents",(async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const r=await this.children((async r=>!r.isNameHidden()&&t===r.size()&&r.nativePath!==e.nativePath));if((0,_.isEmpty)(r))return;const i=await e.sha();if(null!=i)for(const e of r.sort(((e,t)=>-(0,X.diceCoeff)(e.base,t.base))).slice(0,64))if(await e.sha()===i)return e}))}firstMatchingLine(e){const t=new B.Deferred("firstMatchingLine("+this+")"),r=g.default.createReadStream(this.nativePath,{flags:"r"});return r.on("error",(e=>{-2===e.errno||"ENOENT"===e.code?(t.maybeResolve(void 0),r.close()):t.maybeReject(e)})),r.on("close",(()=>t.maybeResolve(void 0))),(0,ye.onDataChunked)(r,(0,N.newlineRe)(),(i=>{const n=e.exec(i);null!=n&&(t.maybeResolve(n),r.close())})),t.promise}contemporary(e,t){return(0,z.thenMap2Or)(this.statTimes(),e.statTimes(),((e,r)=>{for(const i of e)for(const e of r)if((0,O.closeTo)(i,e,t))return!0;return!1}),(()=>!1))}watchUntil(e){const t=e.accept??(e.accept=e=>null!=e&&!1!==e),r=new B.Deferred("watchUntil("+this.nativePath+")");if(e.timeoutMs>0&&r.setTimeout(e.timeoutMs),_e)try{const i=(0,g.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},(async(i,n)=>{try{const s=await e.f(i,(0,k.denull)(n));t(s)&&r.resolve(s)}catch(e){r.reject(e)}}));r.finally((()=>{i.close()}))}catch(t){e.intervalMs??(e.intervalMs=500),this.bflog().warn("fs.watch failed, using polling",{error:t,opts:e})}else e.intervalMs??(e.intervalMs=500),this.bflog().warn("watchUntil(): fsWatch disabled, using polling",{opts:e});if((0,O.gt0)(e.intervalMs)){const i=setInterval((async()=>{try{const i=await e.f();t(i)&&r.resolve(i)}catch(e){r.reject(e)}}),e.intervalMs);e.persistent||i.unref(),r.finally((()=>{clearInterval(i)}))}return r}}t.BaseFile=Pe,s=async function(){const e=(await(0,he.readdir_)(this.dir)).filter((e=>(0,Z.equalsIgnoreCase)(e.basename,this.base))),t=(0,j.leastBy)(e,(e=>(0,X.hamming)(e.basename,this.base)));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,k.map)(t,(e=>this.forSiblingDirent(e))),meta:{sibs:e}})},a=async function(e,t){return this.trap("pipeTo("+e+")",(async()=>{const r=await this.sibling(e).ensureNew_();return await(0,w.pipeline)([g.default.createReadStream(this.nativePath,{autoClose:!0}),t,g.default.createWriteStream(r.nativePath,{autoClose:!0})]),await this.unlink(),r}))},Pe.attrTTL=3*C.minuteMs,Pe.projectRoot=(0,P.lazy)((()=>{const e=de.ProjectPath.Root();if(null==e)throw new Error("Cannot find project path");return Pe.for(e)}));let _e=!0;t.useFsWatch=function(e){_e=e},t.execDir=function(){return Pe.for(v.default.execPath).parent()}},84542:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitCompactLines=t.joinLines=t.splitLines=t.crlf=t.Newline=void 0;const i=r(40958),n=r(96249),s=r(51926),o=r(54993),a=r(43334);function l(...e){return(0,n.flatten)(e.map((e=>Array.isArray(e)?l(...e):(0,o.toS)(e).split((0,s.newlineRe)()))))}t.Newline=a.isWin?"\r\n":"\n",t.crlf=function(...e){const t=e.map(o.toS).join("\n");return a.isWin?t.replace((0,s.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,i.compactBlanks)(l(...e))}},70698:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeCachedirTag_=t.isCachedirTagFile=t.isCachedirTagDirectory=t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0;const i=r(76760),n=r(19851),s=r(50213),o=r(37805),a=r(29882),l=r(93854),u=r(17217),c=r(16287),d=r(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const h=(0,n.lazy)((()=>(0,s.mkLogger)("fs.CachedirTag")));async function f(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;if(!await(0,c.isNonEmptyFile)((0,u.toNativePath_)(e),t.CACHEDIR_TAG_CONTENT.length))return!1;try{const r=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return r===t.CACHEDIR_TAG_CONTENT}catch(t){return h().debug("isCachedirTagFile(): failed to read "+e,t),!1}}t.isCachedirTagDirectory=async function(e){return f((0,i.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=f,t.writeCachedirTag_=async function(e){const r=(0,u.toNativePath_)(e);await(0,a.mkdirp_)(r),await(0,d.writeTextfile_)((0,a.joinNativePath)([r,t.CACHEDIR_TAG]),t.CACHEDIR_TAG_CONTENT,"# This file marks this directory hierarchy as cached content.","# It can be safely deleted if PhotoStructure is not currently running.","#","# Created by https://photostructure.com "+o.version,"#","# See https://bford.info/cachedir/ for details about this file")}},92234:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPaths=t.DefaultWinPaths=t.DefaultDockerPaths=t.DefaultPosixPaths=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(22573),l=r(45969),u=r(43334),c=Object.freeze(["/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/usr/bin","/bin","/usr/sbin","/sbin"]);t.DefaultPosixPaths=Object.freeze(["/usr/local/bin","/usr/local/sbin","/usr/lib/libraw","/opt/local/bin","/opt/local/sbin","/usr/sbin","/usr/bin","/sbin","/bin"]),t.DefaultDockerPaths=Object.freeze(["/opt/photostructure/tools/bin",...t.DefaultPosixPaths]),t.DefaultWinPaths=(0,o.lazy)((()=>[...(0,a.mapNotBlankOr)(s.default.env.SYSTEMROOT,(e=>[e,n.default.join(e,"System32"),n.default.join(e,"System32","webm")]),(()=>[])),"C:\\cygwin64\\bin"])),t.DefaultPaths=Object.freeze((0,l.isDocker)()?t.DefaultDockerPaths:u.isWin?(0,t.DefaultWinPaths)():u.isMac?c:t.DefaultPosixPaths)},89968:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0;const a=s(r(44652)),l=o(r(73024)),u=r(76760),c=r(57975),d=r(19851),h=r(59455),f=r(50213),m=r(81168),g=r(34102),p=r(29882),y=r(65238),v=r(14427),w=r(17217),S=r(16287),b=r(68284);class P{constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof l.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}t.StatDirent=P;const _=(0,d.lazy)((()=>(0,f.mkLogger)("fs.DirectoryEntry")));class E{constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,u.join)(this.dir,t.base),this.ext=(0,p.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new E(e,new P(t.basename,t))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:r,base:i}=(0,w.isSimpleFile)(e)?e:{nativePath:e,...(0,p.parseNativePath)(e)},n=await a.stat(t);return new E(r,new P(i,n))}clear(){return(0,g.ee)().emit("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return E.for((0,u.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(u.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,p.parentBasename)(this.nativePath)}toJSON(){return{_ctor:this.constructor.name,nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[c.inspect.custom](){return this.toJSON()}toString(){return this.nativePath}isFile(){return this.dirent.isFile}isFileSync(){return this.dirent.isFile}isDirectory(){return this.dirent.isDirectory}isDirectorySync(){return this.dirent.isDirectory}get isRoot(){return this.dir===(0,u.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,p.parseNativePath)(this.dir);return e.dir===this.dir?this:new E(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map((e=>e.basename)):void 0}catch(e){return void _().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map((e=>E.fromSimpleDirent(this.nativePath,e)))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}childrenSync(){try{if(!this.isDirectory())return;const e=l.default.readdirSync(this.nativePath,{withFileTypes:!0});return e?.map((e=>new E(this.nativePath,new P(e.name,e))))}catch(e){return void _().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,h.toA)(await this.children()).filter((e=>e.isDirectory()))}async childFiles(){return(0,h.toA)(await this.children()).filter((e=>e.isFile()))}async visitDescendants(e){const t=await this.children();if(null!=t){for(const r of t)r.isDirectory()&&await r.visitDescendants(e);for(const r of t)r.isFile()&&await e(r);for(const r of t)r.isDirectory()&&await e(r)}}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const r of t)r.isFile()&&e(r);for(const r of t)r.isDirectory()&&(r.visitDescendantsSync(e),e(r))}}async visitDescendantFiles(e){return this.visitDescendants((t=>t.isFile()?e(t):void 0))}async filterDescendantFiles(e){const t=[];return await this.visitDescendantFiles((async r=>{!0===await e(r)&&t.push(r)})),t}statDirent(){const e=(0,b.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,S.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){await a.unlink(this.nativePath),(0,g.ee)().emit("fileChanged",this.nativePath)}async rmdir_(e){await a.rmdir(this.nativePath,e),(0,g.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=E},20197:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ensureNewNativePathSync_=t.ensureNewNativePath_=t.DefaultEnsureNewOptions=void 0;const n=i(r(76760)),s=r(39926),o=r(29882),a=r(16287),l=r(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),t.ensureNewNativePath_=async function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if(await(0,o.mkdirp_)(i.dir),!r.requireNumber&&await(0,a.isEmptyFile)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if(await(0,a.isEmptyFile)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)},t.ensureNewNativePathSync_=function(e){const r={...t.DefaultEnsureNewOptions,...e},i=(0,o.parseNativePath)(r.nativePath);if((0,o.mkdirpSync_)(i.dir),!r.requireNumber&&(0,l.isEmptyFileSync)(r.nativePath,r))return r.nativePath;for(let e=r.startIndex;e<=r.maxVersions;e++){const t=n.default.join(i.dir,`${i.name}-${(0,s.leftPad)(e,r.leftPad,"0")}${i.ext}`);if((0,l.isEmptyFileSync)(t,r))return t}throw new Error("There are already more than "+r.maxVersions+" of "+r.nativePath)}},88561:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.isCacheableFile=t.InstanceCacheMaxSize=void 0;const o=r(40958),a=r(22573),l=r(41400),u=r(68708),c=r(25764),d=r(38836),h=r(34102),f=r(80049),m=r(50213),g=r(88158),p=r(45255);function y(e){return"object"==typeof e&&"function"==typeof e.clear}t.InstanceCacheMaxSize=256,t.isCacheableFile=y;class v extends f.FifoCacheAsync{constructor(e){super({maxSize:t.InstanceCacheMaxSize,timeoutMs:p.ShortCommandTimeoutMs,...e}),i.add(this),(0,l.later)((()=>{(0,h.ee)().on("fileChanged",(e=>s(this,i,"m",n).call(this,e))),(0,h.ee)().on("clearCache",(()=>this.clear())),new d.EndableWrapper(e.name+" stats",(()=>{const t=(0,g.mapEntries)(this.stats(),((e,t)=>t>0?t:void 0));(0,o.isNotEmpty)((0,u.keys)(t))&&(0,m.mkLogger)(e.name).info("stats",t)}),c.EndableRanks.stats)}))}}t.FileCache=v,i=new WeakSet,n=async function(e){if((0,a.blank)(e))this.clear();else for(const t of this.cache.keys())if(t.startsWith(e)){const e=await this.cache.get(t);y(e)?e.clear({emit:!1}):this.cache.delete(t)}}},32144:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSidecarMimetype=t.isSidecarExt=t.SidecarExts=t.SidecarFiletypes=t.isLogExt=t.isCsvExt=t.isJsonExt=t.isJpegExt=t.normalizeExt=void 0;const i=r(73024),n=r(22573),s=r(45599),o=r(96249),a=r(68708),l=r(54993),u=r(49047),c=r(17217),d=[u.JpegExts,["tiff","tif"],["heif","heic"],["html","htm"],["jp2","jp2k"]],h=(0,s.defer)((()=>{const e={};for(const[t,...r]of d)for(const i of r)e[i]=t;return e})),f=/(?:^\.?|.\.)(?[a-z\d]{2,4})(?:_original)?$/i;function m(e){const t=(0,c.isSimpleFile)(e)?e.ext:e instanceof i.Dirent?e.name:(0,l.toS)(e),r=f.exec((0,l.toS)(t))?.groups?.ext?.toLowerCase();return(0,n.blank)(r)?void 0:h()[r]??r}t.normalizeExt=m,t.isJpegExt=function(e){return m(e)===u.JpegExts[0]},t.isJsonExt=function(e){return"json"===m(e)},t.isCsvExt=function(e){return"csv"===m(e)},t.isLogExt=function(e){const t=(0,l.toS)(e);return t.endsWith(".log")||t.endsWith(".log.gz")},t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,o.flatten)((0,a.values)(t.SidecarFiletypes)),t.isSidecarExt=function(e){return function(e,...t){e=m(e);for(const r of t)if(r===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes}},43624:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fileStatsSync=t.fileStats=t.fileStats_=void 0;const i=r(68708),n=r(17217),s=r(16287),o=r(68284);async function a(e){return(0,i.pick)(await(0,s.stat_)((0,n.toNativePath_)(e)),"size","mtimeMs","ino","birthtimeMs")}t.fileStats_=a,t.fileStats=async function(e){try{return await a(e)}catch{return}},t.fileStatsSync=function(e){return null==(t=(0,o.statSync)((0,n.toNativePath)(e)))?void 0:(0,i.pick)(t,"size","mtimeMs","ino","birthtimeMs");var t}},4001:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.stripDSC=t.copySuffixCountFromName=t.stripCopySuffixFromName=t.ciStablePosixPath=t.ymdIsoRE=void 0;const i=r(22573),n=r(55835),s=r(31586),o=r(51926),a=r(54993),l=r(97352),u=r(29882),c=[/\s*(?:-\s*)?copy(?:\s*\d{1,3}\s*)?$/i,/\s*(?:-\s*)?copy\s*\(\s*\d{1,3}\s*\)$/i,/\s*\((?:another|\d+[a-z]{2})?\s*copy\)$/i,/\s*-?\(\s*\d{1,4}\s*\)$/,/(?<=[\da-f-]{37}-)[\da-f-]+$/i,/\s*-\s*\d{1,3}$/],d=[...c,/\s*-?edit(?:ed)?$/i];function h(e,t={aggressive:!0}){return f((0,i.toNotBlank)(e.name)??(0,a.toS)(e),t).normalize()}function f(e,r){if(t.ymdIsoRE.test(e))return e;let i=e;for(const e of r.aggressive?d:c){const t=i.match(e);if((0,s.gt0)(t?.index)){const e=i.slice(0,t.index).trim();e.length>0&&(i=e)}}return e===i?e:f(i,r)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/,t.ciStablePosixPath=function(e){const t=e.split("/"),r=t.pop();if((0,i.blank)(r))return e;const n=(0,u.parsePosixPath)(r),s=h(n,{aggressive:!1});return[...t,s+n.ext].join("/").normalize()},t.stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,o.isString)(e)?e:e.name).toLowerCase().normalize(),r=h(t),i=(0,o.stripPrefix)(t.toLowerCase().normalize(),r);return(0,n.map)((0,l.extractInt)(i),Math.abs)};const m=/burst\s*([\w-]{8,})\s*$/i,g=/(?<=.{6})_cover$/i,p=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;t.stripDSC=function(e){let t=((0,o.isString)(e)?e:e.name).trim().replace(g,"").trim();return(0,n.map)(m.exec(t),(e=>t=e[1].trim())),(0,n.map)(p.exec(t),(e=>t=e[1].trim())),t}},50597:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.randomSha=t.numericSha=t.streamSha_=t.uncachedFileSha_=t.fileSha_=t.fileShaMeta_=t.shimmedFileSha_=void 0;const n=i(r(77598)),s=i(r(73024)),o=r(46466),a=r(19851),l=r(98553),u=r(68708),c=r(23467),d=r(80049),h=r(73913),f=r(50213),m=r(12089),g=r(37628),p=r(43624),y=r(17217),v=r(16287),w=(0,a.lazy)((()=>(0,f.mkLogger)("fs.Hash"))),S=(0,a.lazy)((()=>new d.FifoCacheAsync({name:"fs.fileSha",maxSize:512,timeoutMs:0,clearEveryMs:0})));async function b(e,{autoInvalidate:r=!0}={}){const i=(0,y.toNativePath_)(e);if(r){const t=S().get(i);if(null!=t){if((0,c.eql)(t.stats,await(0,p.fileStats_)(e)))return w().debug("fileSha_() cache matches current Stats",{nativePath:i,prior:t}),t;w().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:i,prior:t}),S().delete(i)}}return(0,t.shimmedFileSha_)(e)}async function P(e){const t=Date.now(),r=(0,y.toNativePath_)(e);return{sha:await _(s.default.createReadStream(r)),stats:(0,u.pick)(await(0,v.stat_)(r),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:Date.now()-t}}async function _(e,t=[],r="sha512"){const i=n.default.createHash(r);return await(0,o.pipeline)([e,...t,i]),i.digest().subarray(0,h.HashBits/8).toString("base64")}t.shimmedFileSha_=(0,m.shim1)({name:"fs.Hash",cache:S,impl:P}),t.fileShaMeta_=b,t.fileSha_=async function(e){return(await b(e)).sha},t.uncachedFileSha_=P,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,g.stringShaToBuffer)((0,l.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return n.default.randomBytes(h.HashBits/8).toString("base64")}},25675:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyIgnorableMountpoint=t.isIgnorableMountpoint=t.isPhotoStructureDmg=void 0;const i=r(22573),n=r(54993),s=r(7282),o=r(43334),a=r(69375),l=/^\/dev(?:\/|$)/i,u=o.isMac||(0,s.isTest)()?["/dev","/System/Volumes/Hardware","/System/Volumes/iSCPreboot","/System/Volumes/Preboot","/System/Volumes/Update","/System/Volumes/VM","/System/Volumes/xarts","/Volumes/Install","/Volumes/Recovery"].map((e=>e.toLowerCase())):void 0,c=o.isMac||(0,s.isTest)()?/^\/private\//i:void 0,d=o.isMac||(0,s.isTest)()?/^\/Volumes\/install macos\b/i:void 0,h=o.isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0;function f(e){return null!=h?.exec((0,n.toS)(e))}function m(e){return(0,i.blank)(e)?"blank":(0,a.isExcludedMountpoint)(e)?"excluded":l.test(e)?"/dev":!0===u?.includes(e.toLowerCase())?"macOS system volume":!0===d?.test(e)?"macOS installer volume":!0===c?.test(e)?"macOS private volume":f(e)?"PhotoStructure dmg":void 0}t.isPhotoStructureDmg=f,t.isIgnorableMountpoint=function(e){return null!=m(e)},t.whyIgnorableMountpoint=m},49047:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},33456:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const i=r(57075),n=r(51926),s=r(54993);class o extends i.Transform{constructor(){super({objectMode:!1,autoDestroy:!0}),this._prior=""}_transform(e,t,r){const i=(this._prior+(0,s.toS)(e)).split((0,n.newlineRe)()),o=i.pop();this._prior=o??"";let a=!1;for(const e of i)a||(a=!this.push(e));a?setTimeout(r,1):r()}_flush(e){""!==this._prior&&this.push(this._prior),this._prior="",e()}}t.LineReader=o},64680:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=void 0;const n=i(r(76760)),s=r(17217),o=r(73428);t.mkNoMedia_=function(e){return(0,o.writeTextfile_)(n.default.join((0,s.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")}},29882:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathIncludesPathElement=t.bestMountpointForDir=t.joinNativePathMaybe=t.joinNativePath=t.splitNativePath=t.move_=t.mkdirpSync_=t.mkdirp_=t.isAbsolute=t.isUNC=t.addNameSuffix=t.posixPathFromGrandparent=t.posixPathFromParent=t.ellipsizePaths=t.ellipsizePath=t.posixPathFrom=t.pathDepth=t.pathIsRoot=t.toPathnames=t.eqlPath=t.eqlNameWithoutExt=t.eqlBasename=t.containedByNativePath=t.grandParentBasename=t.parentBasename=t.parseNativePath=t.extMatches=t.dirname=t.extname=t.parsePosixPath=t.resolveMaybe=t.resolveSimpleFile=t.isNotHiddenPosixPath=t.containsHiddenPathname=t.isHiddenBasename=t.logger=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(19851),a=r(40958),l=r(5233),u=r(22573),c=r(98553),d=r(39426),h=r(51926),f=r(48884),m=r(50213),g=r(81168),p=r(70025),y=r(43334),v=r(78133),w=r(53265),S=r(17217),b=r(16287),P=r(66430),_=r(5545);function E(e){return((0,S.isSimpleFile)(e)?e.base:s.default.basename(s.default.resolve(e))).startsWith(".")}t.logger=(0,o.lazy)((()=>(0,m.mkLogger)("fs.Path"))),t.isHiddenBasename=E,t.containsHiddenPathname=function(e){return k(e).some(E)},t.isNotHiddenPosixPath=function(e){return k(e).every((e=>!E(e)))},t.resolveSimpleFile=function(e){return(0,S.isSimpleFile)(e)?e.nativePath:(0,w.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(u.blank)?void 0:(0,w.resolve)(...e)},t.parsePosixPath=function(e){return C((0,v.posix2native)(e))},t.extname=function(e){return C(e).ext},t.dirname=function(e){return s.default.dirname((0,S.toNativePath_)(e))},t.extMatches=function(e,t){return!(0,u.blank)(e)&&!(0,u.blank)(t)&&(0,g.equalsIgnoreCase)(s.default.parse(e).ext,s.default.parse(t).ext)};const M=/^(?.*?)(?\.(?:gz|z|7z|xz|bz2|br))?$/i;function C(e){const t=M.exec(e)?.groups,r=t?.ext2??"",i=s.default.parse(t?.path??e);return{...i,ext:(i.ext??"")+r,base:(i.base??"")+r}}function T(e){const t=s.default.parse((0,S.toNativePath_)(e));return t.root===t.dir?t.root:(0,h.splitLast)(t.dir,s.default.sep)}function x(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,S.toNativePath_)(e.ancestor),r=(0,S.toNativePath_)(e.descendant);if((0,u.blank)(t)||(0,u.blank)(r))return!1;const i=e.acceptSelf??!1;return t===r?i:r.startsWith((0,g.ensureSuffix)(t,s.default.sep))}catch(r){return(0,t.logger)().warn("containedByNativePath() failed (returning false)",{args:e,error:r}),!1}}function D(e,t,r){if(null==t||null==r)return!1;const i=e(t),n=e(r);return null!=i&&null!=n&&(y.isLinux?i===n:(0,g.equalsIgnoreCase)(i,n))}function k(e){return(0,S.isSimpleFile)(e)?e.pathnames:e.split(s.default.sep).filter((e=>null!=e&&""!==e))}function O(e){return(0,u.notBlank)(e)&&k(e).length===(y.isWin?1:0)}function I({p:e,maxLength:t}){const r=(0,S.toNativePath_)(e);if(r.length<=t)return r;const i=k(e),n=[],s=[i.pop()];for(;i.length>0;)if(n.length=t){i.unshift(n.pop());break}}else if(s.unshift(i.pop()),F([...n,...s]).length>=t){i.push(s.shift());break}return i.length>0&&n.push("…"),F([...n,...s])}function A(e){return e.startsWith("\\\\")}function F(e){return(0,h.ensurePrefix)((0,a.compactBlanks)(e).join(s.default.sep),y.isWin?"":s.default.sep)}t.parseNativePath=C,t.parentBasename=T,t.grandParentBasename=function(e){return T(s.default.parse((0,S.toNativePath_)(e)).dir)},t.containedByNativePath=x,t.eqlBasename=function(e,t){return D(S.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return D(S.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return D(S.toNativePath_,e,t)},t.toPathnames=k,t.pathIsRoot=O,t.pathDepth=function(e){return(0,u.blank)(e)?void 0:k(e).length-(y.isWin?1:0)},t.posixPathFrom=function(e,t){const r=(0,S.toNativePath_)(e),i=(0,S.toNativePath_)(t);if((0,u.blank)(r)||(0,u.blank)(i))throw new Error("posixPathFrom empty args "+(0,c.stringify)({parent:e,child:t}));return r===i?"":(0,g.stripPrefix)((0,v.native2posix)(i).normalize(),(0,g.ensureSuffix)((0,v.native2posix)(r),"/").normalize()).normalize()},t.ellipsizePath=I,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:r=4,arrLength:i=e.length}){const n=[];for(const i of e.slice(0,r))n.push(I({p:i,maxLength:t}));return n.join(", ")+(i>r?`, and ${i-r} more…`:"")},t.posixPathFromParent=function(e){return k(e).slice(-2).join("/")},t.posixPathFromGrandparent=function(e){return k(e).slice(-3).join("/")},t.addNameSuffix=function(e,t){const r=C(e);return`${r.base}${t}${r.ext}`},t.isUNC=A,t.isAbsolute=function(e){return y.isPosix&&e.startsWith("/")||y.isWin&&(A(e)||null!=e.match(_.driveRe))},t.mkdirp_=async function(e){try{if(await(0,b.isReadableDirectory)(e))return;if(O(e))throw new d.MetaError("refusing to create root directory",{code:"ENOENT"});await n.default.mkdirp(e)}catch(t){if(await(0,b.isReadableDirectory)(e))return;throw t}},t.mkdirpSync_=function(e,t){try{if((0,P.isReadWriteableDirectorySync)(e))return;n.default.mkdirpSync(e,t)}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}},t.move_=async function(e,t){return(0,l.retryOnReject_)((()=>n.default.move(e,t,{overwrite:!0})),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,S.toNativePath_)(e).split(s.default.sep).filter((e=>null!=e&&""!==e))},t.joinNativePath=F,t.joinNativePathMaybe=function(...e){return e.some(u.blank)?void 0:F(e)},t.bestMountpointForDir=function(e,t){return(0,f.greatestBy)(t,(t=>x({ancestor:t,descendant:e,acceptSelf:!0})?[(0,S.toNativePath_)(t).length]:void 0))},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)}},8103:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=t.wmic=t.pathIfExists=t.pathTo=t.isRXFile=void 0;const n=i(r(76760)),s=r(19851),o=r(40958),a=r(22573),l=r(31586),u=r(51926),c=r(12168),d=r(59455),h=r(54993),f=r(50213),m=r(44198),g=r(96706),p=r(45969),y=r(43334),v=r(64660),w=r(21144),S=r(16287),b=(0,s.lazy)((()=>(0,f.mkLogger)("fs.PathTo"))),P=c.KiB;async function _(e,t=P){const r=await(0,S.statMaybe)(e,"trace");return null!=r&&r.isFile()&&(0,l.gte)(r.size,t)&&(0,v.isStatRX)(r,e)}function E(){if(y.isWin){const e=(0,a.toNotBlank)((0,g.getEnv)("SystemRoot"))??"C:\\Windows",t=(0,a.toNotBlank)((0,g.getEnv)("SystemDrive"))??"C:",r=(0,a.toNotBlank)((0,g.getEnv)("ProgramData"))??"C:\\ProgramData";return[e,n.default.join(e,"System32"),n.default.join(e,"System32","Wbem"),n.default.join(r,"chocolatey","bin"),n.default.join(t,"cygwin64","bin")]}return[...(0,p.isDocker)()?["/opt/photostructure/bin","/opt/photostructure/tools/bin"]:[],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}function M(){const e=(0,h.toS)((0,m.env)().PATH).split(n.default.delimiter);return(0,o.uniq)((0,o.compactBlanks)([...e,...E()]))}t.isRXFile=_,t.pathTo=async function({tool:e,alternativePath:t,paths:r}){const i=(0,o.uniq)((0,o.compactBlanks)([...M(),...(0,d.toA)(r)]));for(const r of(0,o.uniq)((0,o.compactBlanks)([e,t]))){const e=y.isWin?(0,u.ensureSuffix)(r,".exe"):r;for(const t of i){const r=n.default.join(t,e);if(await _(r))return y.isLinux?r:(0,w.actualPath)(r)}}b().warn("Failed to find tool",{tool:e,dirs:i})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>P&&(0,v.isStatRX)(t,e.nativePath)?e.nativePath:void 0},t.wmic=()=>"wmic",t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},78133:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.native2posix=t.posix2native=void 0;const n=i(r(76760)),s=r(22573),o=r(81168);t.posix2native=function(e,t){if((0,s.blank)(e))return e;if(n.default.sep===n.default.posix.sep)return e;const r=(0,s.notBlank)(t)?n.default.sep+n.default.sep+t+n.default.sep:"",i=e.split(n.default.posix.sep);return(0,o.equalsIgnoreCase)(i[0],t)&&i.unshift(),r+i.join(n.default.sep)},t.native2posix=function(e){return(0,s.blank)(e)||n.default.sep===n.default.posix.sep||n.default.posix.sep===n.default.sep?e:e.split(n.default.sep).join(n.default.posix.sep)}},43899:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectPath=void 0;const n=i(r(76760)),s=i(r(1708)),o=r(19851),a=r(40958),l=r(48884),u=r(50213),c=r(45969),d=r(29325),h=r(43334),f=r(65843),m=r(25675),g=r(53265);function p(...e){return(0,o.lazy)((()=>n.default.join(t.ProjectPath.Root(),...e)))}t.ProjectPath={Root:(0,o.lazy)((()=>{const e=["data","public","views"],t=[];(0,c.isDocker)()&&t.push("/opt/photostructure"),h.isElectron&&t.push(n.default.join((0,g.execDir)(),"resources"),n.default.join((0,g.execDir)(),"..","Resources")),t.push(...(0,a.compactBlanks)([(0,g.execDir)(),s.default.cwd(),__dirname])),(0,l.uniqInPlace)(t);for(const r of t){if((0,f.hasChildrenSync)(r,e))return r;for(const t of(0,f.ancestors)(r).slice(0,(0,d.isPacked)()?4:6)){if((0,f.hasChildrenSync)(t,e))return t;const i=n.default.join(r,"node_modules","photostructure");if((0,f.hasChildrenSync)(i,e))return i}}return(0,u.mkLogger)("fs.ProjectPath").throw("Failed to find project root. Looked in "+t)})),Bin:p("bin"),Data:p("data"),ICC:p("data","icc"),Migrations:p("data","migrations"),Public:p("public"),Tools:p("tools"),Views:p("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectPath.Root())}}},45879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.intFromFileSync=t.readFileMaybe=void 0;const i=r(44652),n=r(19851),s=r(31586),o=r(50213),a=r(57902),l=r(69428),u=(0,n.lazy)((()=>(0,o.mkLogger)("fs.ReadFile")));t.readFileMaybe=async function(e,t=a.LogLevels.info){try{return await(0,i.readFile)(e)}catch(r){return void u().log(t,".readFileMaybe("+e+")",r)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,s.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})}},93854:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=void 0;const i=r(44652),n=r(97352);t.readFilePart_=async function({nativePath:e,position:t=0,length:r}){let s=-1;try{const n=r??(await(0,i.stat)(e)).size-t,o=Buffer.alloc(n);return s=await(0,i.open)(e,"r"),await(0,i.read)(s,o,0,n,t)}finally{(0,n.mapGte0)(s,i.close)}}},69428:function(e,t,r){var i=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=void 0;const o=s(r(73024));t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}}},32323:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const i=r(57075);class n extends i.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=n},65238:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readdirUncached_=t.readdirCached=t.readdir_=t.readdir=t.childDirectories_=t.isCachedDir=t.setSlowDir=t.isSlowDir=t.slowDirs=t.clearCachedReaddir=t.clearReaddirCaches=t.readdirCacheDir=t.ReadDirCacheName=void 0;const n=i(r(51455)),s=r(76760),o=r(19851),a=r(76790),l=r(22573),u=r(42659),c=r(41400),d=r(31586),h=r(13538),f=r(83104),m=r(54127),g=r(50213),p=r(95937),y=r(34102),v=r(28874),w=r(63870),S=r(88561),b=r(41080);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,o.lazy)((()=>(0,s.join)(v.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName)));const P=(0,o.lazy)((()=>(0,g.mkLogger)("fs.Readdir")));async function _(){try{await n.default.rm((0,t.readdirCacheDir)(),{force:!0,recursive:!0})}catch(e){P().warn("clearReaddirCaches(): failed",{error:e})}}t.clearReaddirCaches=_;const E=(0,o.lazy)((()=>new S.FileCache({name:"fs.readdir",maxSize:256,timeoutMs:(0,w.commandTimeoutMs)(),clearEveryMs:u.minuteMs})));function M(e){(0,l.blank)(e)||E.prior()?.delete(e)}async function C(e){return P().tap({level:"trace",msg:"readdir_("+e+")",result:await E().getOrSetAsync(e,(()=>async function(e){const r=Date.now()+2*(0,b.statTimeoutMs)(),i=T(e),n=await(0,h.thenOrTimeout)(i,(0,d.toGt0)(v.Settings.fsCacheSlowMs.valueOrDefault)??(0,b.statTimeoutMs)());if(n===f.Timeout&&(0,p.onTimeout)({soft:!1}),n!==f.Timeout&&n.length({basename:e.name,isFile:e.isFile(),isDirectory:e.isDirectory()}))),(e=>[e.isFile,e.basename.toLowerCase(),e.basename]))}t.clearCachedReaddir=M,(0,c.later)((()=>{v.Settings.cacheDir.watchLater((()=>{t.readdirCacheDir.clear(),E.prior()?.clear(),t.slowDirs.prior()?.clear()})),(0,y.ee)().on("clearCache",(()=>(t.slowDirs.prior()?.clear(),_()))),(0,y.ee)().on("fileChanged",(e=>(0,l.blank)(e)?_():M(e)))})),t.slowDirs=(0,o.lazy)((()=>new m.FifoSet(256))),t.isSlowDir=async function(e){return!((0,l.blank)(e)||!(0,t.slowDirs)().has(e)&&(!E().has(e)||((0,t.slowDirs)().add(e),0)))},t.setSlowDir=function(e){M(e),(0,t.slowDirs)().add(e)},t.isCachedDir=async function(e){return null!=E().get(e)},t.childDirectories_=async function(e){return(await C(e)).filter((e=>e.isDirectory)).map((t=>(0,s.join)(e,t.basename)))},t.readdir=async function(e){try{return(0,d.gt0)(v.Settings.readdirCacheMs.valueOrDefault)?C(e):T(e)}catch(t){return void P().warn("readdir() failed for "+e,t)}},t.readdir_=C,t.readdirCached=function(e){return E().get(e)},t.readdirUncached_=T},53265:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolveRelativeMaybe=t.currentWorkingDirectories=t.execDir=t.resolve=void 0;const n=r(73024),s=i(r(76760)),o=r(40958),a=r(22573),l=r(45599),u=r(50213),c=r(43334),d=r(5545),h=(0,l.defer)((()=>(0,u.mkLogger)("fs.Resolve"))),f=c.isWin?/[\\/]/:/\//;function m(){return(0,o.compactBlanks)([(0,t.execDir)(),process.cwd(),__dirname])}function g(...e){for(const t of m()){const r=s.default.resolve(t,...e);if((0,n.existsSync)(r))return r}h().warn("resolveRelative: failed to find a working cwd",{input:e,cwds:m()})}t.resolve=function(...e){if((0,a.blank)(e.join("")))throw new Error("resolve(): empty paths");if(c.isWin)if(1===e.length&&/^[a-z]:$/i.test(e[0]))e[0]+="\\";else{const t=/^\/(?[a-z])\/(?.*)$/i.exec(e[0])?.groups;null!=t&&(e[0]=t.drive.toUpperCase()+":\\"+t.path.replace(/\//g,"\\"))}const t=e[0].split(f).slice(0,2).find(a.notBlank);return(0,d.upcaseDriveLetters)(([".",".."].includes(t)?g(...e):void 0)??s.default.resolve(...e))},t.execDir=(0,l.defer)((()=>s.default.dirname(process.execPath))),t.currentWorkingDirectories=m,t.resolveRelativeMaybe=g},50274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const i=r(50989);t.SidecarExts=(0,i.strEnum)("xmp","mie","exv")},14427:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=void 0;const i=r(22573),n=r(38639);t.isSimpleDirent=function(e){return null!=e&&(0,i.notBlank)(e.basename)&&(0,n.isBoolean)(e.isFile)&&(0,n.isBoolean)(e.isDirectory)}},17217:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.firstSelfOrAncestor=t.someSelfOrAncestor=t.isFileSync=t.findFileIndex=t.rootDir=t.dirname=t.nameWithoutExt=t.basename=t.toNativePath_=t.toNativePath=t.isSimpleFile=void 0;const n=i(r(73024)),s=i(r(76760)),o=r(22573),a=r(98553),l=r(81168),u=r(43334),c=r(29882),d=r(53265),h=r(14427);function f(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function m(e){if(null==e)throw new Error("toNativePath(null)");if((0,o.blank)(e))throw new Error("toNativePath(blank)");if((0,l.isString)(e))return(0,d.resolve)(e);if((0,o.blank)(e.nativePath))throw new Error(`toNativePath(${(0,a.stringify)(e)})`);return e.nativePath}function g(e){return e instanceof n.default.Dirent?e.name:f(e)?e.base:s.default.basename(String(e))}t.isSimpleFile=f,t.toNativePath=function(e){try{return m(e)}catch{return}},t.toNativePath_=m,t.basename=g,t.nameWithoutExt=function(e){return(0,c.parseNativePath)(g(e)).name},t.dirname=function(e){return f(e)?e.dir:s.default.dirname(m(e))};const p=/^[a-z]:$/i;t.rootDir=function(e){if(f(e)){const t=e.pathnames;return u.isWin&&null!=t[0].match(p)?t[1]:t[0]}{const t=(0,l.stripPrefix)(e,"/"),r=t.indexOf(s.default.sep);return r>0?t.slice(1,r):void 0}},t.findFileIndex=function(e,t){for(let r=0;r(0,d.mkLogger)("fs.Stat")));async function v(e){return(0,a.blank)(e)?y().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):await(0,c.thenOrTimeoutError)(n.default.stat(e),(0,p.statTimeoutMs)(),!0)}function w(e,t=f.LogLevels.debug){return(0,a.blank)(e)?void 0:v(e).catch((r=>{y().log(t,"stat() failed",{error:r,nativePath:e})}))}function S(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function b(e){return(0,l.isDate)(e)?(0,l.unixtime)(e):(0,u.isNumber)(e)?e:void 0}function P(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const r=S(e),i=S(t);if(r!==i)return"inconsistent file type: "+r+" ≠ "+i;for(const r of["size","mtime"]){const i=e[r],n=t[r],s=(0,u.diff)(b(i),b(n));if(null==s||s>1)return"unmatched "+r+": "+i+" ≠ "+n}}t.stat_=v,t.statMaybe=w,t.statToType=S,t.whyStatNotEql=P,t.statEql=function(e,t){return null==P(e,t)},t.exists=async function(e,t=f.LogLevels.info){return null!=await w(e,t)},t.isEmptyFile=async function(e,t){const r=await w(e,t?.logLevel??f.LogLevels.trace);return!(null!=r&&!(t?.emptyIsNew??1))&&(0,g.isEmptyStats)(r)},t.isNonEmptyFile=async function(e,t=0){const r=await w(e);return null!=r&&r.isFile()&&r.size>=t},t.nativePathIsFile=async function(e,t=f.LogLevels.info){return!0===(await w(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await w(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.access)({stat:r,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=f.LogLevels.trace){const r=await w(e,t);return null!=r&&r.isDirectory()&&(0,m.isStatRWX)(r,e)},t.isMtimeRecent=async function(e,t){return(0,h.isRecentMs)((await w(e))?.mtimeMs,t)},t.statTimes=function(e){return(0,o.uniq)([e.birthtimeMs,e.mtimeMs].filter((e=>null!=e&&0!==e)))}},68284:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDirectorySync=t.isNonEmptyFileSync=t.isEmptyFileSync=t.isFileSync=t.isEmptyStats=t.statSync=void 0;const n=i(r(73024)),s=r(22573);function o(e){try{return(0,s.blank)(e)?void 0:n.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function a(e){return null==e||e.isFile()&&0===e.size}t.statSync=o,t.isEmptyStats=a,t.isFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const r=o(e);return t.emptyIsNew?null==r:a(r)},t.isNonEmptyFileSync=function(e,t=0){const r=o(e);return null!=r&&r.isFile()&&r.size>=t},t.isDirectorySync=function(e){return!0===o(e)?.isDirectory()}},41080:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=void 0;const i=r(28874);t.statTimeoutMs=function(){return i.Settings.statTimeoutMs.valueOrDefault}},66003:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Chunker=t.onDataChunked=void 0;const i=r(22573),n=r(56409);t.onDataChunked=function(e,t,r){const i=new s(t,r,!0);return i.read(e),i.done};class s{constructor(e,t,r=!0){this.sep=e,this.onData=t,this.filterBlanks=r,this.incompleteChunk="",this.done=new n.Latch}onChunk(e){if(null==e)return;const t=(this.incompleteChunk+e.toString()).split(this.sep);this.incompleteChunk=t.pop(),t.forEach((e=>{this.filterBlanks&&!(0,i.notBlank)(e)||this.onData(e)}))}clear(){this.onChunk(""),(0,i.notBlank)(this.incompleteChunk)&&this.onData(this.incompleteChunk),this.incompleteChunk=""}read(e){return e.on("data",(e=>this.onChunk(e))),e.on("end",(()=>{this.clear(),this.done.resolve()})),this}}t.Chunker=s},95705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=void 0,t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},36868:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ByteCounter=t.remoteDesc=t.closeStreams=t.onChildError=t.closeStream=t.endStream=t.writeAsync=t.PassthroughStream=void 0;const n=i(r(57075)),s=r(41400),o=r(55835),a=r(68708),l=r(42279),u=r(99331),c=r(70025);class d extends n.default.Duplex{_write(e,t){this.push(e,t)}}t.PassthroughStream=d,t.writeAsync=async function(e,t){return new Promise(((r,i)=>{!1===e.write(t,(e=>{e&&i(e)}))?e.once("drain",r):r()}))},t.endStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}(0,u.ending)()?e.end(null):await new Promise((t=>e.end(null,t))),await(0,s.delay)(50);try{(0,a.maybeCall)(e,"destroy")}catch{}}},t.closeStream=async function(e){if(null!=e){try{(0,a.maybeCall)(e,"unref")}catch{}if((0,u.ending)())try{e.close(l.NoOp)}catch{}else await new Promise((t=>e.close(t)))}},t.onChildError=function(e,t){for(const{name:r,ea:i}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,o.map)(i,(e=>e.on("error",(e=>{!1===(0,c.isIgnorableError)(e)&&t(r,e)}))))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`};class h extends n.default.Transform{constructor(e){super({transform:(e,t,r)=>{this.onProgress(this.bytes+=e.length),r(e)}}),this.onProgress=e,this.bytes=0}}t.ByteCounter=h},66430:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posixPathExistsSync=t.firstExistingDirectory=t.isReadWriteableDirectorySync=t.isReadableDirectorySync=t.isMtimeRecentSync=t.nativePathSizeSync=t.nativePathExistsSync=void 0;const n=i(r(73024)),s=r(76760),o=r(22573),a=r(76596),l=r(64660),u=r(78133),c=r(68284);function d(e){if((0,o.blank)(e))return!1;try{return n.default.existsSync(e)}catch{return!1}}t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,a.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,o.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,o.notBlank)(t)){const e=(0,s.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,o.blank)(e)&&d((0,u.posix2native)(e))}},27794:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=void 0;const n=i(r(44652)),s=r(19851),o=r(22573),a=r(42659),l=r(31586),u=r(68708),c=r(13538),d=r(29882),h=r(17217),f=r(16287),m=r(41080);function g(e){return null==e?void 0:(0,a.isDate)(e)?e.getTime():(0,l.gt0)(e)?e:void 0}t.touch_=async function e(t){const r=t.ensureFile??!0;if(null==t.file||(0,o.blank)(t.file))throw new Error("can't touch blank path");const i=(0,h.toNativePath_)(t.file);r&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const a=(0,s.lazy)((()=>(0,f.statMaybe)(t.reference?.nativePath))),l=Math.round(g(t.mtimeMs)??(await a())?.mtimeMs??Date.now()),p=Math.round(g(t.atimeMs)??(await a())?.atimeMs??l);try{await(0,c.thenOrTimeoutError)(n.default.utimes(i,new Date(p),new Date(l)),(0,m.statTimeoutMs)())}catch(s){if(!r||"ENOENT"!==s.code)throw s;await(0,c.thenOrTimeoutError)(n.default.ensureFile(i),(0,m.statTimeoutMs)()),(0,u.keys)(t).length>1&&await e({...t,ensureFile:!1})}}},5545:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.upcaseDriveLetters=t.driveRe=void 0;const n=i(r(76760)),s=r(54993);t.driveRe=/^(?[A-Z]:)(?[\\/].*)?$/i,t.upcaseDriveLetters=function(e){const r=t.driveRe.exec(e)?.groups;return null==r?e:r.drive.toUpperCase()+(0,s.toS)(r.path??n.default.sep)}},58722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const i=r(57075),n=r(22911);class s extends i.Writable{constructor(e){super(e),this.deferred=new n.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",(()=>{this.deferred.resolve(this.data)})),this.on("error",(e=>{this.deferred.reject(e)}))}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_write(e,t,r){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),r()}}t.WritableToBuffer=s},73428:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeTextSync_=t.writeFileSync_=t.writeTextfile_=t.writeText_=t.writeFile_=void 0;const n=i(r(44652)),s=i(r(76760)),o=r(51926),a=r(54993),l=r(34102),u=r(84542),c=r(29882);async function d(e,t){const r=s.default.dirname(e);await(0,c.mkdirp_)(r),await n.default.writeFile(e,t),(0,l.ee)().emit("fileChanged",r)}function h(e,t){const r=s.default.dirname(e);(0,c.mkdirpSync_)(r),n.default.writeFileSync(e,t),(0,l.ee)().emit("fileChanged",r)}t.writeFile_=d,t.writeText_=async function(e,...t){return d(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const r=(0,u.crlf)(...(0,o.wrap)(t));await d(e,r)},t.writeFileSync_=h,t.writeTextSync_=function(e,...t){return h(e,(0,u.crlf)((0,o.ensureSuffix)(t.map(a.toS).join("\n"),"\n")))}},13047:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.outputJsonGz=t.outputJsonGz_=t.readJsonGz=t.readJsonGz_=t.zCopyToBuffer_=t.zpipe_=t.zcat=t.zcat_=void 0;const n=i(r(73024)),s=r(76760),o=r(46466),a=r(38522),l=r(19851),u=r(40958),c=r(98553),d=r(80875),h=r(50213),f=r(57159),m=r(29882),g=r(57902),p=r(32323),y=r(58722),v=(0,l.lazy)((()=>(0,h.mkLogger)("fs.zcat")));async function w(e,t){return(await b(e,t)).toString()}async function S(e,t,r){const i=[],s=[n.default.createReadStream(e,{autoClose:!0,...r}).on("error",(e=>i.push(e)))];if(e.toLowerCase().endsWith(".gz")?s.push((0,a.createGunzip)().on("error",(e=>i.push(e)))):e.toLowerCase().endsWith(".br")&&s.push((0,a.createBrotliDecompress)().on("error",(e=>i.push(e)))),s.push(t),await(0,o.pipeline)(s),(0,u.isNotEmpty)(i))throw new f.WrappedError("zPipe("+e+") failed",{causes:i,path:e})}async function b(e,t){const r=new y.WritableToBuffer;return await S(e,r,t),await r.buffer}async function P(e){return(0,d.parseJSON)(await b(e))}async function _(e,t){const r=(0,c.stringify)(t);await(0,m.mkdirp_)((0,s.parse)(e).dir),await(0,o.pipeline)(new p.ReadableBuffer(r),(0,a.createGzip)(),n.default.createWriteStream(e,{autoClose:!0}))}t.zcat_=w,t.zcat=async function(e,t){try{return w(e,t)}catch(t){return void v().warn("zcat failed to read "+e,t)}},t.zpipe_=S,t.zCopyToBuffer_=b,t.readJsonGz_=P,t.readJsonGz=async function(e,t=g.LogLevels.warn){try{return await P(e)}catch(r){return void v().log(t,"readJsonGz("+e+"): failed",r)}},t.outputJsonGz_=_,t.outputJsonGz=async function(e,t,r=g.LogLevels.warn){try{await _(e,t)}catch(t){v().log(r,"outputJsonGz("+e+"): failed",t)}}},33866:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const i=r(50989);t.HealthCheckIds=(0,i.strEnum)("library-db","library-directories","library-free-space","library-nothing-to-sync","ps-version","media-directories","nodejs-version","proc-memory-use","proc-not-in-dmg","proc-not-superuser","settings-env","settings-library","settings-system","sync-paused","system-load","system-version","system-volumes","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-video","volume-uuids")},52086:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const i=r(50989);t.CropStrategies=(0,i.strEnum)("center","entropy","attention")},48584:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const i=r(50989);t.SharpFailOns=(0,i.strEnum)("none","truncated","error","warning")},32105:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const i=r(19851),n=r(23560),s=r(66184),o=r(72210);class a{log(e,t,r,i){this.enabled(e,t)&&(0,o.pushLogEntries)({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:r,meta:i})}enabled(e,t){return(0,s.logFilter)().enabled(e,t)}async flush(){}toJSON(){return{_ctor:"ConsoleLogger"}}}t.ConsoleLogger=a,a.instance=(0,i.lazy)((()=>new a))},14593:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const i=r(57975),n=r(22573),s=r(26905),o=r(55835),a=r(68708),l=r(13538),u=r(50213),c=r(97352),d=r(45255),h=r(76740),f=r(57159),m=r(57902),g=/logger|lazy/i;class p{constructor(e,t=u.rootLoggers){this.loggers=t,this.abortable=new h.Abortable,this.context=(0,n.toNotBlank)(e)??(0,s.shortStack)().find((e=>!g.test(e)))??""}toLogJSON(){return"CtxLogger("+this.context+")"}[i.inspect.custom](){return this.toLogJSON()}addContext(e){return new p(this.context+e,this.loggers)}addParameterContext(e){return new p(this.context+"("+e+")",this.loggers)}throwIfAborted_(e){try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log("warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log("warn","awaitOrAbort()",{error:e}),e}}throw(e,t){const r=(0,f.toWrappedError)(e,{message:this.context,error:t?.error,meta:(0,a.omit)(t,"error")});throw Error.captureStackTrace?.(r),this.log(!0===r.ignorable?"warn":"error",".throw() "+r.message,{stack:r.stack,...t}),r}tap(e){const t=e.level??(0,c.mapGt0)(e.meta?.elapsedMs,m.msTolevel)??m.LogLevels.debug;return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=Date.now();let r;try{r=setTimeout((()=>this.log("warn","slow: "+e.msg)),d.ShortCommandTimeoutMs);const i=e.result(),n=Date.now()-t;return this.tap({level:e.level,msg:e.msg,result:i,meta:{...e.meta,elapsedMs:n}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,o.map)(r,clearTimeout)}}async tapAsync_(e){try{return this.tap({...e,result:await(0,l.thenOrTimeoutError)(e.result,e.timeoutMs)})}catch(t){return this.throw(t,(0,a.pick)(e,"errorMsg","msg","timeoutMs","meta"))}}enabled(e,t){for(const r of this.loggers())if(r.enabled(e,t??this.context))return!0;return!1}log(e,t,r){for(const i of this.loggers())i.log(e,this.context,t,r)}elapsed(e,t,r){this.log((0,m.msTolevel)(t),e,{elapsedMs:t,...r})}async flush(){for(const e of this.loggers())await e.flush()}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}}t.ContextualLogger=p},28981:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const i=r(19851),n=r(51879);t.DefaultLogFormatter=(0,i.lazy)((()=>new n.PlaintextLogFormatter))},20839:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},4904:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sortLogEntriesInPlace=t.logEntrySorter=t.isLogEntry=void 0;const i=r(76790),n=r(31586),s=r(51926),o=r(57902);t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,s.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,i.sortByInPlace)(e,(e=>e.ts))}},66184:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isLogged=t.ifLog=t.silentlyAsync=t.silently=t.isDefaultLogLevelAtLeast=t.defaultLogLevel=t.logFilter=t.LogLevelRe=t.SimpleLogFilter=void 0;const i=r(19851),n=r(57902);class s{constructor(e){this.minLogLevel=e,this.silent=!1,this.defaultLevelIndex=(0,n.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,n.levelIndex)(e)<=this.defaultLevelIndex}}t.SimpleLogFilter=s,t.LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,t.logFilter=(0,i.lazy)((()=>new s(n.LogLevels.warn))),t.defaultLogLevel=(0,i.lazy)((()=>n.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])),t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,n.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,r){return(0,t.logFilter)().enabled(e)?r():void 0},t.isLogged=function(e,r){return(0,t.logFilter)().enabled(e,r)}},57902:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.msTolevel=t.level2syslog=t.levelGte=t.levelIndex=t.LogLevels=void 0;const i=r(31586),n=r(50989),s=r(28874);t.LogLevels=(0,n.strEnum)("fatal","error","warn","info","debug","trace");const o=t.LogLevels.indexOf("trace");t.levelIndex=function(e){return t.LogLevels.indexOf(e)??t.LogLevels.indexOf(e.trim().toLowerCase())??o},t.levelGte=function(e,r){return(0,i.gte)(t.LogLevels.indexOf(e),t.LogLevels.indexOf(r))};const a=new Map([[t.LogLevels.fatal,1],[t.LogLevels.error,3],[t.LogLevels.warn,4],[t.LogLevels.info,6],[t.LogLevels.debug,7]]);t.level2syslog=function(e){return a.get(e)},t.msTolevel=function(e,t=s.Settings.statTimeoutMs.valueOrDefault){return e>=.75*t?"error":e>=.5*t?"warn":e>=.25*t?"info":"debug"}},72210:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popExpiredLogEntries=t.pushLogEntries=t.logEntries=t.setLogTailEnabled=t.logTailEnabled=void 0;const i=r(92322),n=r(82328),s=r(28981),o=r(20839),a=r(4904);let l=!1;t.logTailEnabled=function(){return l},t.setLogTailEnabled=function(e){l=e},t.logEntries=new i.SortedSet(a.logEntrySorter),t.pushLogEntries=function(...e){for(const r of e)l?t.logEntries.add(r):(0,n.stdoutEnded)()||console.log((0,s.DefaultLogFormatter)().formatLogEntry(r))},t.popExpiredLogEntries=function(e=2*o.DefaultLogFlushMs){return t.logEntries.shiftLte(Date.now()-e)}},51879:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const i=r(57975),n=r(40958),s=r(55835),o=r(68708),a=r(54993),l=r(23560),u=r(81168),c=r(57902);t.PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e,this.paddedLogLevels=(0,o.fromEntries)(c.LogLevels.values.map((e=>[e,(0,u.rightPad)(e,5," ")])))}formatLogEntry(e){return(0,n.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,s.map)(e.meta,(e=>(0,i.inspect)(e,this.inspectOptions)))]).map((e=>(0,a.toS)(e))).join(" ")}format(e,t,r,i){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:r,meta:i})}}},82647:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Average=t.averageStats=t.p84=void 0;const o=r(57975),a=r(40958),l=r(96249),u=r(55835),c=r(31586),d=r(68708),h=r(59455),f=r(48884),m=r(89788),g=r(22454),p=r(70417);t.p84=function(e){return null!=e&&(0,c.isNumber)(e.mean)&&(0,c.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new y).pushAll(e).stats()};class y{static merge(e,t){if(0===e.n&&0===t.n)return new y(Math.max(e.maxSamples,t.maxSamples));if(0===e.n)return t.clone();if(0===t.n)return e.clone();if(e.n<=e.maxSamples){const r=t.clone();return r.pushAll(e.samples),r}if(t.n<=t.maxSamples){const r=e.clone();return r.pushAll(t.samples),r}{const r=new y(Math.max(e.maxSamples,t.maxSamples));r._n=e.n+t.n,r._min=Math.min(e._min,t._min),r._max=Math.max(e._max,t._max),r._m=e._m*e.n/r.n+t._m*t.n/r.n,r._s=e._s*e.n/r.n+t._s*t.n/r.n;const i=(0,l.flatten)((0,f.zip)(e.samples,t.samples));return r._samples.push(...i),r._weightedTotalAvg=(0,p.weightedAvg)([r._m,...i]),r}}constructor(e=20){i.add(this),this.maxSamples=e,this._n=0,this._samples=new m.BoundedList(e)}[(i=new WeakSet,o.inspect.custom)](){return this.stats()}toJSON(){return{_ctor:"Average",n:this._n,_m:this._m,_s:this._s,min:this._min,max:this._max,samples:this._samples.toA()}}static fromJSON(e){return(new y).with(e)}with(e){this._n=e.n,this._min=e.min,this._max=e.max,this._m=e._m,this._s=e._s,this._samples.push(...(0,h.toA)(e.samples))}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());this._min=(0,p.min)([this._min,e.min]),this._max=(0,p.max)([this._max,e.max]);const t=this.n+e.n;return this._m=this._m*this.n/t+e._m*e.n/t,this._s=this._s*this.n/t+e._s*e.n/t,this._n+=e._n,this._samples.push(...(0,h.toA)(e.samples)),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._weightedTotalAvg)this._m=e,this._s=0,this._weightedTotalAvg=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._weightedTotalAvg=(this._weightedTotalAvg+e)/2}return e}clone(){return(0,d.tap)(new y(this.maxSamples),(e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._weightedTotalAvg=this._weightedTotalAvg,e._samples.push(...this._samples)}))}pushAll(e){if(null!=e)for(const t of e)(0,c.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,u.map)(t,(t=>t>100?Math.round(t):(0,c.sigFigs)(t,e))),r={};return r.k=t(this.n),this.empty||(r.mean=t(this.avg),r.sum=t(this.sum),r.sd=t(this.stdDev),r.max=t(this.max),r.min=t(this.min)),r}get empty(){return 0===this._n}get n(){return this._n}get avg(){return this.empty?void 0:(0,c.sigFigs)(this._m,4)}get sum(){return this._n>0?this._m*this._n:0}get max(){return this._max}get min(){return this._min}get last(){return this._samples.last}get p16(){return s(this,i,"m",n).call(this,-1)}get p29(){return s(this,i,"m",n).call(this,-.5)}get p38(){return s(this,i,"m",n).call(this,-.25)}get p69(){return s(this,i,"m",n).call(this,.5)}get p84(){return s(this,i,"m",n).call(this,1)}get p98(){return s(this,i,"m",n).call(this,2)}get p99(){return s(this,i,"m",n).call(this,3)}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new g.CountingSet;return this._samples.forEach((e=>t.incr(e))),t.topKeys(e)}get sampleVariance(){return(0,a.mapNotEmpty)(this._samples,p.variance)}get sampleStdDev(){return(0,a.mapNotEmpty)(this._samples,p.stdDev)}get sampleAvg(){return(0,a.mapNotEmpty)(this._samples,p.avg)}get sampleSlope(){return(0,p.slope)(this._samples)??0}get samples(){return[...this._samples]}get weightedSampleAvg(){return(0,u.map)((0,p.weightedAvg)(this._samples),(e=>(0,c.sigFigs)(e,4)))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._n=0,this._m=void 0,this._s=void 0,this._weightedTotalAvg=0,this._samples.length=0}}t.Average=y,n=function(e){return null==this._m||null==this._s?void 0:(0,c.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}},20014:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bits=t.pop=t.bitsSetBig=t.bitUnzip=t.bitZip=t.isBitSet=t.BitZip=t.diffConcattedBits=t.splitBits=t.concatBits=void 0;const i=r(40958),n=r(55835),s=r(31586),o=r(30976),a=r(48884),l=r(70417);function u(e,t){const r=Math.pow(2,t),i=[];for(;e>0;)i.unshift(e%r),e=Math.floor(e/r);return i}t.concatBits=function(e,t){const r=Math.pow(2,t);return e.reduce(((e,t)=>e*r+(0,s.clamp)(0,r,(0,s.toInt)(t,{defaultValue:0}))),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,r){return(0,n.map2)(e,t,((e,t)=>(0,i.sum)((0,a.zip)(u(e,r),u(t,r)),(([e,t])=>(0,s.absdiff)(e,t)))))},t.BitZip=class{constructor(e){this.dims=e}clampValue(e){return e.map(((e,t)=>(0,s.clamp)(this.dims[t].min,this.dims[t].max,e)))}randomValue(){return this.dims.map((e=>(0,o.randomInt)(e.min,e.max)))}zipMin(e){return this.zip(this.dims.map((e=>e.min)),e)}zipMax(e){return this.zip(this.dims.map((e=>e.max)),e)}zip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max)),n=this.clampValue(e);let s=0;for(let e=0;eo?(s+=1,r[t]=o):i[t]=o}return s}unzip(e,t){const r=this.dims.map((e=>e.min)),i=this.dims.map((e=>e.max));for(let n=0;n(r[e]+i[e])/2))}};const c=Math.pow(2,32)-1;function d(e,t,r){return!0!==r&&e>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map(((e,t)=>"1"===e?t:-1)).filter((e=>-1!==e))}t.isBitSet=d,t.bitZip=function(e){e.dims.forEach((e=>e.value=(0,s.clamp)(e.min,e.max,e.value)));let t=0;for(let r=0;rs?(t+=1,n.min=s):n.max=s}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const r=h(e);for(let e=0;e(0,l.avg)([e.min,e.max])))},t.bitsSetBig=h,t.pop=function(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,63&(e+=e>>8)+(e>>16)},t.bits=function(e,t){return(0,i.sum)(e,((r,i)=>t(r,i)?Math.pow(2,e.length-i-1):0))}},55222:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.RadixAlphaNum=t.Base64=t.Radix58=t.Hex=t.Radix=t.encodeDigits=void 0;const i=r(77598),n=r(22573),s=r(55835),o=r(32639),a=r(88158),l=r(81168),u=BigInt(0);function c(e,t,r=0){if(!isFinite(t)||e<=1)return[];const i=[];if(0===t)i.unshift(0);else for(;t>0;)i.unshift(t%e),t=Math.floor(t/e);for(;i.lengththis.numerals[e])).join("")}encode(e,t=0){if(!isFinite(e))return"";const r=e<0;return r&&(e=Math.abs(e),t--),(r?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],r=BigInt(this.base);let i=e;for(;i>u;)t.push(Number(i%r)),i/=r;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let r of e)for(t.forEach(((e,i)=>{r+=e<<8,t[i]=r%this.base,r=Math.floor(r/this.base)}));r>0;)t.push(r%this.base),r=Math.floor(r/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,s.map)(this.decodeBigInt(e),(t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)}))}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,n.blank)(e))return;const t="-"===(e=(0,o.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const r=BigInt(this.base);let i=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;i=i*r+BigInt(e)}return t?BigInt(-1)*i:i}randomChars(e){return this.encodeBuffer((0,i.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,r="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(r)}tokenEql(e,t,r){const i=this.normalizeToken(e),n=this.normalizeToken(t);return i.length>=r&&i===n}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter((e=>this.numerals.includes(e))).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",(e=>e.toLowerCase())),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.RadixAlphaNum=new d("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",(e=>e.toLowerCase())),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",(e=>e.toLowerCase())),t.TokenRadix=new d("TokenRadix","0123456789abcdefhjkmnpqrtuvwxy",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",(e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g"))),t.NumericRadix=new d("NumericRadix","0123456789",(e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9")))},976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rateStats=void 0;const i=r(31586);t.rateStats=function(e){return{eventCount:e?.eventCount,eventsPerSecond:(0,i.sigFigs)(e?.eventsPerSecond,2),msSinceLastEvent:e?.msSinceLastEvent}}},70417:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},o=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r};Object.defineProperty(t,"__esModule",{value:!0}),t.jaccard=t.cosineSimilarity=t.dot=t.l2norm=t.centroid=t.weightedAvg=t.p84=t.stdDev=t.variance=t.slope=t.normalize=t.avg=t.Mean=t.sumf=t.sum=t.mode=t.modes=t.deltas=t.max=t.min=void 0;const a=r(40958),l=r(55835),u=r(31586),c=r(59455),d=r(22454),h=r(77377),f=r(82647);function m(e){let t;for(const r of e)null!=r&&(null==t||rt)&&(t=r);return t}function y(e,t){const r=new d.CountingSet;for(const t of e)(0,u.isNumber)(t)&&r.incr(t);return r.topKeys(t)}function v(e,t){let r=0,i=0;for(const n of e){if(null!=n){const e=t(n,r);(0,u.isNumber)(e)&&(i+=e)}r++}return i}t.min=m,t.max=p,t.deltas=function(e){const t=(0,c.toA)(e);return null==e||t.length<=1?[]:t.slice(1).map(((e,r)=>e-t[r]))},t.modes=y,t.mode=function(e){return y(e,1)[0]},t.sum=function(e){let t=0;for(const r of e)(0,u.isNumber)(r)&&(t+=r);return t},t.sumf=v;class w{constructor(){i.set(this,0),n.set(this,void 0)}push(e){var t;(0,u.isNumber)(e)&&(o(this,n,null==s(this,n,"f")?e:s(this,n,"f")*s(this,i,"f")/(s(this,i,"f")+1)+e/(s(this,i,"f")+1),"f"),o(this,i,(t=s(this,i,"f"),++t),"f"))}get mean(){return s(this,n,"f")}}function S(e){const t=new w;for(const r of e)t.push(r);return t.mean}function b(e){const t=S(e);if(null==t)return;let r=0,i=0;for(const n of e)(0,u.isNumber)(n)&&(i++,r+=(n-t)*(n-t));return r/i}function P(e){let t=0;for(const r of e)t+=r*r;return Math.sqrt(t)}function _(e,t){let r=0;for(let i=0;i(1-t)*e+t*(r+o*(e-n)/s)))},t.slope=function(e){const t=(0,c.toA)(e).filter(u.isNumber),r=S(t);if(null!=r){const e=(t.length-1)/2,i=v(t,((t,i)=>(t-r)*(i-e))),n=v(t,(e=>(e-r)**2));return 0===n?0:i/n}},t.variance=b,t.stdDev=function(e){return(0,l.map)(b(e),Math.sqrt)},t.p84=function(e){return(new f.Average).pushAll(e).p84},t.weightedAvg=function(e,t=.5){let r;t=(0,u.clamp)(0,1,t);for(const i of e)r=null==r?i:r*t+i*(1-t);return r},t.centroid=function(e){const t=e[0].length,r=[];for(let i=0;ie[i]))));return r},t.l2norm=P,t.dot=_,t.cosineSimilarity=function(e,t){return(0,u.finiteOrElse)(_(e,t)/(P(e)*P(t)),void 0)},t.jaccard=function(e,t){return(0,a.isEmpty)(e)&&(0,a.isEmpty)(t)?0:(0,u.finiteOrElse)((0,h.intersection)(e,t).size/(0,h.union)(e,t).size,void 0)}},45969:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const i=r(73024),n=r(38639),s=r(19851),o=r(59958),a=r(43334);t.isDocker=(0,s.lazy)((()=>a.isLinux&&((0,n.toBoolean)(process.env[o.PS_IS_DOCKER])??(0,i.existsSync)("/.running-in-container"))))},29325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const i=r(76760),n=r(19851),s=r(54993);t.isPacked=(0,n.lazy)((()=>!(0,s.toS)(__filename).includes((0,i.join)("core","platform","IsPacked"))))},43334:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinuxSnap=t.isLinuxAppImage=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const n=i(r(48161)),s=i(r(1708)),o=r(22573),a=r(38639),l=r(59958),u=n.default.platform();t.inspectFlag=s.default.argv.includes("--inspect")||(0,a.isTrue)(s.default.env.NODE_INSPECT),t.isCI=(0,a.isTrue)(s.default.env.CI),t.isWin="win32"===u||"cygwin"===u,t.isWinPortable=t.isWin&&(0,o.notBlank)(s.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===u,t.isLinux="linux"===u,t.isLinux_x64=t.isLinux&&"x64"===n.default.arch(),t.isArm=null!=/^arm\b/i.exec(n.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isLinuxAppImage=t.isLinux&&((0,o.notBlank)(s.default.env.APPIMAGE)||(0,o.notBlank)(s.default.env.APPDIR)),t.isLinuxSnap=t.isLinux&&(0,o.notBlank)(s.default.env.SNAP_USER_DATA),t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=s.default.versions.electron,t.isElectron=t.isMainElectron||(0,a.isTrue)(s.default.env[l.ELECTRON_RUN_AS_NODE]),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":u},24540:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=t.containsRpiModel=void 0;const n=i(r(73024)),s=r(19851),o=r(43334);function a(e="/proc/cpuinfo"){if(o.isWin||o.isMac)return!1;try{return null!=n.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.containsRpiModel=a,t.isRaspberryPi=(0,s.lazy)((()=>o.isLinux_arm&&a())),t.procDeviceModel=(0,s.lazy)((()=>{try{return o.isLinux?n.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}}))},45643:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.waitForPidExit=t.existingPids=void 0;const i=r(58587),n=r(59455),s=r(31562);t.existingPids=function(e){return(0,n.toA)(e).filter(i.pidExists)},t.waitForPidExit=function(e,t){return(0,s.untilTrue)((()=>!(0,i.pidExists)(e)),{timeoutMs:t,intervalMs:250})}},95402:function(e,t,r){var i,n,s,o,a=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)},l=this&&this.__classPrivateFieldSet||function(e,t,r,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,r):n?n.value=r:t.set(e,r),r},u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.addPid=t.Pids=t.killPid=void 0;const c=r(58587),d=u(r(31421)),h=u(r(1708)),f=r(40958),m=r(22573),g=r(42659),p=r(55835),y=r(31586),v=r(97790),w=r(59455),S=r(54993),b=r(54557),P=r(19851),_=r(50213),E=r(88158),M=r(409),C=r(78406),T=r(25764),x=r(99331),D=r(56519),k=r(46292),O=r(8769),I=r(83278),A=r(32144),F=r(29882),N=r(43334),L=r(24399),R=r(58261),j=(0,P.lazy)((()=>(0,_.mkLogger)("proc.Pids"))),B=10*g.secondMs;function V(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const r=(0,p.map)(t.start,(e=>e.getTime())),i=e.startTime;return(0,y.gt0)(r)&&(0,y.gt0)(i)&&Math.abs(r-i){const e=Date.now()-2*g.minuteMs,t=await this.pidsDir.childFiles((async t=>(0,A.isJsonExt)(t)&&(0,F.isHiddenBasename)(t.base)&&(0,y.lt)(t.mtimeMs(),e)));for(const e of(0,w.toA)(t))j().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}}),this.killOldProcs=(0,M.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:g.minuteMs,f:async(e={})=>{j().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,r=e.force??N.isWin,i=await this.pidfiles(),n=await this.pids(i??[]);if((0,f.isEmpty)(n))return j().info("killOldProcs(): no pidfiles"),[];const s=[],o=[],a=await(0,R.pidInfos)(n);if(null!=a){for(const n of i){const i=await n.readJson();if(null==i){j().warn("killOldProcs(): failed to read pidfile "+n.base),await n.unlink("debug");continue}const l=i.pid;if(!(0,y.gt0)(l)){j().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+n.base,{json:i,pid:l}),await n.unlink("debug");continue}const u=a.find((e=>e.pid===l));if(null==u||!V(i,u)){j().debug("killOldProcs(): pid no longer present: unlinking "+n.base,{json:i,pidEntry:u}),await n.unlink("debug"),s.push(i);continue}const c=(0,y.gt0)(i.timeoutMs)?i.startTime+i.timeoutMs:void 0,d=t?"all pids are being shut down":(0,y.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,y.lt)(i.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=d&&(j().info("killOldProcs(): killing",{reason:d,json:i}),o.push(W(l,r,!1)),s.push({...i,...u}))}return o.length>0&&await Promise.allSettled(o),s}(0,O.onError)("Pids.killOldProcs(): failed to get process information")}}),o.set(this,void 0)}async addPid_(e,t,r=!1){if(null==e)throw new Error("undefined info");const o=e.pid;if(!(0,y.gt0)(o))throw new Error("undefined pid");const l=e.ppid+":"+e.pid;return(0,c.pidExists)(o)?(r&&a(this,n,"f").delete(l),a(this,n,"f").getOrSet(l,(async()=>{const r=a(this,i,"m",s).call(this,e.pid),n=(0,v.opt)((0,E.Try)((()=>(0,F.parseNativePath)(e.cmd).base))).filter(m.notBlank).getOrElse((()=>e.cmd)),o=t.getTime(),l={...e,cmd:n,startTime:o};return await r.writeJson_(l),j().debug("addPid() wrote "+r,l),r}))):(a(this,n,"f").delete(l),void j().debug("addPid(): no-op, pid already gone",{info:e,start:t}))}pidfiles(){return this.pidsDir.clear().children((e=>{const t=(0,y.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==h.default.pid}))}async pids(e=this.pidfiles()){return(0,f.compact)((0,w.toA)(await e).map((e=>(0,y.toInt)(e.name))))}async onKill(e){const t=a(this,i,"m",s).call(this,e);return(0,D.thenMap)(t.readJson(),(t=>this.addPid_({...t,timeoutMs:1},(0,g.ago)(g.minuteMs),!0).catch((t=>{j().info("onKill(): failed to rewrite pidfile: "+t,{pid:e})}))))}scheduleInterval(){return(null==a(this,o,"f")||a(this,o,"f").ended)&&l(this,o,new C.EndableInterval({name:"Pids.cleanup",callback:()=>this.killOldProcs(),intervalMs:5*g.minuteMs,rank:T.EndableRanks.first}),"f"),a(this,o,"f")}cancelInterval(){a(this,o,"f")?.end(),l(this,o,void 0,"f")}}t.Pids=q,n=new WeakMap,o=new WeakMap,i=new WeakSet,s=function(e){return this.pidsDir.join(e+".json")},q.instance=(0,P.lazy)((()=>(0,p.map)((0,k.configDir)(),(e=>new q(I.BaseFile.for(e).join("pids")))))),t.addPid=function(e,t){return q.instance()?.addPid_(e,t)}},58261:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.psWinWmic=t.pidInfos=t.notExistingPids=t.pidInfo=t.isProcEntry=void 0;const n=r(31421),s=r(48161),o=i(r(1708)),a=r(40958),l=r(22573),u=r(42659),c=r(31586),d=r(68708),h=r(59455),f=r(54993),m=r(48884),g=r(53507),p=r(19851),y=r(50213),v=r(84968),w=r(48963),S=r(56519),b=r(84777),P=r(8103),_=r(45879),E=r(43334),M=r(24399),C=r(45643),T=(0,p.lazy)((()=>(0,y.mkLogger)("proc.ps")));function x(e){return null!=e&&(0,c.gt0)(e.pid)&&null!=e.start&&(0,l.notBlank)(e.cmd)}async function D(e){if(E.isLinux)return async function(e){const t=[];for(const r of e)t.push(z(await(0,_.readFileMaybe)("/proc/"+r+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,a.compact)(t)})}(e);const t=(0,C.existingPids)(e),r=(await(0,m.collectBatchedAsync)(t,20,E.isWin?A:R)).filter((e=>x(e)&&t.includes(e.pid)));return T().tap({msg:"pidInfos()",result:r,meta:{pids:e}})}t.isProcEntry=x,t.pidInfo=async function(e){return(0,S.thenMap)(D([e]),(t=>(0,h.toA)(t).find((t=>t.pid===e))))},t.notExistingPids=async function(e){return(0,a.isEmpty)(e)?[]:(0,S.thenMap)((0,C.existingPids)(e),(t=>{const r=[o.default.pid,...t];return e.filter((e=>!r.includes(e)))}))},t.pidInfos=D;const k="Get-Process",O="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).join(",")}async function A(e){if(M.PowerShell.instance().ended)return L(e);const t=[k,"-Id",I(e),"-ErrorAction SilentlyContinue",O].join(" ");return(0,S.thenMap)(M.PowerShell.instance().executeJsonToA(t),(e=>e.map((e=>({pid:e.Id,start:(0,w.pwshJsonDate)(e.StartTime),cmd:e.ProcessName})))))}const F={maxBuffer:1048576,timeoutMs:15*u.secondMs,ignoreExitCode:!0,ignoreStderr:!0},N=["CommandLine","CreationDate","ProcessId"];async function L(e){const t=["process"];if((0,a.isNotEmpty)(e)){const r=(0,a.uniq)([...e.filter(c.gt0),o.default.pid]).map((e=>`ProcessId=${e}`)).join(" or ");t.push("where",r)}t.push("get",N.join(","));const r=await(0,b.stdoutResult_)((0,P.wmic)(),t,F),i=(0,d.onlyReqValued)((0,g.parseFixed)(N,r.result).map((e=>({pid:(0,c.toInt)(e.ProcessId,{defaultValue:-1}),start:(0,w.wmiDate)(e.CreationDate),cmd:(0,f.toS)(e.CommandLine)}))));return i.find((e=>e.pid===o.default.pid))||i.push({pid:o.default.pid,start:new Date(v.StartTs),cmd:"node "+o.default.title}),i}async function R(e){return t=(await(0,b.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...F,ignoreExitCode:!0})).result,(0,l.blank)(t)?[]:(0,g.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map((e=>({pid:(0,c.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)})));var t}t.psWinWmic=L;const j=(0,p.lazy)((()=>{try{if(E.isLinux)return(0,c.toGt0)((0,n.spawnSync)("getconf",["CLK_TCK"],{shell:!1}))??100}catch(e){T().warn("clk_tck failed",{error:e})}return 100})),B=(0,p.lazy)((()=>Date.now()-(0,s.uptime)()*u.secondMs)),V=/(?\d+) \((?.+)\) (?[A-Z]) (?:\d+ ){18}(?\d+)/i;function z(e){const t=V.exec((0,f.toS)(e))?.groups,r=(0,c.toInt)(t?.pid),i=t?.comm,n=(0,c.toInt)(t?.starttime);return(0,c.gt0)(r)&&!(0,l.blank)(i)&&(0,c.gt0)(n)?{pid:r,cmd:i,start:new Date(B()+n/j()*u.secondMs),state:t?.state}:void 0}},24399:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkPowerShell_=t.PowerShell=t.pwshQuote=void 0;const i=r(58587),n=r(19851),s=r(22573),o=r(42659),a=r(41400),l=r(55835),u=r(13538),c=r(36557),d=r(14121),h=r(50213),f=r(7282),m=r(45255),g=r(81168),p=r(25764),y=r(38836),v=r(99331),w=r(56519),S=r(31562),b=r(84777),P=r(34102),_=r(43334),E=r(28874),M=r(63870),C="{ready}",T=" | ConvertTo-Json -Compress";function x(e){return'"'+e.replace(/['`"“”#]/g,(e=>"`"+e)).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}t.pwshQuote=x,(0,a.later)((()=>(0,P.ee)().on("clearCache",(()=>D.instance.prior()?.clearMockResults()))));class D extends y.EndableWrapper{static ensureInstance(){const e=this.instance();return e.ended?this.instance.refresh():e}constructor(){super("PowerShell",(()=>this.bco.end()),p.EndableRanks.postdb),this.mockResults=new Map,this.bco=new c.BatchClusterObserver("PowerShell",new i.BatchCluster({processFactory:()=>(0,b.execFile)("powershell",E.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${C}"}`,...(0,s.mapNotBlankOr)(E.Settings.powerShellCulture.valueOrDefault,(e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`]),[])].join(";"),pass:C,fail:"Error",exitCommand:"exit",maxProcs:E.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,M.commandTimeoutMs)(),maxIdleMsPerProcess:o.minuteMs,cleanupChildProcs:!1}),p.EndableRanks.postdb),E.Settings.powerShellProcs.watch((()=>this.bco.t.setMaxProcs(E.Settings.powerShellProcs.valueOrDefault))),this.pwsh=this.bco.t}get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson("$PSVersionTable.PSVersion")}version(){return(0,w.thenMap)(this.executeJson("$PSVersionTable.PSVersion"),(e=>`${e.Major}.${e.Minor}.${e.Build}`))}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,g.ensureSuffix)(e,T),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const r=this.mockResults.get(e);return t(r.stdout,r.stderr,r.passed)}try{const r=await(0,d.thenElapsed)(this.pwsh.enqueueTask(new i.Task(e,((r,i,n)=>t((0,l.map)(r,(t=>(0,g.stripPrefix)(t,e))),i,n)))));return this.logger.tap({msg:"execute()",result:r.result,meta:{elapsedMs:r.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed: "+t,{cmd:e})}}}async executeJson(e){const t=await this.execute((0,g.ensureSuffix)(e,T),((e,t,r)=>({stdout:e,stderr:t,passed:r})));if(null!=t)if((0,s.blank)(t.stdout)||(0,s.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const r=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,g.ellipsize)(t.stdout),after:(0,g.ellipsize)(r)}),JSON.parse(r)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){return(0,w.thenMap)(this.executeJson(e),(e=>Array.isArray(e)?e:[e]))}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+x(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=D,D.instance=(0,n.lazy)((()=>{if(!_.isWin)throw new Error("PowerShell isn't available on this platform");return new D})),t.checkPowerShell_=async function(){const e=D.instance();if(e.ended||(0,v.ending)())return"PowerShell ended";const t=await(0,u.thenOrTimeoutError)(e.version(),(0,M.commandTimeoutMs)());if((0,s.blank)(t)){const t=await(0,S.until)((()=>e.lastStartError??e.lastTaskError),{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});throw null!=t?t:new Error("(unknown error)")}return t}},22859:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateTypes=void 0;const i=r(50989);t.AggregateTypes=(0,i.strEnum)("union","intersection")},71988:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const i=r(50989);t.AssetFileSortCriteria=(0,i.strEnum)("resolution","schemeIdx","capturedAtPrecision","metadataCoverage","isBrowserSupported","isEditOrUpdate","isCover","count","mtime","basename","parentBasename","uri")},38483:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const i=r(22573),n=r(38639),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toBoolean})}}t.BooleanSetting=o},90536:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).flatMap(parseFloat).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=a},75164:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(97790),o=r(83179);class a extends o.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:t=>(0,s.opt)(t).filter(i.notBlank).flatMap(n.toInt).map((t=>(0,n.clamp)(e.min,e.max,t))).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,n.clamp)(this.min,this.max,e??this.min)}addToJSON(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=a},10546:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const i=r(50989);t.ColorDistanceFunctions=(0,i.strEnum)("cie76","cie94","ciede2000")},90967:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const i=r(36507),n=r(22573),s=r(45599),o=r(50213),a=r(81168),l=r(98314),u=r(8769),c=r(80372),d=(0,s.defer)((()=>(0,o.mkLogger)("settings.CronSetting")));function h(e){try{const t=(0,a.trimQuotes)(e);return void((0,n.blank)(t)||(0,i.Cron)(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,r){try{return(0,n.blank)(t)?void 0:(0,i.Cron)(t,{name:e,unref:!0,protect:!0,catch:r=>(0,u.onError)(r,{name:e,crontab:t}),...r})}catch(r){return void d().warn("invalid cron",{name:e,crontab:t,error:r})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},67958:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},55948:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorPixelsDefault=void 0,t.DominantColorPixelsDefault=1024},57039:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const i=r(70488),n=r(91655),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration})}get valueOrDefault(){return(0,i.decodeDuration)(super.valueOrDefault)}get value(){return(0,i.decodeDuration)(super.value)}set value(e){super.userValue=(0,i.decodeDuration)(e)}get humanValue(){return(0,n.fmtFullDuration)(this.value)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,i.decodeDuration)(e)}}t.DurationSetting=o;class a extends s.Setting{constructor(e){super({...e,toEnv:i.encodeDuration,fromEnv:i.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,i.decodeDuration)(this.defaultValue)}get fileValue(){return(0,i.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=a},9945:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.FloatSetting=o},74589:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt})}}t.IntegerSetting=o},844:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinValidYear=void 0,t.MinValidYear=1920},96093:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFileSetting=void 0;const i=r(22573),n=r(53265),s=r(87652);class o extends s.OptionalStringSetting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>(0,i.blank)(e)?void 0:(0,n.resolve)(e),defaultValue:void 0,...e})}}t.OptionalFileSetting=o},23561:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:i.notBlankToS,fromEnv:n.toFloat})}}t.OptionalFloatSetting=o},69005:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const i=r(22573),n=r(31586),s=r(83179);class o extends s.Setting{constructor(e){super({...e,toEnv:i.notBlankToS,fromEnv:n.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=o},87652:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=n},28283:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.envFromName=t.nameFromEnv=void 0;const i=r(51926),n=r(83556);t.nameFromEnv=function(e){return(0,n.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,i.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")}},83179:function(e,t,r){var i,n,s=this&&this.__classPrivateFieldGet||function(e,t,r,i){if("a"===r&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?i:"a"===r?i.call(e):i?i.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=t.settingsToObj=void 0;const o=r(19851),a=r(40958),l=r(79666),u=r(50357),c=r(57924),d=r(98553),h=r(55835),f=r(68708),m=r(39926),g=r(46891),p=r(42279),y=r(59455),v=r(40583),w=r(81168),S=r(44198),b=r(96706),P=r(34102),_=r(28283),E=r(81075),M=r(98778),C=r(10357);t.settingsToObj=function(e){const t={};for(const r of e)r.hasValue()&&(t[r.name]=r.value);return t},t.Setting=class{constructor(e){i.add(this),this.opts=e,this._envValue=(0,o.lazy)((()=>this.readFromEnv())),this.watchers=[],this.optsOverrides={}}getState(){return{user:this._userValue,env:this.envValue,file:this._fileValue,tmp:this._tmpValue}}dump(){return{name:this.name,key:this.key,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}setState(e){null!=e&&(this._userValue=e.user,this.envValue=e.env,this._fileValue=e.file,this._tmpValue=e.tmp)}toEnv(e){return null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?s(this,i,"m",n).call(this,e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const r=this.opts.whyInvalid?.(e);return null!=r?s(this,i,"m",n).call(this,e??t)+": "+r:null==this.fromEnv(e)?s(this,i,"m",n).call(this,e??t):void 0}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,(e=>this._fileValue=e))}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,(t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()}))}refreshEnvValue(e={}){const t=(0,l.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get tmpValue(){return this._userValue??this._tmpValue}set tmpValue(e){this.onChange(e,(e=>this._tmpValue=e))}get value(){return this._userValue??this._envValue()??this._fileValue??this._tmpValue}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}set userValue(e){this.onChange(e,(e=>this._userValue=e))}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,w.includesIgnoreCase)([...this.keys,...this.names],e)}readFromEnv(e){const t=null==e?(0,b.caseInsensitiveEnv)():new v.CaseInsensitiveValued(e);for(const e of[...this.keys,...this.names]){const r=(0,h.map)(t.get(e),(e=>this.fromEnv(e)));if(null!=r)return r}}setFromEnv(e=(0,S.env)()){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate((()=>this.broadcastChange()))}unWatch(e){(0,a.filterInPlace)(this.watchers,(t=>t===e))}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);(0,P.ee)().emitDebounced("settingsChanged")}onChange(e,t){const r=(0,l.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(r)}maybeBroadcastChange(e){(0,u.eql)(this.valueOrDefault,e)||this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name)throw new Error("cannot set name twice");this._name=e,this._names=(0,a.uniq)([e,...(0,y.toA)(this.opts.aliases)]),this._key=(0,_.envFromName)(e),this._keys=(0,a.uniq)([...this._names.map(_.envFromName),this._key,...(0,y.toA)(this.opts.envAliases)])}get key(){return this._key}get keys(){return this._keys}get altKeys(){return this._keys.filter((e=>e!==this._key))}get category(){return this.opts.category}get categoryType(){return E.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get advanced(){return(0,h.mapOr)(this.opts.advanced,(e=>e()),(()=>!0))}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set tmpValueIfUnset(e){this.isUnset()&&(this.tmpValue=e)}get defaultValue(){return(0,p.tot)(this.optsOverrides.defaultValue)??(0,p.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,l.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,p.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const r=e??(0,S.env)(),i=t??this.value;return null!=i&&(r[this.key]=this.toEnv(i)),null==e&&b.caseInsensitiveEnv.unset(),r}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const r=e??(0,S.env)(),i=this.toEnvValue(t);return null!=i&&(r[this.key]=i,null==e&&b.caseInsensitiveEnv.unset()),r}deleteFromEnv(e){const t=(0,h.map)(e,(e=>new v.CaseInsensitiveValued(e)))??(0,b.caseInsensitiveEnv)();for(const e of[...this.names,...this.keys]){for(const r of t.delete(e)??[])delete process.env[r];delete process.env[e]}return t.obj}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0,this._tmpValue=void 0}unset(){return this.onChange(void 0,(()=>{this.unsetFileValue(),this._envValue.unset(),this.optsOverrides={},this.deleteFromEnv()})),this}addToJSON(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,w.wrap)([(0,m.padding)("-",e.length),e,(0,m.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],C.WrapComments);function r(e,r){(0,a.isEmpty)(r)||t.push(...(0,w.wrap)(["",(1===r.length?e:(0,g.pluralize)(e))+": "+(0,c.orList)(r.map((e=>(0,d.stringify)(e))))],C.WrapComments))}r("alias",this.opts.aliases),r("environment alias",this.altKeys);for(const[e,r]of(0,f.entries)(this.addToJSON())){const i=Array.isArray(r)?(0,c.orList)(r.map((e=>(0,d.stringify)(e)))):(0,d.stringify)(r);t.push(...(0,w.wrap)(["",e+": "+i],C.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,h.map)(e,(e=>this.toEnv(e)))??this.envValueOrDefault)}toTomlLines(){const e=this.toCommentedLines();return(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Example value:"],key:this.name,value:(0,p.tot)(this.exampleValue)}),(0,M.wrapTomlToLines)({lines:e,wrap:C.WrapComments,prepend:["Default value:"],key:this.name,value:(0,p.tot)(this.defaultValue)}),(0,M.wrapTomlToLines)({lines:e,key:this.name,value:(0,p.tot)(this.fileValue)}),e}},i=new WeakSet,n=function(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,d.stringify)(e)}`}},81075:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const i=r(50989);t.SettingCategories=(0,i.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Performance","Auth","Color","Db","Deduping","Filters","HealthChecks","Parsing","Previews","Privacy","Reporting","Sidecars","Subscriptions","Sync","Tagging","Updates","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Deduping,t.SettingCategories.Filters,t.SettingCategories.HealthChecks,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscriptions,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Updates,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter((e=>!t.LibraryCategories.includes(e))).sort())},28874:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.getSettingByNameOrKey=t.persistedLibrarySettings=t.persistedSystemSettings=t.transientSettings=t.persistedSettings=t.allSettings=t.pathWithDefaults=t.withDefaultPaths=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=t.isProd=void 0;const i=r(58587),n=r(51168),s=r(76760),o=r(19851),a=r(40958),l=r(76790),u=r(22573),c=r(42659),d=r(73722),h=r(68708),f=r(50989),m=r(12168),g=r(54993),p=r(37975),y=r(9092),v=r(40583),w=r(79840),S=r(7282),b=r(12801),P=r(4328),_=r(70488),E=r(84248),M=r(5531),C=r(99315),T=r(34365),x=r(34580),D=r(96706),k=r(50274),O=r(33866),I=r(52086),A=r(48584),F=r(45969),N=r(43334),L=r(24540),R=r(70379),j=r(71300),B=r(33209),V=r(48987),z=r(68268),W=r(61208),q=r(99023),U=r(30577),G=r(1485),H=r(19861),J=r(55111),K=r(30933),$=r(22859),Y=r(71988),Z=r(38483),X=r(90536),Q=r(75164),ee=r(10546),te=r(90967),re=r(67958),ie=r(55948),ne=r(57039),se=r(9945),oe=r(74589),ae=r(844),le=r(96093),ue=r(23561),ce=r(69005),de=r(87652),he=r(81075),fe=r(58305),me=r(57571),ge=r(72564),pe=r(80372),ye=r(80496);t.isProd=(0,o.lazy)(S.isProd);const ve=()=>!(0,t.isProd)();function we(){return t.Settings.exposeNetworkWithoutAuth.valueOrDefault}function Se(){return(0,t.isProd)()?"warn":"info"}t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={configDir:new de.OptionalStringSetting({category:he.SettingCategories.Paths,description:["This is the system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml! This setting is here for documentation, and to allow the PS_CONFIG_DIR environment variable to override the default setting.","PhotoStructure's system configuration directory defaults to:","- Windows: %APPDATA%\\PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","- macOS: ~/Library/Application Support/PhotoStructure","- Linux: ${XDG_CONFIG_DIR:$HOME/.config}/PhotoStructure."].join("\n"),defaultValue:()=>"",advanced:()=>!1,transient:!0}),libraryDir:new le.OptionalFileSetting({aliases:["libraryPath","library"],category:he.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),copyAssetsToLibrary:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'Should PhotoStructure copy photos and videos to your PhotoStructure Library? This setting holds the value for the welcome page\'s "May PhotoStructure organize your photos and videos?" section, and is called "automatic organization" on the website.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),previewsDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 .',defaultValue:()=>".photostructure/previews"}),originalsDir:new pe.StringSetting({aliases:["originalDir"],category:he.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nSee https://forum.photostructure.com/t/hybrid-photostructure-libraries/775 and https://forum.photostructure.com/t/new-easy-mode-for-docker-coming-in-v2-1/1278/6?u=mrm .',defaultValue:""}),scanAllDrives:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:()=>!1}),scanMyPictures:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:'If set, PhotoStructure will automatically add your pictures directory to your "scanPaths" setting and then flip this setting back to false. Add your Pictures directory directly to your scanPaths setting instead.',defaultValue:!1,deprecated:!0}),scanPaths:new fe.StringArraySetting({aliases:["scanPath"],category:he.SettingCategories.Paths,description:'This holds an array of absolute paths to scan for assets. If you are setting this via an environment variable, you may use either standard PATH formatting, like `PS_SCAN_PATHS="/path/one:/path/two"`, or use JSON encoding, like `PS_SCAN_PATHS=\'["/path/one","/path/two"]\'`.',advanced:()=>!1}),argvScanPaths:new fe.StringArraySetting({category:he.SettingCategories.Paths,description:'This holds an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. See https://forum.photostructure.com/t/1597/4 . For internal use only.',transient:!0,advanced:()=>!0}),pidFile:new de.OptionalStringSetting({category:he.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new pe.StringSetting({category:he.SettingCategories.Paths,description:"Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""}),fsCacheSlowMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>ve()?"1":"25"}),imageCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"Assets requiring conversion may need intermediary file storage as they are imported. These intermediary files only need to live as long as the import process for that asset. Too short of a time will result in this conversion work being re-done during import. Too long of a time will result in additional diskspace in your cache directory being consumed.",defaultValue:"15m"}),readdirCacheMs:new ne.DurationSetting({category:he.SettingCategories.Cache,description:"readdir() can take a long time over slow network shares and when directories are very large. This setting controls how long to cache readdir results that are slow (which take >= .5 seconds). Too short of a time will result in low cache hit rates, and very slow imports for these problematic directories. Too long of a time will result in PhotoStructure not seeing changes made to these directories.\nSet to 0 to disable readdir() caching.",defaultValue:"5m"}),readdirSizeCacheThresh:new oe.IntegerSetting({category:he.SettingCategories.Cache,description:"If readdir() has more than this number of child elements, always cache it.\nSet to 0 to disable readdir() caching.",defaultValue:()=>ve()?32:1024}),quiet:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"If true, the main service won't emit lifecycle messages to stdout. Note that logStdout=true or logTail=true will override quiet=true.",defaultValue:!1}),logLevel:new pe.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:he.SettingCategories.Logging,description:'Determines which level of log messages are emitted to log files. May be "debug", "info", "warn", "error", "fatal", or several log level directives followed by a context (like "debug:web").',defaultValue:Se}),logDir:new pe.StringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logCompression:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:t.isProd}),logWebRequests:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new Z.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:he.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),tailLogs:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs from currently running PhotoStructure processes? This should be false unless you're running a service by hand.",defaultValue:!1,transient:!0}),logColor:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Output all logs with terminal escape codes to colorize output. If NO_COLOR=1, TERM=dumb, or TERM=unknown, this defaults to false. See https://no-color.org/ .",defaultValue:()=>!(0,p.noColor)()}),logContextLimit:new oe.IntegerSetting({category:he.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new Z.BooleanSetting({category:he.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new de.OptionalStringSetting({category:he.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nSee https://docs.greylog.org/v1/docs/gelf .',exampleValue:()=>"localhost:12201"}),logServerLevel:new pe.StringSetting({category:he.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:Se}),useFsWatch:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will use the native filesystem watch APIs to detect file changes. This is the default and recommended setting. If false, PhotoStructure will poll the filesystem for changes instead. This is not recommended, but may be useful if you're running PhotoStructure on an OS or filesystem that doesn't support change notifications, like some network filesystems.\nSee https://nodejs.org/api/fs.html#availability for more information.",defaultValue:()=>!0}),allowFilesystemSleep:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"If true, PhotoStructure will set disable a handful of other settings which will allow the OS to put the filesystem to sleep when it's idle. This can save power, but can also cause PhotoStructure to miss file changes.\nThis sets sharedStatePollMs=0 and dbFsLockStaleMs=0.",defaultValue:()=>!1}),statTimeoutMs:new ne.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:he.SettingCategories.Filesystem,description:'Filesystem traversal can be dangerous business with scratched CDROMs and old busted hard drives. To prevent PhotoStructure from getting "stuck" when trying to read these devices, it will timeout directory iteration if stat() or readdir() exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.\nSet to 0 to disable.',defaultValue:()=>"30s"}),watchDebounceMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new fe.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:he.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.",defaultValue:()=>H.DefaultExcludedFilesystemTypes}),excludedRootDirectories:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into these root directories looking for assets.",defaultValue:()=>G.DefaultExcludedLinuxRoots}),excludedMountpointPaths:new fe.StringArraySetting({aliases:["ignoredMountpoints"],category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.",defaultValue:G.defaultExcludedLinuxMountpointPaths}),excludedMountpointBasenames:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these names.",defaultValue:()=>G.DefaultExcludedLinuxMountpointNames}),validateMountpoints:new Z.BooleanSetting({category:he.SettingCategories.Filesystem,description:"When true, PhotoStructure ignores volumes whose mountpoints do not exist. If any volumes are unhealthy, though, this may wedge volume handlers.",defaultValue:!0}),mountpoints:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:"If set, this value will be used instead of the cross-platform mountpoints() method. Normally only for internal use."}),mountpointsTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>N.isWin?"15m":"0"}),remoteFilesystemTypes:new fe.StringArraySetting({category:he.SettingCategories.Filesystem,description:'Filesystems with these types should always be considered "remote".',defaultValue:["sshfs","s3fs"]}),volumeUuidFilePaths:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:'PhotoStructure will append these paths to all mountpoints to look for previously-set volume universally unique identifiers (UUIDs). The first item in this list that exists will be used, and if "writeVolumeUuidFiles" is true, the first item in this list will be used to write the volume UUID (which will be the partition UUID, if available, or a random UUID if not available). Windows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid","System Volume Information/IndexerVolumeGuid"]}),readVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nSee https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:"When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.",defaultValue:!0}),writeVolumeUuidFiles:new Z.BooleanSetting({category:he.SettingCategories.Volumes,description:'When true, PhotoStructure (tries to) write files with universally unique identifiers into the root directory of volumes, which enables cross-host library portability. Set this to false if you don\'t want PhotoStructure to try to write these ".uuid" files. See https://photostructure.com/faq/what-is-a-volume for more information.',defaultValue:!0}),writeVolumeUuidMountpointBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new ne.DurationSetting({category:he.SettingCategories.Filesystem,description:"How frequently should PhotoStructure reload volume metadata (like bytes-free, which is used in a health check)? Values less than a minute are not necessary. A value of 0 will cache indefinitely.",defaultValue:"15m"}),hostname:new de.OptionalStringSetting({category:he.SettingCategories.Networking,description:"If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS)."}),localhost:new pe.StringSetting({category:he.SettingCategories.Networking,description:'If "exposeNetworkWithoutAuth" is false, what value should PhotoStructure use for localhost? (Some firewalls are OK with "127.0.0.1", some require "localhost"). See https://letsencrypt.org/docs/certificates-for-localhost/ and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues .',defaultValue:()=>"127.0.0.1"}),httpPort:new oe.IntegerSetting({category:he.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787}),noNetwork:new Z.BooleanSetting({category:he.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1}),trustProxy:new pe.StringSetting({category:he.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See .\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),exposeNetworkWithoutAuth:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,F.isDocker)()}),cspReportOnly:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP .",defaultValue:()=>!1}),upgradeInsecureRequests:new Z.BooleanSetting({category:he.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new de.OptionalStringSetting({category:he.SettingCategories.Security,description:"If you're seeing CSP errors with older browsers, add your externally-available base URL to this setting, and it will be appended to the CSP directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src .",exampleValue:()=>"https://myphotos.example.com"}),disabledHelmetMiddleware:new ge.StringEnumsSetting({category:he.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nSee https://github.com/helmetjs/helmet#reference .',defaultValue:[],strEnum:J.HelmetPlugins}),shortProcessNames:new Z.BooleanSetting({category:he.SettingCategories.Processes,description:'Should PhotoStructure name its own processes "PhotoStructure" + the name of the sub-process, or abbreviated "phstr"? This defaults to false on PhotoStructure for Desktops and true everywhere else.',defaultValue:()=>!N.isElectron}),minDelayBetweenSpawnMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"The shorter this time is, the faster PhotoStructure will ramp up parallelism at the start of a sync. Having a larger value here mitigates initial system load from forking. See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis .",defaultValue:()=>(0,_.encodeDuration)((new i.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["minDelayBetweenSpawnMillis"],description:"If a task has an error, should we wait a bit before retrying? This may help temper error cascades.",defaultValue:()=>"250ms"}),maxRetries:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>1}),minBusyPct:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:'Every couple of minutes, if a sync is currently running, and the system load is below this value, we will assume any task running longer than "stuckCheckIntervalMs" is "stuck" and should be canceled.\nSet this to 0 to disable this check.',defaultValue:()=>1}),stuckCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:'How often should sync check for stuck tasks? See "minBusyPct" for details.',defaultValue:()=>ve()?"5s":"5m"}),streamFlushMs:new ne.DurationSetting({category:he.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis .",defaultValue:()=>N.isMac?"100ms":N.isWin?"200ms":"30ms"}),healthCheckIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"10m"}),exiftoolProcsPerChild:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new pe.StringSetting({category:he.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>w.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"Wait at most this time for sync to shut down cleanly. This needs to be long enough to possibly copy the library database back to the remote filesystem if your library is stored on a network drive. Set to 0 to disable this timeout.",defaultValue:"2m"}),minTimeBetweenServiceRestartsMs:new ne.DurationSetting({category:he.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),fatalErrorRatePerMinute:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"If PhotoStructure sees errors at a higher rate per minute than this setting, PhotoStructure will shut down. If this value is too high, PhotoStructure may look busy, but it's just busy failing. If this value is set too low, temporary errors (due to network flakiness or USB hiccups) might shut down PhotoStructure needlessly.",defaultValue:20}),minDiskFreeGb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will pause processing if the GB free on the disk that your library is stored on drops below this value. The value provided here will be multiplied by 1000^3. Note that many OSes will corrupt themselves when disks fill up, and SSDs can fail as they approach full capacity. A value of less than 8 may be unsafe (due to hibernation and OS update files).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16}),cpuBusyPercent:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will run the sync process in "single-process mode"--no external worker processes will be spun up by the "sync" process, and file imports will be done serially.',defaultValue:75,min:0,max:500}),timeoutThrottleCoeff:new se.FloatSetting({category:he.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new ce.OptionalIntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently? This will be clamped between 1 and 32.\nIf not set, a sensible value will be computed based on "cpuLoadPercent".\nIf set explicitly, this and "sharpThreadsPerProcess" will override "cpuLoadPercent" and "maxConcurrentImportsWhenRemote" settings.'}),maxConcurrentImportsWhenRemote:new oe.IntegerSetting({category:he.SettingCategories.Processes,aliases:["maxSyncFileJobsWhenRemote"],description:"How many concurrent files can be imported if the library is on a remote volume? This defaults to 2 to try to avoid overwhelming HDD I/O on the remote NAS. If this is larger than (cpus.length * cpuLoadPercent) or max child processes given available memory, this value will be ignored.",defaultValue:2}),sharpThreadsPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new me.StringEnumSetting({category:he.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>b.PriorityClasses.BelowNormal,strEnum:b.PriorityClasses}),maxMemoryMb:new oe.IntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes). Note that this is not the allocated memory. See maxRssMemoryMb for total allocated.\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxTasksPerProcess:new Q.BoundedIntegerSetting({category:he.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>ve()?50:500,min:1,max:5e3}),enableArchive:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),enableRemove:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!we()}),argon2TimeCost:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new oe.IntegerSetting({category:he.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),forceLocalDbReplica:new Z.BooleanSetting({category:he.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements .",defaultValue:()=>!1}),dbRetries:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?",advanced:()=>!0,defaultValue:20}),dbBackupRetentionCount:new Q.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:he.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbAutoVacuumMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"SQLite can auto-vacuum your library database, which ensures the database stays performant. If this is set to NONE, PhotoStructure will periodically run vacuum and optimizations from the sync process. For details, https://sqlite.org/pragma.html#pragma_auto_vacuum .",advanced:()=>!0,strEnum:E.AutoVacuumModes,defaultValue:E.AutoVacuumModes.INCREMENTAL}),dbWalCheckpointType:new me.StringEnumSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\n- PASSIVE, FULL, RESTART, and TRUNCATE values will enable.\nSee https://sqlite.org/pragma.html#pragma_wal_checkpoint .",strEnum:M.CheckpointTypes,defaultValue:M.CheckpointTypes.TRUNCATE}),dbWalAutoCheckpoint:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"The write-ahead log of your PhotoStructure library database is checkpointed periodically by the sync subprocess.\n- Choosing 0 will disable SQLite's built-in automatic PASSIVE checkpointing.\nSee https://sqlite.org/pragma.html#pragma_wal_autocheckpoint .",defaultValue:1e3}),dbInvalidFKThreshold:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nSee https://sqlite.org/pragma.html#pragma_synchronous .',strEnum:T.SynchronousModes,defaultValue:T.SynchronousModes.NORMAL}),dbRepairMode:new me.StringEnumSetting({category:he.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:C.RepairModes,defaultValue:C.RepairModes.dump}),maxBusyDbMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite supports concurrent readers but concurrent writers may collide, causing a LOCKED or BUSY error. PhotoStructure will retry the db operation for maxBusyDbMs milliseconds. This defaults to 90 seconds to accommodate slow hard drive spinups and VACUUM write locks.",advanced:()=>!0,defaultValue:()=>"90s"}),dbBusyTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"SQLite can time out requests if the db file is unavailable. PhotoStructure will retry those requests (up to `maxBusyDbMs`). A shorter time may help overall throughput, but may require more work done in retry logic. A longer time may be better for slower machines and slower disks. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nSee https://sqlite.org/pragma.html#pragma_busy_timeout for more details.\nSet this to 0 to disable.",advanced:()=>!0,defaultValue:()=>"7s"}),dbMaintenanceTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?\nNote that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.",advanced:()=>!0,defaultValue:()=>"2m"}),dbBackupIntervalMs:new ne.DurationSetting({category:he.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>ve()?"30s":"30m"}),dbBackupIntervalMinutes:new X.BoundedFloatSetting({category:he.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:ve()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>ve()?.5:30}),dbPageSizeBytes:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's page_size PRAGMA. A default of 4k should be OK. This must be a power of 2. See https://sqlite.org/pragma.html#pragma_page_size for more information.",advanced:()=>!0,defaultValue:4096}),dbCacheSizeMb:new oe.IntegerSetting({category:he.SettingCategories.Db,description:"This value will be used for SQLite's cache_size PRAGMA. The cache_size pragma should ideally be set such that the whole DB can be in memory. Note that PhotoStructure automatically increases this value to accommodate your library as it gets larger, if there is sufficient memory, so this setting is only a lower bound. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",advanced:()=>!0,defaultValue:128}),dbBatchSelectSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:1024}),dbBatchUpsertSize:new Q.BoundedIntegerSetting({category:he.SettingCategories.Db,description:"How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).",advanced:()=>!0,defaultValue:32,min:1,max:128}),dbForceRecover:new Z.BooleanSetting({category:he.SettingCategories.Db,aliases:["dbForceRebuild"],transient:!0,description:"SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nSee https://sqlite.org/recovery.html .",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new Z.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:he.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),trySoftDeletes:new Z.BooleanSetting({category:he.SettingCategories.Auth,description:'If true, "Empty Trash" will _try_ to move files into the "Trash can" or "Recycle bin", when possible. If moving a file into the trash can fails (due to permissions or filesystem functionality), the file will be "hard" deleted (or "unlinked"). This setting defaults to false on docker.',defaultValue:()=>!!ve()||!(0,F.isDocker)()}),skipHealthCheckIds:new ge.StringEnumsSetting({category:he.SettingCategories.HealthChecks,description:"List of health check IDs to skip.",defaultValue:[],strEnum:O.HealthCheckIds}),ffmpegHwaccel:new pe.StringSetting({category:he.SettingCategories.Video,description:'FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disable" to omit this argument.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry "disable" if there are hwaccel errors.\nSee https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166>, https://trac.ffmpeg.org/wiki/HWAccelIntro , and 1,min:1,max:6}),ffmpegAvcTranscodeArgs:new fe.StringArraySetting({category:he.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'The following are the default arguments added to transcode requests made to ffmpeg, when ffmpeg is available. The following arguments will follow "ffmpeg -loglevel error -threads T -i INPUT_FILE_PATH" (where T is replaced by ~half the available CPU threads, and INPUT_FILE_PATH is the full native pathname to the source video).\nIf your videos are in high colorspace like bt2020, you may want to remove the "-vf" and "colorspace=all=bt709:iall=bt709:itrc=srgb" options, but this may cause rendering issues on SDR displays. See https://forum.photostructure.com/t/1003/3 for more details.\nCAUTION: this is an advanced setting. Invalid values may cause videos that require transcoding to not be imported, or not be viewable on some browsers.',defaultValue:["-c:a","aac","-c:v","libx264","-pix_fmt","yuv420p","-vf","colorspace=all=bt2020:iall=bt601-6-625:fast=1","-color_range","1","-colorspace","1","-color_primaries","1","-movflags","+faststart"]}),transcodeMaxDim:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new ce.OptionalIntegerSetting({category:he.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded framerates.",exampleValue:()=>30}),transcodeVideos:new Z.BooleanSetting({aliases:["transcodeVideo"],category:he.SettingCategories.Video,description:"Should videos that are not in a browser-supported format be transcoded during import? Note that this is a plus-only feature. FFmpeg must be installed. Note that this *dramatically* slows down imports, and *dramatically* increases the disk space your library will need to use, but allows you to see videos that aren't directly supported by your browser. If this is set to false, your browser will only render videos directly supported by your OS.",defaultValue:!0}),transcodeBitrateQVGA:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode QVGA (320 × 240) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:800}),transcodeBitrateUHD:new oe.IntegerSetting({category:he.SettingCategories.Video,description:"What max bitrate should PhotoStructure encode UHD (3840 × 2160) videos? Videos with resolutions between QVGA and UHD will use an interpolated value between these two settings, and will not exceed the encoded bitrate of the original video. This value is in kilobytes per second.",defaultValue:18e3}),doNotTranscodeMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following video codecs. The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new fe.StringArraySetting({category:he.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following audio codecs. The audio codec is stored in the "AudioCodec" tag.',defaultValue:()=>["mp4a","sowt"]}),enableSIMD:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.",defaultValue:()=>!0}),enableVipsCache:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Should PhotoStructure enable VIPS caching, which may help speed up image operations? Note that this increases memory usage, and cache hit rates are low.",defaultValue:()=>!1}),showFileInFolderUsesThunar:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new Z.BooleanSetting({category:he.SettingCategories.Tools,description:"Does the showFileInFolderCommand expect a file: URI to the file? If this is false, the native path will be appended instead.",exampleValue:()=>!0,defaultValue:()=>N.isLinux}),showFileInFolderCommand:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),dcraw_emuPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "dcraw_emu" binary on this system. If this is set to "dcraw_emu", PhotoStructure will search your $PATH. See https://www.libraw.org/docs/Samples-LibRaw.html .',defaultValue:"dcraw_emu"}),ffmpegPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/video-support/ .',defaultValue:"ffmpeg"}),heifConvertPath:new pe.StringSetting({category:he.SettingCategories.Tools,description:'This should be the absolute, native path to the "heif-convert" binary on this system. If this is set to "heif-convert", PhotoStructure will search your $PATH. See https://photostructure.com/getting-started/heif-support/ .',defaultValue:"heif-convert"}),powerShellArgs:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new pe.StringSetting({category:he.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new oe.IntegerSetting({category:he.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new fe.StringArraySetting({category:he.SettingCategories.Tools,description:'These paths are appended to the PATH to ensure PhotoStructure can find and run external tools like ffmpeg. Use your operating system\'s separator to separate paths (":" for mac and linux, ";" for windows).',defaultValue:()=>[]}),emitTimingsOnExit:new Z.BooleanSetting({category:he.SettingCategories.Performance,transient:!0,description:"If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.",defaultValue:!1}),autoHideMenuBar:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops on Windows and Linux will auto hide the menu bar unless the Alt key is pressed.",defaultValue:!1}),hideOnLaunch:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new Z.BooleanSetting({category:he.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),updateChannel:new me.StringEnumSetting({category:he.SettingCategories.Updates,description:'TL:DR; keep this on "stable". This setting controls which builds of PhotoStructure you are eligible to update to, and on desktops, this upgrade is automated.\nPlease note that "prealpha" and "alpha" builds may not even launch, and "beta" builds have not been thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>"stable",strEnum:U.UpdateChannels}),autoUpdateCheck:new Z.BooleanSetting({category:he.SettingCategories.Updates,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.',defaultValue:!1}),allowUserAgent:new Z.BooleanSetting({category:he.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new Z.BooleanSetting({aliases:["doNotTrack"],envAliases:["DO_NOT_TRACK","DNT","GPC"],category:he.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,x.doNotTrack)()}),email:new de.OptionalStringSetting({category:he.SettingCategories.Reporting,description:"If set, this email will be used for license subscriptions and added to error reports, so we can contact you to help debug the issue. It is not required. Setting a value here does not subscribe you to any marketing emails.",exampleValue:()=>"email@example.com",advanced:()=>!1}),reportErrors:new Z.BooleanSetting({category:he.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new oe.IntegerSetting({category:he.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3}),webUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:"How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Web,description:'Streams (shown on the asset page) are coalesced when the dice coefficient of their contents are greater than this value. A value of 100 requires streams to match exactly. A value of ~50 allows streams with a couple differences to be considered the "same" stream.',defaultValue:()=>50,max:100,min:1}),lazyLoadExtraVh:new oe.IntegerSetting({category:he.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenHomeTags:new fe.StringArraySetting({category:he.SettingCategories.Web,description:'The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").',defaultValue:()=>["Type"]}),openGraphTargetWidth:new oe.IntegerSetting({category:he.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new Z.BooleanSetting({category:he.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0}),fastForwardEmptyTags:new Z.BooleanSetting({category:he.SettingCategories.Web,description:'When browsing tags in the UI, should tags that only have one child tag and no direct assets be skipped, or "fast-forwarded," over? See https://forum.photostructure.com/t/volume-id-shows-as-a-tag/754/5 for context.',defaultValue:!0}),defaultHomepagePath:new me.StringEnumSetting({category:he.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,f.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),syncUvThreads:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,description:"How many libuv threads should the primary sync process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.",advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new pe.StringSetting({category:he.SettingCategories.Sync,description:'Detailed reports for every sync are stored in this directory, which defaults to ".photostructure/sync-reports" within your PhotoStructure library. Absolute paths here are supported.',defaultValue:()=>".photostructure/sync-reports"}),syncReportMaxRows:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"Some software can't open large CSVs, so PhotoStructure will start a new sync report if the rows exceed this value. Excel and LibreOffice can open million-row CSVs, so that's our default.",defaultValue:()=>1e6}),syncReportRetentionCount:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many historical sync reports should be retained?\nSet to 0 to retain all sync reports.",defaultValue:()=>64}),quickSyncMode:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,L.isRaspberryPi)()}),taskTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),scanLibraryFirst:new Z.BooleanSetting({aliases:["syncLibraryFirst"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new Z.BooleanSetting({aliases:["syncLibraryLast"],category:he.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"When sync starts, it tries to pick up where it was previously, but this doesn't make sense if the prior work was done a while ago, as it is more likely that the filesystem has changed since.",defaultValue:6}),copyToLibraryMimeTypes:new fe.StringArraySetting({category:he.SettingCategories.Sync,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),onlyNativeFileCopy:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "cp" on macOS and Linux, and PowerShell "Copy-Item" on Windows.',defaultValue:!1}),verifyFileCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should PhotoStructure verify all file copies by comparing SHAs of the source and destination? This shouldn't be necessary on most OSes and filesystems, and slows down library imports.",defaultValue:!0}),assetPathnameFormat:new pe.StringSetting({category:he.SettingCategories.Sync,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into /.\n- See the originalsDir system setting for what your is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ".\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- See https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2?u=mrm for more details.',defaultValue:"y/y-MM-dd/BASE"}),writeSourceTagToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should PhotoStructure write to the "Source" tag add metadata to assets copied into your library that includes the path where the file was originally found? This defaults to false to prevent adding sidecars to every file in your library.',defaultValue:!1}),writeInferredTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),writeGeolocationTagsToLibraryCopies:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When enabled, inferred geolocation tags will backfill into Country/State/City tags in the library copy (by default, into an XMP sidecar).\nThis defaults to false, as reverse-geo lookup results can change over time (and should be done on-demand, rather than stored statically and drift into inaccuracies).",defaultValue:!1}),assetSubdirectoryDatestampFormat:new pe.StringSetting({category:he.SettingCategories.Sync,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),startPaused:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new te.CronSetting({category:he.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).",defaultValue:"0 2 * * *"}),syncCronTZ:new de.OptionalStringSetting({category:he.SettingCategories.Sync,whyInvalid:e=>(0,u.blank)(e)?"(blank)":n.Info.isValidIANAZone(e)?void 0:"not a valid IANA time zone",description:'The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the TZ environment variable will be used, and if TZ is blank, we\'ll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.'}),forceRebuildLibrary:new Z.BooleanSetting({category:he.SettingCategories.Sync,aliases:["rebuild"],description:"When set, all files in your library will be re-imported (caution: slow!).",defaultValue:!1,transient:!0}),forceSync:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem.",defaultValue:!1,transient:!0}),forceFilters:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.",defaultValue:!1,transient:!0}),forceRebuildPreviews:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0}),skipLibraryRebuild:new Z.BooleanSetting({aliases:["noModelUpdates"],category:he.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0}),exitWhenDone:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"When set, the sync process will exit after jobs are completed (used internally and for tests).",defaultValue:!1,transient:!0}),overwriteOriginal:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:'Should changes made through the UI, like rotations, captions, and keywords, overwrite the original file? This is potentially dangerous, as your original may be lost if the disk has errors, or there are issues in rewriting the file contents. If this is set to false, the original file will be retained in the same directory. "image.jpg" will be stored as "image_original.jpg".',defaultValue:!0}),maxDuplicatePathElements:new oe.IntegerSetting({category:he.SettingCategories.Sync,description:"How many times can a given path element exist in a directory before it is considered within an infinite filesystem loop, and should be skipped from import?",defaultValue:7}),resyncAssetOnVisit:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should Assets be automatically re-synchronized whenever their info panel is viewed? This can make sure Assets are in-sync with the filesystem, but this can slow down current imports, and add load to slower computers. This defaults to true only if the current machine has >= 8 CPUs.",defaultValue:()=>!!ve()||(0,K.cpuCount)()>=8}),excludeNoMediaAssetsOnRebuild:new Z.BooleanSetting({category:he.SettingCategories.Sync,description:"Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?",defaultValue:()=>!0}),taskListCap:new Q.BoundedIntegerSetting({category:he.SettingCategories.Sync,aliases:["workQueueHighWater"],description:"Whenever PhotoStructure is scheduling work, the task scheduler will pause producing tasks if the current task list has more than this number of items already scheduled. For example, when PhotoStructure is syncing a directory, the first step is to walk the directory and search for files to import. When the list of files scheduled to process is larger than this value, sync will pause looking for additional files to process.\nThis backpressure should help import directories that contain very large numbers of files. Note that until the last batch of work is scheduled, ETAs will be inaccurate.",defaultValue:1024,min:64,max:65536}),matchSidecarsCaseInsensitively:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new me.StringEnumSetting({category:he.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:k.SidecarExts,defaultValue:k.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to images into sidecars. If set to false, PhotoStructure will overwrite original images with metadata changes.",defaultValue:!0}),sidecarTagBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Sidecars,description:"Many applications don't read metadata from sidecars, which can make some tags, like Orientation, Rotation, or Rating, not seem to work properly in other applications. This setting is ignored if writeMetadataToSidecarsIfImage, writeMetadataToSidecarsIfVideo, and writeMetadataToSidecarsIfSidecarExists are all set to false.",defaultValue:()=>["Orientation","Rotation","Rating"]}),writeMetadataToSidecarsIfVideo:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes made to videos into sidecars. If set to false, PhotoStructure will overwrite original videos with metadata changes. This defaults to false, as most software does not use sidecars except for images.",defaultValue:!1}),writeMetadataToSidecarsIfSidecarExists:new Z.BooleanSetting({category:he.SettingCategories.Sidecars,description:"If set to true, PhotoStructure will write metadata changes into sidecars if the file already has a sidecar and the tag is not in the sidecarTagBlocklist.",defaultValue:!0}),strictDeduping:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'How strict should PhotoStructure de-duplicate files? If this is false, we consider files to be equivalent if sufficient metadata matches (even if the image hash is different). If this is true, we will always compare image hashes. NOTE: This will most likely cause RAW and JPEG pairs to not always merge to the same asset, especially if your camera uses extensive computational imagery. ALSO NOTE: If this is true, "useImageHashes" will be forced to true, and the "*corr*" and "*coeffPct" settings will be set to 95.',defaultValue:!1}),assetAggregation:new me.StringEnumSetting({category:he.SettingCategories.Deduping,description:'How should assets be aggregated?\n- "union" will allow asset file variants to join an asset if they match *any* existing variant.\n- "intersection" will only allow asset file variants to join an asset if they match *all* existing variants.\nVersions prior to 2.1 defaulted to "union" behavior.',defaultValue:$.AggregateTypes.intersection,strEnum:$.AggregateTypes}),useImageHashes:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:"Building image hashes slows down imports, but supports more robust asset merging heuristics, and allows for dominant color tagging and browsing. If you set this from false to true, and you'd previously imported new assets, you may want to rebuild your library to re-aggregate your assets.",defaultValue:!0}),checkBasenameMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'Most cameras take JPG/RAW pairs with matching basenames (so "P01234" for "P01234.JPG"). When PhotoStructure is trying to find matching assets for a given file, may it check assets that have matching basename file variants?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new Z.BooleanSetting({category:he.SettingCategories.Deduping,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),minMatchesWithoutImageHashes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If "useImageHashes" is true, this is ignored. This is a "backstop" that allows files to be aggregated together if their metadata is equal "enough." As of Sept 2022, there are 5 metadata classes to match: "cameraId", "lensId", "imageId", "exposureSettings", and "geohash". All of these "classes" pull from several individual tags. Note that if any of these classes _don\'t_ match, the files will always be considered to be from different assets.',defaultValue:3}),maxContemporaryAdoptionAssets:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'To handle photos and videos with "fuzzy" captured-at times (those that are missing second, minute, hour, or even day resolution), how many previously-imported assets with nearby captured-at times should PhotoStructure look for in your library to find an adoption candidate?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),datesBeforeAreEstimated:new pe.StringSetting({category:he.SettingCategories.Deduping,description:'PhotoStructure automatically interprets captured-at timestamps before this ISO-formatted datestamp as "estimated." PhotoStructure also considers timestamps whose minutes, seconds, and milliseconds are all 0 as "estimated."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),minExposureSettingsCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This is the minimum similarity coefficient between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,max:100,min:0}),minImageCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting controls how aggressively images are merged with each other, and is the minimum image hash similarity coefficient for images to be considered equivalent when their date is accurate, their mimetypes match, and are in color.\nThis value is applied when the captured-at date has a non-zero minute, second, or millisecond, and was captured after "datesBeforeAreEstimated," so the timestamp is considered to have high precision.\n100 (or 100%) requires exact image correlation is not recommended due to causing false negative matches.\nA value of less than 50% is fairly low image correlation, and can lead to false positive matches.',defaultValue:()=>70,max:100,min:0}),imageHashFuzzyDateDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when captured-at dates have low precision. It defaults to a positive value so we are more strict about merging images with inaccurate dates. Set to 0 to disable this delta.',defaultValue:()=>12,max:100,min:-100}),imageHashDifferentMimetypesDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'This setting\'s value is added to "minImageCoeffPct" and "minColorCoeffPct" when file mimetypes don\'t match. It defaults to a negative value because RAW and JPEG formats frequently raster slightly different image hashes, requiring a more lax threshold to match JPG+RAW pairs. Set to 0 to disable this delta.',defaultValue:()=>-15,max:100,min:-100}),imageHashGreyscaleDelta:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"This setting's value is added to \"minImageCoeffPct\" when either image is essentially greyscale. It defaults to a positive value so we are more strict about merging greyscale images. We also don't have color correlation to help us, so a more strict threshold is warranted.",defaultValue:()=>10,max:100,min:-100}),minColorCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:"Given two sets of dominant colors, this is the average percent that those sets correlate with eachother. A higher number requires stronger dominant color correlation. 100 (or 100%) requires exact dominant color correlation. A value of less than 50% indicates fairly low correlation of dominant colors, and can lead to false positives.",defaultValue:()=>73,max:100,min:0}),greyscaleColorThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Deduping,description:'Many "black and white" images, which scanned, actually include color information, especially if the source has yellowed with age. PhotoStructure determines if an image is "greyscale" if the standard deviation of a* plus the standard deviation of b* values is less than this value. By only looking at standard deviation, we can categorize sepia photos as "greyscale." Smaller values are stricter.',defaultValue:3,max:128,min:0}),gpsErrorMeters:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"What's the maximum number of meters between GPS fixpoints that should be considered equivalent locations? Note that JPG+RAW pairs from smartphones frequently have different GPS locations due to one being recorded from a rough WiFi fix, and another from aGPS.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:"Some cameras store JPEG+RAW pairs with slightly different captured-at times (!!). To ensure these are merged properly, we need to allow for these discrepancies. This setting controls how many milliseconds of difference we allow between captured-at times for different mimetypes. Set to 0 to disable this feature.",defaultValue:()=>1500}),minCapturedAtPrecisionStat:new oe.IntegerSetting({category:he.SettingCategories.Deduping,description:'If a captured-at time is low quality (using the mtime or birthtime of the file), what should PhotoStructure use as the "minimum" precision for that time? This is used to determine how much "fuzziness" to allow when comparing captured-at times during assert aggregation. Set to 0 to disable this feature.',defaultValue:()=>c.minuteMs}),fuzzyDatePrecisionCoeff:new se.FloatSetting({category:he.SettingCategories.Deduping,description:'When comparing "captured-at" dates that aren\'t from reliable metadata tags, what coefficient should be applied to the inferred precision of those dates? Larger values will mean PhotoStructure will consider these "fuzzy" dates to be less precise, and expand the date range when searching for matching assets. Set to 1 to disable this feature.',defaultValue:2}),dominantColorPixels:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modePixels"],description:"PhotoStructure downsamples images to contain this number of pixels, converts each pixel into CIELAB space, and then runs k-means clustering to extract dominant colors. Larger values will be slower to process, but will result in more accurate dominant colors. Smaller values will be faster, but may result in inaccurate dominant colors.",defaultValue:ie.DominantColorPixelsDefault,max:4096,min:256}),dominantColorDeltaE:new me.StringEnumSetting({aliases:["delta_e"],category:he.SettingCategories.Color,description:"What delta_e algorithm should PhotoStructure use to determine color differences? cie76 is quick but inaccurate. cie94 is more accurate than cie76 but 6x more computationally expensive than cie76. ciede2000 is best, but 4-6x more expensive than cie94.",defaultValue:ee.ColorDistanceFunctions.ciede2000,strEnum:ee.ColorDistanceFunctions}),dominantColorKmeansRuns:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:re.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,description:"The best dominant color cluster centroids may be quite similar. PhotoStructure will merge centroids if their Δe is less than this value. Larger values will result in more different dominant colors, but those may not be as accurate.",defaultValue:10,max:32,min:0}),dominantColorGreyThreshold:new Q.BoundedIntegerSetting({category:he.SettingCategories.Color,aliases:["modeGrey"],description:'May PhotoStructure ignore pixels that are greyscale, or "desaturated," when looking for dominant colors? Larger values will result in only saturated colors being considered for dominant colors. A pixel color will be removed if its absolute a* and b* values in CIELAB space sum to less than this value.\nSet this to 0 to include greys in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of greyscales, which results in false matches.',defaultValue:11,max:80,min:0}),previewQuality:new Q.BoundedIntegerSetting({aliases:["jpegQuality"],category:he.SettingCategories.Previews,description:"JPEG output quality for previews. Smaller values produce smaller images with lower quality. The default value of 80 strikes a balance that has almost no noticeable compression artifacts, yet still compresses images reasonably well. Depending on image content, values less than 50-70 can produce noticeable artifacts.",defaultValue:()=>80,max:100,min:10}),previewProgressive:new Z.BooleanSetting({category:he.SettingCategories.Previews,aliases:["progressive","jpegProgressive"],description:"Should preview JPEGs be progressively encoded? If set, thumbnails will take ~15% longer to generate, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0}),previewMinimized:new Z.BooleanSetting({aliases:["jpegMinimized"],category:he.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!ve()||(0,K.cpuCount)()>=4}),dcrawEmuArgs:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'Maps an original image profile to a filename stored in the "icc" directory. See that directory\'s _info.md for more information about this settings.',defaultValue:["Display P3:DisplayP3Compat-v2-magic.icc","Adobe RGB:AdobeCompat-v2.icc"]}),squareThumbStrategy:new me.StringEnumSetting({category:he.SettingCategories.Previews,description:'When PhotoStructure crops images and videos to square thumbnails, it needs to crop non-square images to a square. The default, "attention," focuses on faces and higher image energy, but is more expensive than simply cropping to the center of the image (which is faster, but will mean less-nice cropping, where faces are chopped in half). More details are available here: https://sharp.pixelplumbing.com/api-resize .',defaultValue:I.CropStrategies.attention,strEnum:I.CropStrategies}),videoFrameAtSec:new se.FloatSetting({category:he.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new Z.BooleanSetting({aliases:["sharpen"],category:he.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= 2.5x pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,a.diff)(d.FitSizes.values,["uhd8k","uhd5k"]),strEnum:d.FitSizes}),embeddedPreviews:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"For larger source images that are greater than 15MP, what embedded image preview tags should be used when present? Using these embedded images speeds up image preview generation, but if the embedded image doesn't match the full-sized image, the image preview will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxEmbeddedBuffer:new oe.IntegerSetting({category:he.SettingCategories.Previews,description:`PhotoStructure tries to use embedded images for preview generation to minimize work. For smaller images, we can directly pipe the buffer from the embedded image into our image pipeline, but for larger images, it can be faster to use an intermediary file stored on the cache drive. Larger values will reduce disk I/O but increase memory and CPU consumption. Set this to 0 to force all previews to be written to the cache dir.\nThis defaults to ${(0,m.fmtBytes)(4*t.DefaultMaxEmbeddedBuffer)} on Windows due to slow disk I/O on that platform.`,defaultValue:()=>(N.isWin?4:1)*t.DefaultMaxEmbeddedBuffer}),skipPreviews:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1}),variantSortCriteria:new ge.StringEnumsSetting({category:he.SettingCategories.Previews,aliases:["assetFileSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variant for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria .',strEnum:Y.AssetFileSortCriteria}),variantSortCriteriaPower:new X.BoundedFloatSetting({category:he.SettingCategories.Previews,description:'Variant sort criteria "resolution" and "fileSize" are scaled down to ignore irrelevant differences. Scalars are raised to this power to reduce them, so a value of 1 means the criterion is unchanged from the "raw" value. Smaller values for this setting let _larger_ differences be ignored.',defaultValue:()=>1/6,max:1,min:1e-6}),includePreviewTags:new Z.BooleanSetting({category:he.SettingCategories.Previews,description:'By default, PhotoStructure strips all metadata from preview images. This both saves space, and reduces disk I/O during preview generation. If this setting is enabled, all "includedPreviewTags" will be restored in preview images that are more than 1 megapixel. If this setting is enabled, each preview image will be written to twice (once for the image and once for the metadata), so imports will be slower.',defaultValue:!1}),includedPreviewTags:new fe.StringArraySetting({category:he.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>B.DefaultIncludedPreviewTags}),disableAllFilters:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new Z.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:he.SettingCategories.Filters,description:'Setting this to true will omit ALL default exclusion globs, and is equivalent to providing all default exclusion globs to the "excludeGlobsOmit" setting. You\'re then free to add whatever exclusion globs you want, using the "excludeGlobsAdd" setting.',defaultValue:!1}),excludeGlobsOmit:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.',defaultValue:()=>[]}),globsCaseInsensitive:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs of v2023, this defaults to "false", as most people don\'t use this filesystem feature, and it\'s expensive for PhotoStructure to check for this flag on every file it imports.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Normally PhotoStructure uses file extensions (like .JPEG or .MP4) to perform initial file filtering, rather than examining the content of the file to determine the file format (or "mimetype"). If you have files that don\'t use valid file extensions, you can set this to false, but know that file imports will be slower.',defaultValue:!0}),requireMakeModel:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"PhotoStructure can require images to have EXIF tags for Make and Model. This prevents unwanted preview images from other photo apps and screenshots from being imported. If you have images you want in your library that don't have these tags, set this to false. Note that this is ignored for video files, as those files seldom have Make and Model set (and would prevent most video files from being imported).",defaultValue:!1}),rejectRatingsLessThan:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:'Files with a metadata rating that is less than this value will not be imported into your library. Set to -100 to disable this filter.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.',defaultValue:0}),keywordBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"Any asset that contains any of these keywords will be excluded from your library. Set this to an empty array to disable this feature.",defaultValue:["private"]}),minImageDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels an image's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the image. The default comes from the VGA standard of 640x480. If this is set to 0, no minimum resolution filter will be applied to photos.",defaultValue:480}),minVideoDimension:new oe.IntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of pixels a video's dimensions must meet or exceed to be imported? Note that this value is applied to both the height and width of the video. The default comes from the QVGA standard of 320x240. If this is set to 0, no minimum resolution filter will be applied to videos.",defaultValue:240}),minVideoDurationSec:new ue.OptionalFloatSetting({category:he.SettingCategories.Filters,description:"What's the minimum number of seconds for a video to be imported? If this is set to 0 or unset, no minimum duration limit will be applied.",defaultValue:2}),maxVideoDurationSec:new ce.OptionalIntegerSetting({category:he.SettingCategories.Filters,description:"What's the maximum length a video can be and still be imported? If this is set to 0 or unset, no maximum duration limit will be applied."}),minAssetFileSizeBytes:new oe.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*m.KB}),maxAssetFileSizeBytes:new oe.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:he.SettingCategories.Filters,description:"What's the maximum photo or video size you want imported into your library? (This can prevent movies from being pulled into and filling up your library). A value of 0 will disable this filter.",defaultValue:.5*m.GB}),validateJpegImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should JPEG photos be validated before importing? If a JPEG has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports.",defaultValue:!0}),imageFailOn:new me.StringEnumSetting({category:he.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:A.SharpFailOns.truncated,strEnum:A.SharpFailOns}),validateRawImages:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:"Should raw-format images (like NEF, CR2, ARW, and ORF) be validated before importing? If an image has any decoding errors, and this setting is true, that file will not be imported into your library.\nNote that more recent cameras may use a raw encoding that isn't supported yet (like CR3), but PhotoStructure may still be able to import those files if full-resolution embedded images are present, so this defaults to false.\nEnabling this feature slows down imports.",defaultValue:!1}),validateMimetypeSkiplist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:"If a file's mimetype matches any of these values, it will be imported without being validated. This is useful for files from cameras that may render RAW image formats that are not supported by LibRaw (yet). Note that this setting is case-insensitive.",defaultValue:()=>["image/x-panasonic-rw2"]}),validateVideos:new Z.BooleanSetting({category:he.SettingCategories.Filters,description:'Should videos be validated before importing? If a video has any decoding errors, and this setting is true, that file will not be imported into your library. Enabling this feature slows down imports, as videos must be fully decoded (or "played") to be validated.',defaultValue:()=>!1}),validationErrorBlocklist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input stream","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new fe.StringArraySetting({category:he.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),capturedAtTags:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.DefaultCapturedAtTagsConst}),useMWG:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.",defaultValue:!0}),capturedAtTagsFallback:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:j.ProblematicCapturedAtTags}),badDates:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"The following ISO values will be ignored when extracting a file's captured-at time. See https://forum.photostructure.com/t/photostructure-ignored-the-date-metadata-of-some-photos-marked-them-as-taken-in-2002/340/8 and https://forum.photostructure.com/t/incorrect-date-assigned-to-photo/419 .",defaultValue:()=>["2002-12-08T12:00:00"]}),defaultVideosToUTC:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should video created-at times be assumed to be in UTC? Most cameras use UTC (even if the timezone is set in the camera!). Set this to false to revert to pre-v2.1 behavior.",defaultValue:()=>!0}),defaultCopyright:new de.OptionalStringSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>V.DefaultLensMakes}),extraDateTimeFormats:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new fe.StringArraySetting({category:he.SettingCategories.Parsing,description:'These timezone formats are appended to each "extraDateTimeFormats" template to try to capture the timezone offset. Note that ZZZZ and ZZZZZ are not supported for parsing. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>P.DefaultTimezoneSuffixes}),fuzzyDateParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new oe.IntegerSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is less than this value, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nFor what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ), and KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:ae.MinValidYear}),maxValidFutureMs:new ne.DurationSetting({category:he.SettingCategories.Parsing,description:"If PhotoStructure encounters a year that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),useStatToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths.',defaultValue:!0}),useLibraryDirsToInferDates:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".tz\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:"We always look at {@link Tags.TimeZone}, {@link Tags.OffsetTime}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new Z.BooleanSetting({category:he.SettingCategories.Parsing,description:'This setting has been replaced by the "siblingInference" setting. "true" is equivalent to "auto", and "false" is equivalent to "never".',defaultValue:!0,deprecated:!0}),siblingInference:new me.StringEnumSetting({category:he.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time, Make, or Model isn\'t found in metadata, PhotoStructure will try to use nearby files to "fill in the blanks." If this is set to "auto", this is disabled automatically for slow directories. If this is set to "always", even files in slow directories will have tag inference, when necessary. Set to "never" to disable.',strEnum:ye.TagInferenceSettingValues,defaultValue:ye.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new se.FloatSetting({category:he.SettingCategories.Filters,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new Q.BoundedIntegerSetting({category:he.SettingCategories.Filters,description:"What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),recountAllTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should all tags be recounted? PhotoStructure normally only recounts tags that have had assets recently added or removed, unless there are more than 20 changed tags.",defaultValue:!1,transient:!0}),tagCamera:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure tag assets with the full lens model (like "Canon EF-M 15-45mm f/3.5-6.3 IS STM") or a just the lens information ("15-45mm f/3.5-6.3")? (If you change this value, you\'ll need to "Rebuild" your library to make the setting take effect).',defaultValue:!0}),tagYMD:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'Should assets be tagged with "When > Year" (the "y" option), or "When > Year > Month" (the "ym" option), or "When > Year > Month > Day" (the "ymd" option)? Setting this to "" will disable date tagging.',defaultValue:R.DateTagFormats.ym,strEnum:R.DateTagFormats}),tagDateFromStat:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should PhotoStructure tag assets with a date if the captured at time was only found in filesystem metadata? Filesystem metadata is not as reliable as EXIF metadata, as it can be changed arbitrarily when files are backed up.",defaultValue:()=>!ve()}),tagKeywordsFromPath:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"PhotoStructure should look in the following tags for keywords. Note that these values are case-sensitive.",defaultValue:()=>["CatalogSets","Categories","HierarchicalSubject","HierarchicalKeywords","KeywordInfo","Keywords","LastKeywordXMP","Subject","TagsList","XPKeywords"]}),keywordReparenting:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:z.KeywordReparentingStrategies.move,strEnum:z.KeywordReparentingStrategies}),rootTagAlbumsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be album names. This is matched case-insensitively.",defaultValue:()=>["Album","Albums","Collection","Collections"]}),rootTagKeywordsAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"List hierarchical tag roots that PhotoStructure should interpret to be keywords. This is matched case-insensitively.",defaultValue:()=>["Keyword","Keywords","Tag","Tags"]}),rootTagWhereAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Where".\nFor example, using default values, "Location/Beach" will be replaced with "Where/Beach". This is matched case-insensitively.',defaultValue:()=>["Geo","Location"]}),rootTagWhoAliases:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoSynonyms"],description:'When hierarchical tag values are found with any of these root names PhotoStructure will replace the root with "Who".\nFor example, using default values, "People/Jane Doe" will be replaced with "Who/Jane Doe" (or "Who/Doe/Jane", if tagNamesFormatter="family/given").\nDigicam uses "People". This is matched case-insensitively.',defaultValue:()=>["Person","People","Face","Faces"]}),keywordDelimiters:new de.OptionalStringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordPathSeparators:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new Z.BooleanSetting({category:he.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoMaxDistanceKm:new se.FloatSetting({category:he.SettingCategories.Tagging,description:'If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.',defaultValue:25}),tagGeoSynonyms:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we\'ll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","City","Location"]}),tagJsonFaces:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Google Takeout provides .json sidecars that may contain the names of the people (or pets) found in the image. Should PhotoStructure import these tags under "Who"?.',defaultValue:!0}),tagFaceRegions:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Picasa and other software supports embedding face names within "RegionInfo.RegionList.Name" metadata. If this setting is enabled, and "RegionInfo.RegionList.Type" is "Face", PhotoStructure will import these tags under "Who".',defaultValue:!0}),whoTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,aliases:["tagWhoNames"],description:'This is a list of tags that will be examined for strings or string arrays. All values associated to these fields will be interpreted as names. Note that "dotted notation" is supported.',defaultValue:["People","PersonInImage","PersonInImageWDetails.PersonName","PersonInImageName","RegionInfoMP.Regions.PersonDisplayName"]}),tagNamesFormatter:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:W.NameTagFormats["as-is"],strEnum:W.NameTagFormats}),tagNamesDefaultFamily:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new me.StringEnumSetting({category:he.SettingCategories.Tagging,description:'How should PhotoStructure parse people\'s names? Note that this setting is only used if "tagNamesFormatter" is set to "family/given". See https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:"western",strEnum:q.NameTagOrders}),tagNamesSurnamePrefixes:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family name prefixes to be considered part of the family name. These are matched case-insensitively. This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>["A","D’","Da","De la","De las","De","Del","Della","Den","Des","Di","Du","La","Las","Le","Li","Lo","Mc","Mac","op de","St.","ten","ter","Van ‘t","van de","van der","van","von der","von","z","zu"]}),tagNamesSurnames:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all family names you expect in tags that are not single words that are found at the end of a tagged name. Hyphenated family names (like "Ocasio-Cortez") do not need to be listed here: only compound family names, and if your language doesn\'t separate family names with whitespace. In the latter case, either include all family names, or include all givenNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesGiven:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'List all given names you expect in tags that are not single words. Hyphenated given names (like "Rose-Ann") do not need to be listed here. If your language doesn\'t separate family names and given names with whitespace, either include all given names, or include all familyNames (whatever\'s easier for you). This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:()=>[]}),tagNamesFamilySurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added as a family name. As an example, if you use the default "()", then "Michelle LaVaughn (Robinson) Obama" will be name tagged with both "Who/Robinson/Michelle LaVaughn" and "Who/Obama/Michell LaVaugn". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["()"]}),tagNamesGivenSurrounds:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'This setting contains pairs of characters. When name portions are surrounded by these pairs, the contents will be added to the end of the given name with the surrounds retained. As an example, if you use the defaults of "[]" and double-quotes, then "Joe "Joey" Smith" will be name tagged with Who/Smith/Joe "Joey". This setting is used by the "tagNamesFormatter" if it is set to "family/given".',defaultValue:["[]",'""']}),tagNamesLexical:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Assume any name with a comma is in "lexical name order", which is always "lastname, given name(s)". If the given name is found to be "sr.", "senior", "jr.", or "junior", the name will be considered to be in western order ($givenNames $familyName, $modifier), and the $modifier will be added to the $givenNames. If this is set to false, commas are ignored.',defaultValue:!0}),excludedRootTags:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:"Keywords starting with the given roots will be omitted from your PhotoStructure library. Changing this value requires a library rebuild.",defaultValue:()=>["http:","https:","file:"]}),tagDisplayNameFS:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'What should PhotoStructure call the "root" tag for browsing by filesystem paths? Note that this value is only for the UI, and will update the "_displayName" of the /fs/ tag: this value won\'t change the URL path from be "/tag/fs/.../". Reasonable options that have been suggested include "Folder", "Directory", "Drive", "File", "Path", "Volume", or "Computer".',defaultValue:"Folder"}),tagDisplayNameFSRoot:new pe.StringSetting({category:he.SettingCategories.Tagging,description:'On POSIX systems, how should PhotoStructure reference the "root" directory (/)? "/" is a bit confusing, so "root" may be less confusing? Also see "tagDisplayNameFSRootWithHostname".',defaultValue:"root"}),tagDisplayNameFSRootWithHostname:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!ve()||!(0,F.isDocker)()}),tagDisplayNameFSLabels:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'Should PhotoStructure use volume labels, if available, as display names for filesystem tags? As an example, instead of showing "Folder / D:", you\'d see "Folder / Photo backup #3" (or whatever the label D: has).',defaultValue:!0}),tagAlbumFilenames:new fe.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:he.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'If true, album titles will be split as hierarchical keywords. If false, album titles will not be split, and all albums will be under the "Albums" root tag.',defaultValue:!0}),tagAlbumDescription:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["Notes","albumData.description"]}),tagAlbumDate:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'If you have enabled "tagAlbumFromJson", what\'s the name of the field encoded in the album file? Object hierarchies are separated with a ".".',defaultValue:["albumData.date"]}),tagAlbumsExcluded:new fe.StringArraySetting({category:he.SettingCategories.Tagging,description:'For "metadata.json" albums, some are automatically generated. If the title or description includes any of these strings, it will be ignored.',defaultValue:["Album for automatically uploaded content"]}),omitAncestorTags:new Z.BooleanSetting({category:he.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0}),subscriptionTimeoutMs:new ne.DurationSetting({category:he.SettingCategories.Subscriptions,description:"How long can PhotoStructure spend trying to gather system metadata and validating subscription licenses? This is fairly short, as the user is presumably waiting for PhotoStructure to spin up. If you have a slow system, you may want to increase this value.",defaultValue:()=>"7s"}),pickPlanOnWelcome:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'If set to true, the welcome page flow will redirect to https://account.photostructure.com/plans to have you pick between a "PLUS" and "LITE" plan. If set to false, the welcome page will continue directly to the settings page with a "LITE" plan. You can still upgrade to a paid plan later from the main menu or the about page, even if this is false.',defaultValue:!0}),coupon:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,description:"Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new Z.BooleanSetting({category:he.SettingCategories.Subscriptions,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new de.OptionalStringSetting({category:he.SettingCategories.Subscriptions,sensitive:!0,description:'Subscription licenses are normally saved automatically into both your library and system configuration directories. This setting just provides users with an alternative way to provide a license, if it\'s more convenient. Any value provided to this setting will be considered in addition to existing license files when PhotoStructure is trying to find the "best" license available.'})};for(const[e,r]of(0,h.entries)(t.Settings))r._setName(e);function be(e){const r=((0,u.blank)(e)?"":e).split(s.delimiter);return(0,F.isDocker)()&&r.unshift("/opt/photostructure/tools/bin"),r.push(...t.Settings.toolPaths.valueOrDefault),(0,a.uniq)(r).filter(u.notBlank).join(s.delimiter)}function Pe(e){return["system"===e.categoryType?0:1,he.SettingCategories.indexOf(e.category)??he.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.withDefaultPaths=be,t.pathWithDefaults=(0,o.lazy)((()=>be((0,D.getEnv)("PATH")))),t.allSettings=(0,o.lazy)((()=>(0,l.sortBy)((0,h.values)(t.Settings),Pe))),t.persistedSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>!e.transient)))),t.transientSettings=(0,o.lazy)((()=>(0,t.allSettings)().filter((e=>e.transient)))),t.persistedSystemSettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.SystemCategories.includes(e.category))))),t.persistedLibrarySettings=(0,o.lazy)((()=>(0,t.persistedSettings)().filter((e=>he.LibraryCategories.includes(e.category)))));const _e=(0,o.lazy)((()=>{const e=new y.CaseInsensitiveMap;for(const r of(0,t.persistedSettings)()){for(const t of r.names)e.set(t,r);for(const t of r.keys)e.set(t,r)}return e}));t.getSettingByNameOrKey=function(e){return _e().get((0,g.toS)(e).toLowerCase())},t.ciSettings=(0,o.lazy)((()=>new v.CaseInsensitiveValued(t.Settings,((e,t)=>[...t.names,...t.keys]))))},41692:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const i=r(19851),n=r(31586),s=r(7282),o=r(49776),a=r(46292),l=r(32774),u=r(55086),c=r(46296),d=r(55939),h=r(96706),f=r(83278),m=r(92234),g=r(45969),p=r(60865),y=r(30933),v=r(15674),w=r(28874);t.setSettingsDefaults=(0,i.lazy)((()=>{w.Settings.configDir.opts.defaultValue=a.configDir,w.Settings.logDir.opts.defaultValue=c.defaultLogDir_,w.Settings.logServerLevel.opts.defaultValue=()=>w.Settings.logLevel.valueOrDefault,w.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,w.Settings.toolPaths.opts.defaultValue=()=>(0,h.isEnvTrue)("SETTINGS_IO_TEST")?m.DefaultPosixPaths:m.DefaultPaths,w.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,g.isDocker)()?l.DefaultDockerLibraryDir:(0,s.isTest)()?"/home/test/Pictures":(0,d.defaultPicturesDir)(),w.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,w.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,w.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],w.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,v.maxCpus)()/4)),w.Settings.useFsWatch.watch(f.useFsWatch),w.Settings.updateChannel.opts.defaultValue=p.channel,w.Settings.minBusyPct.opts.defaultValue=()=>(0,n.sigFigs)(50/(0,y.cpuCount)(),2)}))},84438:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},58305:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=t.splitStringArray=t._join=void 0;const i=r(76760),n=r(40958),s=r(22573),o=r(98553),a=r(55835),l=r(59455),u=r(19851),c=r(83179);function d(e){return null==e?void 0:(0,o.stringify)(e)}t._join=d;function h(e){return(0,a.map)(function(e){const t=(0,s.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,n.compact)((0,l.toA)(JSON.parse(t)).map(s.notBlankToS))}catch{}for(const e of["¦",i.delimiter])if(t.includes(e))return(0,n.compactBlankish)(t.split(e));return[t]}}(e),n.compactBlankish)}t.splitStringArray=h;class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.synonymMap=(0,u.lazy)((()=>{const e=new Map;for(const t of this.values){const r=t.split("|");for(const t of r)e.set(t,r)}return e})),this.watchLater((()=>{this.synonymMap.clear()}))}toValidValue(e){return(0,s.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,n.uniq)(e.map((e=>this.toValidValue(e))))}push(...e){(0,n.isEmpty)(e)||(this.value=this.toValidValues((0,n.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}isEmpty(){return(0,n.isEmpty)(this.values)}isNotEmpty(){return(0,n.isNotEmpty)(this.values)}toNotEmpty(){return(0,n.toNotEmpty)((0,n.compactBlanks)(this.values))}}t.StringArraySetting=f},57571:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const i=r(83179);class n extends i.Setting{constructor(e){super({toEnv:t=>e.strEnum.getCI(t),fromEnv:t=>e.strEnum.getCI(t),...e}),this.strEnum=e.strEnum;const t=this.defaultValue;if(!this.strEnum.has(t))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumSetting=n},72564:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const i=r(40958),n=r(98553),s=r(55835),o=r(58305);class a extends o.StringArraySetting{constructor(e){super({toEnv:e=>(0,s.map)(e,(e=>(0,n.stringify)((0,i.uniq)(e)))),fromEnv:t=>{return r=t,n=e.strEnum,(0,i.compact)((0,o.splitStringArray)(r)?.map((e=>n.getCI(e))));var r,n},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}toValidValue(e){return this.strEnum.getCI(e)}addToJSON(){return{"valid values":this.strEnum.values}}}t.StringEnumsSetting=a},80372:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const i=r(22573),n=r(81168),s=r(83179);class o extends s.Setting{constructor(e){super({toEnv:a,fromEnv:a,...e})}hasValue(){return(0,i.notBlank)(this.value)}}function a(e){return null==e?void 0:(0,n.trimQuotes)(e)}t.StringSetting=o},32707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=void 0;const i=r(76760),n=r(55835),s=r(46292),o=r(84438);t.systemSettingsFile=function(){return(0,n.map)((0,s.configDir)(),(e=>(0,i.join)(e,o.SettingsToml)))}},80496:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const i=r(50989);t.TagInferenceSettingValues=(0,i.strEnum)("never","always","auto")},6707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeTomlFile_=t.readTomlFile_=t.readTomlFileSync=void 0;const i=r(90858),n=r(44652),s=r(22573),o=r(76850),a=r(50213),l=r(81168),u=r(84542),c=r(17217),d=r(68284),h=r(98778);function f(e){return t=(0,o.debom)(e),(0,s.blank)(t)?void 0:(0,i.parse)((0,l.dumbquote)(t));var t}t.readTomlFileSync=function(e){const t=(0,s.mapNotBlank)(e,c.toNativePath_);if(null!=t)try{return(0,d.isFileSync)(t)?f((0,n.readFileSync)(t)):void 0}catch(e){return void(0,a.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,s.mapNotBlank)(e,(async e=>f(await(0,n.readFile)((0,c.toNativePath_)(e)))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,c.toNativePath_)(e),(0,u.joinLines)(...(0,h.stringifyToml)(t)))}},98778:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapTomlToLines=t.kvToToml=t.stringifyToml=void 0;const i=r(22573),n=r(96249),s=r(98553),o=r(68708),a=r(51926);function l(e,t,r){if((0,i.blank)(e))throw new Error("kvToToml(): Blank key");const n=e+" = "+(0,s.stringifyPretty)(t);return(0,i.blank)(r?.prefix)?[n]:(0,a.wrap)(n.split("\n"),r)}t.stringifyToml=function(e){return(0,n.flatten)((0,o.entries)(e).map((([e,t])=>l(e,t))))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,i.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,a.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines}},10357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},65162:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bname=void 0;const i=r(4001),n=r(81168);t.bname=function(e,t=!0){let r=(0,n.isString)(e)?e:e.name;return t&&(r=(0,i.stripCopySuffixFromName)(r)),r=(0,n.trimLeftPadding)((0,i.stripDSC)(r)),r.toLowerCase().normalize()}},70379:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const i=r(50989);t.DateTagFormats=(0,i.strEnum)("y","ym","ymd","")},71300:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultCapturedAtTagsConst=t.ProblematicCapturedAtTags=t.OverrideUTCZoneTags=t.IgnoredCapturedAtTags=void 0,t.IgnoredCapturedAtTags=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.ProblematicCapturedAtTags=["SubSecCreateDate","SubSecMediaCreateDate","SubSecModifyDate","CreateDate","MediaCreateDate","ModifyDate","DateTime","DateTimeCreated","photoTakenTime","TrackCreateDate","CreationTime",...t.OverrideUTCZoneTags],t.DefaultCapturedAtTagsConst=["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","DateTimeDigitized","OriginalCreateDateTime","DigitalCreationDateTime"]},33209:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},68268:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const i=r(50989);t.KeywordReparentingStrategies=(0,i.strEnum)("move","copy","retain")},61208:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const i=r(50989);t.NameTagFormats=(0,i.strEnum)("as-is","family/given","family/fullname")},99023:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const i=r(50989);t.NameTagOrders=(0,i.strEnum)("western","eastern")},60865:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=t.channel=void 0;const i=r(37805),n=r(30577);t.channel=function(){return(0,n.extractUpdateChannel)(i.version)},t.baseVersion=()=>[i.versionMajor,i.versionMinor,i.versionPatch].join("."),t.versionMajorMinor=i.versionMajor+"."+i.versionMinor},30577:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eligibleForChannel=t.extractUpdateChannel=t.UpdateChannels=void 0;const i=r(50989);t.UpdateChannels=(0,i.strEnum)("prealpha","alpha","beta","stable"),t.extractUpdateChannel=function(e){for(const r of t.UpdateChannels.values)if(e.includes("-"+r))return r;return t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))}},1485:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedLinuxMountpointNames=t.defaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxMountpointPaths=t.DefaultExcludedLinuxRoots=void 0;const i=r(45969);t.DefaultExcludedLinuxRoots=["boot","efi","etc","lib","proc","snap","sys","tmp"],t.DefaultExcludedLinuxMountpointPaths=["/dev/shm","/run","/run/lock","/run/qemu","/run/snapd/ns","/tmp","/var/tmp"],t.defaultExcludedLinuxMountpointPaths=function(){return[...(0,i.isDocker)()?["/"]:[],...t.DefaultExcludedLinuxMountpointPaths]},t.DefaultExcludedLinuxMountpointNames=["#snapshot"]},19861:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultExcludedFilesystemTypes=void 0,t.DefaultExcludedFilesystemTypes=["cgmfs","cgroup","debugfs","devfs","devtmpfs","sunrpc","sysfs","tracefs","udev"]},69375:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.whyExcludedMountpoint=t.isExcludedMountpoint=t.isExcludedFilesystem=void 0;const i=r(19851),n=r(22573),s=r(50213),o=r(9103),a=r(7282),l=r(29882),u=r(43334),c=r(28874),d=(0,i.lazy)((()=>(0,s.mkLogger)("volumes.PosixVolumes")));t.isExcludedFilesystem=function(e){return!(0,n.blank)(e)&&u.isPosix&&c.Settings.excludedFilesystemTypes.values.includes(e)};const h=u.isLinux||(0,a.isTest)()?/^\/dev(?!\/mapper)(?:\/|\/?$)/i:void 0,f=u.isLinux||(0,a.isTest)()?/^\/var\/snap(?:$|\/)/:void 0,m=u.isLinux||(0,a.isTest)()?/^\/run\/user\/\d+\/gvfs\/.+$/i:void 0,g=u.isLinux||(0,a.isTest)()?/^\/var\/lib\//:void 0;function p(e){if((0,n.blank)(e))return"blank";const t=(0,l.toPathnames)(e),r=t[0],i=t[t.length-1];return c.Settings.excludedRootDirectories.has(r)?"ExcludedRootDirectory":c.Settings.excludedMountpointPaths.has(e)?"excludedMountpointPaths":c.Settings.excludedMountpointBasenames.has(i)?"excludedMountpointBasenames":!0===h?.test(e)?"LinuxDevMapperRE":!0===f?.test(e)?"LinuxVarSnapRE":"run"===r&&!1===m?.test(e)?"LinuxRunRE":!0===g?.test(e)?"LinuxDockerRE":void 0}t.isExcludedMountpoint=(0,o.memoize)((e=>{if(u.isWin)return!1;const t=p(e);return d().tap({msg:"isExcludedMountpoint",result:null!=t,meta:{mountpoint:e,why:t}})}),{maxSize:512}),t.whyExcludedMountpoint=p},63870:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=t.commandTimeoutMs=t.volumeMetadataTtlMs=t.mountpointsTtlMs=void 0;const i=r(42659),n=r(12168),s=r(28874);t.mountpointsTtlMs=function(){return s.Settings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return s.Settings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return s.Settings.statTimeoutMs.valueOrDefault},t.MinIoRate=n.MiB/i.secondMs},55111:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const i=r(50989);t.HelmetPlugins=(0,i.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},30933:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const n=i(r(48161)),s=r(19851),o=r(42659),a=r(31586),l=r(50213),u=r(28874),c=(0,s.lazy)((()=>(0,l.mkLogger)("work.CpuInfo")));t.cpuInfo=(0,s.lazy)((()=>n.default.cpus()),5*o.minuteMs),t.cpuCount=(0,s.lazy)((()=>{try{if(u.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=n.default.availableParallelism?.(),r=(0,t.cpuInfo)().length;return c().tap({msg:"cpuCount()",result:(0,a.clamp)(1,128,Math.ceil(e??r)),meta:{availableParallelism:e,cpuInfoLength:r}})}catch(e){return c().warn("availableParallelism()/cpuCount() failed",{error:e}),1}}))},58444:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const n=i(r(48161)),s=r(19851),o=r(31586),a=r(12168),l=r(50213),u=r(45879),c=r(70417),d=r(45969),h=(0,s.lazy)((()=>(0,l.mkLogger)("work.FreeMem")));t.estimatedFreeMem=(0,s.lazy)((()=>{const e=n.default.freemem(),t=n.default.totalmem(),r=(2*e+t)/3;if((0,d.isDocker)()){const i=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,o.gt0)(i))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([i,r]),meta:{freemem:e,totalmem:t,cgroupMem:i}})}return h().tap({msg:"estimatedFreeMem() ",result:r,meta:{result:(0,a.fmtBytes)(r),freemem:(0,a.fmtBytes)(e),totalmem:(0,a.fmtBytes)(t)}})}))},15674:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sharpThreadsPerProcess=t.maxConcurrentImports=t.maxCpus=t.singleThreadedMode=t.targetCpuLoadPct=t.timeoutPenalization=t.clearMaxWorkCaches=void 0;const i=r(19851),n=r(42659),s=r(41400),o=r(31586),a=r(12168),l=r(50213),u=r(7282),c=r(34102),d=r(57902),h=r(28874),f=r(30933),m=r(58444),g=r(22751),p=(0,i.lazy)((()=>(0,l.mkLogger)("work.MaxCpus")));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),g.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,s.later)((()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",(()=>y())),(0,c.ee)().on("settingsChanged",y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)})),t.clearMaxWorkCaches=y;const v=(0,i.lazy)((()=>{const e=(0,o.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*a.MB;return p().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/a.MB),worstCaseMemPerProcMb:Math.ceil(e/a.MB)}})}),n.minuteMs);function w(){const e=Math.round(g.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,r=0===e||0===t?1:(0,o.sigFigs)(t/e,2);return p().tap({msg:"timeoutPenalization()",level:r>1?d.LogLevels.warn:d.LogLevels.debug,result:r,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function S(){return((0,o.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.timeoutPenalization=w,t.targetCpuLoadPct=S,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()||Math.round(S()*(0,f.cpuCount)())<=1},t.maxCpus=(0,i.lazy)((function(){if(h.Settings.cpuBusyPercent.valueOrDefault<=0)return 1;const e=Math.max(1,Math.floor(S()*(0,f.cpuCount)())-1);let t=e;const r=g.timeoutRate.prior()?.eventsPerMinute??0,i=w();if(1!==i){const e=t;t*=i,p().warn("Recent timeouts! Throttling down.",{penalization:i,resultBeforePenalization:e,resultAfterPenalization:t})}const n=Math.min(e,v());return t=(0,o.clamp)(1,n,Math.floor(t)),p().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:S(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:i,timeoutsPerSecond:r,maxProcsForMem:v()}})})),t.maxConcurrentImports=(0,i.lazy)((function(){return(0,o.gt0)(h.Settings.maxConcurrentImports.valueOrDefault)?(0,o.clamp)(1,(0,t.maxCpus)(),h.Settings.maxConcurrentImports.valueOrDefault):Math.ceil(.8*(0,t.maxCpus)())})),t.sharpThreadsPerProcess=function(){const e=h.Settings.sharpThreadsPerProcess.valueOrDefault;return e>0?e:(0,o.clamp)(1,Math.min((0,t.maxCpus)(),h.Settings.sharpThreadsPerProcess.max),Math.round((0,t.maxCpus)()/4))}},22751:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onTimeout=t.timeoutRate=void 0;const i=r(58587),n=r(87997),s=r(19851),o=r(42659),a=r(41400),l=r(50213),u=r(7282),c=r(45255),d=r(34102),h=r(976),f=r(15674),m=(0,s.lazy)((()=>(0,l.mkLogger)("work.WorkTimeout")));t.timeoutRate=(0,s.lazy)((()=>new i.Rate(5*o.minuteMs,(0,u.isTest)()?100:c.ShortCommandTimeoutMs)));const g=(0,s.lazy)((()=>(0,n.setInterval)(p,o.minuteMs).unref()));function p(){f.maxCpus.refresh(),f.maxConcurrentImports.refresh(),g()}t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),m().warn("onTimeout()",(0,h.rateStats)(e)),p()},(0,a.later)((()=>{(0,d.ee)().on("clearCache",(()=>{f.maxCpus.unset(),f.maxConcurrentImports.unset(),t.timeoutRate.unset()}))}))},40958:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndexes=t.arrayEndsWith=t.arrToIterator=t.commaList=t.last=t.diff=t.primitiveValueOfOrElse=t.stepRange=t.range=t.anneal=t.commonPrefixLength=t.firstMatch=t.sum=t.count=t.clear=t.uniqBy2=t.uniqByLast=t.uniqBy=t.uniqSubstrings=t.uniqFirst=t.uniq=t.compactBlankish=t.compactBlanks=t.compact=t.removeSame=t.remove=t.insertUniq=t.insertAt=t.pushUniqBy=t.pushUniq=t.eqlPrimitiveUnordered=t.includesAll=t.includesAny=t.indexOfPrimitive=t.indexOf=t.includes=t.flatMap=t.move=t.filterInPlaceAsync=t.filterInPlace=t.startsWith=t.toPrimitive=t.mapNotEmptyOr=t.mapNotEmpty=t.mapArray=t.isEmpty=t.notEmptyOr=t.toNotEmpty=t.isNotEmpty=void 0;const i=r(76790),n=r(22573),s=r(50357),o=r(98553),a=r(49769),l=r(34666),u=r(30976),c=r(42279),d=r(32639),h=r(59455),f=r(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function g(e){return null==e||0===(0,h.toA)(e).length}function p(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every(((e,r)=>e===t[r]))}function v(e,t){for(let r=0;r=e.length||r>=e.length)return e;const i=e[t];return e.splice(t,1),e.splice(r,0,i),e}function S(e){return null==e?[]:v((0,h.toA)(e),(e=>null!=e))}function b(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&(0,a.getOrSet)(r,e,(()=>i))}return[...r.values()]}function P(e,t,r=1,i=(e=>e)){const n=[];if(et;s-=r)n.push(i(s));return n}t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=g,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,r){return m(e)?t(e):(0,c.tot)(r)},t.toPrimitive=p,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let r=0;rt.includes(e)))},t.includesAll=function(e,t){if(g(e)||g(t))return!1;for(const r of t)if(!e.includes(r))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const r=(0,i.sortBy)(e,p),n=(0,i.sortBy)(t,p);return r.every(((e,t)=>e===n[t]))},t.pushUniq=function(e,...t){for(const r of t)null==r||e.some((e=>(0,s.eql)(e,r)))||e.push(r);return e},t.pushUniqBy=function(e,t,r){const i=e.map(r);for(const n of t){const t=r(n);i.includes(t)||(e.push(n),i.push(t))}return e},t.insertAt=function(e,t,...r){return e.splice(t,0,...r),e},t.insertUniq=function(e,t,r){for(let t=0;t0)throw new Error("badly sorted array: "+e);for(let i=0;i0)return e.splice(i,0,t),e}return e.push(t),e},t.remove=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>!(0,s.eql)(e,t))))),r!==e.length},t.removeSame=function(e,...t){const r=e.length;return v(e,(e=>t.every((t=>e!==t)))),r!==e.length},t.compact=S,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map((e=>(0,f.toS)(e).trim())).filter((e=>e.length>0))},t.compactBlankish=function(e){return null==e?[]:[...e].filter(n.notBlankish)},t.uniq=function(e){if(null==e)return[];const t=S(e);if(t.length<=1)return t;if(t.length<10){const e=t[0];if(t.every((t=>t===e)))return[e]}return b(t,(e=>(0,l.isPrimitive)(e)?e:(0,o.stringify)(e)))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const r of e)null==r||(0,s.eql)(t[t.length-1],r)||t.push(r);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=S(e);if(0===e.length)return[];const r=[];for(const e of(0,i.sortBy)(t,(e=>[-e.length,e.toLowerCase()])))r.some((t=>t.includes(e)))||r.push(e);return(0,i.sortBy)(r,(e=>t.indexOf(e)))},t.uniqBy=b,t.uniqByLast=function(e,t=(e=>(0,o.stringify)(e))){const r=new Map;for(const i of e)if(null!=i){const e=t(i);null!=e&&r.set(e,i)}return[...r.values()]},t.uniqBy2=function(e,t){const r=[];for(const i of e)null!=i&&r.every((e=>!t(i,e)))&&r.push(i);return r},t.clear=function(e){return e.length=0,e},t.count=function(e,t){return e.reduce(((e,r,i)=>e+(t(r,i)?1:0)),0)},t.sum=function(e,t){return e.reduce(((e,r,i)=>e+t(r,i)),0)},t.firstMatch=function(e,t){for(const r of S(t)){const t=e.exec(r);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let r=0;for(;e[r]===t[r];)r++;return r},t.anneal=function({array:e,expense:t,allowedDelta:r}){const i=Math.round(r);if(i<2)return e;for(let r=0;re)){return P(e,t,1,r)},t.stepRange=P,t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,o.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))},t.diff=function(e,r,i=t.primitiveValueOfOrElse){const n=new Set(r.map(i));return e.filter((e=>!n.has(i(e))))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=void 0,t.copyArrayTo=function(e,t){for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.pushSorted=t.deepSortBy=t.sortBy=t.sortedBy=t.isSorted=t.sortUniqByInPlace=t.sortUniq=t.sortUniqBy=t.sortByInPlace=t.sort=void 0;const i=r(40958),n=r(36783),s=r(41801),o=r(98553),a=r(49769),l=r(55835),u=r(34666),c=r(59455);function d(e,t){return(0,n.copyArrayTo)(f(e,t),e)}function h(e,t){const r=new Map;for(const i of e)(0,a.getOrSet)(r,(0,o.stringify)(t(i)),(()=>i));return f(r.values(),t)}function f(e,t){return(0,c.toA)(e).filter((e=>null!=e)).map(((e,r)=>({item:e,cmp:(0,l.map)(t(e,r),(e=>[e,r]))}))).filter((e=>null!=e.cmp)).sort(((e,t)=>(0,u.cmp)(e.cmp,t.cmp))).map((e=>e.item))}t.sort=function(e){return d((0,i.compact)(e),i.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,(e=>e))},t.sortUniqByInPlace=function(e,t){return(0,n.copyArrayTo)(h(e,t),e)},t.isSorted=function(e){return e.every(((t,r)=>0===r||t>=e[r-1]))},t.sortedBy=function(e,t){return e.every(((r,i)=>0===i||t(r)>=t(e[i-1])))},t.sortBy=f,t.deepSortBy=function e(t,r){return f(t,r).map((t=>(0,s.isIterable)(t)?e(t,r):t))},t.pushSorted=function(e,t,r){const i=e.findIndex((e=>r(t){Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=void 0;const i=r(32639);t.asPromise=async function(e){const t=await e;return(0,i.isFunction)(t)?t():t}},5233:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=void 0;const i=r(41400),n=r(31586),s=r(13538),o=r(41583);t.retryOnReject_=async function(e,t){const r=(0,n.gt0)(t.timeoutMs)?()=>(0,s.thenOrTimeoutError)(e(),t.timeoutMs):e;if(t.maxRetries<=0)return r();const a=t.onRetryWaitUntil??(e=>(0,i.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let l=0;const u=async()=>{try{return await r()}catch(e){const r=(0,o.toErr)(e);if(!1===t.errorIsRetriable?.(r)||l>t.maxRetries)throw r;return l++,await a(l),u()}};return u()}},17586:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.at=void 0,t.at=function(e,t){if(null!=e&&((t=Math.trunc(t)||0)<0&&(t+=e.length),!(t<0||t>=e.length)))return e[t]}},22573:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notBlankish=t.blankish=t.firstNotBlank=t.mapNotBlankOr=t.mapNotBlank=t.notBlankAnd=t.notBlankOr=t.toNotBlank=t.notBlankToS=t.notBlank=t.blank=void 0;const i=r(55835),n=r(42279),s=r(54993);function o(e){return null==e||""===e||"string"==typeof e&&""===e.trim()}function a(e){return!o(e)}function l(e,t){if(!1===e||null==e||""===e)return;const r=(0,s.toS)(e);return a(r)?t(r):void 0}t.blank=o,t.notBlank=a,t.notBlankToS=function(e){return a(e)&&"undefined"!==e?(0,s.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,s.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,n.tot)(t);const r=(0,s.toS)(e).trim();return r.length>0?r:(0,n.tot)(t)},t.notBlankAnd=function(e,t){return!o(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,r){return(0,i.orElse)(l(e,t),r)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t};const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,s.toS)(e))}t.blankish=c,t.notBlankish=function(e){return!c(e)}},38639:(e,t)=>{function r(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function i(e,...t){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const r=String(e).toLowerCase();return["false","0",...t].map((e=>e.toLowerCase())).includes(r)}Object.defineProperty(t,"__esModule",{value:!0}),t.mapTrue=t.mapBoolean=t.maybeAnd=t.and=t.or=t.isDisabled=t.isFalse=t.boolToInt=t.toNotBoolean=t.toBoolean=t.isTrue=t.isBoolean=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=r,t.toBoolean=function(e){return!!r(e)||!i(e)&&void 0},t.toNotBoolean=function(e){return!r(e)&&(!!i(e)||void 0)},t.boolToInt=function(e){return r(e)?1:0},t.isFalse=i,t.isDisabled=function(e){return i(e,"no","disable","disabled")},t.or=function(e){return e.some((e=>r(e)))},t.and=function(e){return e.every((e=>r(e)))},t.maybeAnd=function(e){let t;for(const r of e){if(!1===r)return!1;!0===r&&(t=!0)}return t},t.mapBoolean=function(e,t){return r(e)?t(!0):i(e)?t(!1):void 0},t.mapTrue=function(e,t){return r(e)?t():void 0}},79666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shallowClone=t.clone=void 0;const i=r(98553);t.clone=function(e){return null==e?e:JSON.parse((0,i.stringify)(e))},t.shallowClone=function(e){return Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e}},42659:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtElapsedMs=t.fmtAgo=t.msUntilMidnight=t.nextMidnightTs=t.fmtLocalToShort=t.localToDate=t.fmtIsoDate=t.fmtIsoDuration=t.fmtHMS=t.fmtYMDHMS=t.unixtime=t.hence=t.ago=t.thisYear=t.isDate=t.splitHMS=t.fmtDateShort=t.toDate=t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0;const i=r(40958),n=r(22573),s=r(30301),o=r(55835),a=r(31586),l=r(39926),u=r(51926),c=r(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}))),h=(0,s.lazy)((()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})));function f(e){return e instanceof Date?e:new Date(e)}function m(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function g(e){return e instanceof Date}function p(e,t){return new Date((t?.getTime()??Date.now())-e)}t.toDate=f,t.fmtDateShort=m,t.splitHMS=function(e){return(0,o.mapOr)(/^[0:]{1,4}/.exec(e),(t=>[t[0],e.slice(t[0].length)]),(()=>["",e]))},t.isDate=g,t.thisYear=function(){return(new Date).getFullYear()},t.ago=p,t.hence=function(e,t){return p(-e,t)},t.unixtime=function(e){const r=g(e)?e.getTime():(0,a.isNumber)(e)?e:Date.now();return Math.floor(r/t.secondMs)},t.fmtYMDHMS=function(e){const t=f(e);return t.getFullYear()+(0,l.pad2)(t.getMonth()+1)+(0,l.pad2)(t.getDate())+(0,l.pad2)(t.getHours())+(0,l.pad2)(t.getMinutes())+(0,l.pad2)(t.getSeconds())},t.fmtHMS=function(e,r={includeMs:!0}){const i=Math.floor(e/t.hourMs);e-=i*t.hourMs;const n=Math.floor(e/t.minuteMs);e-=n*t.minuteMs;const s=Math.floor(e/t.secondMs),o=Math.floor(e-s*t.secondMs);return(0,l.pad2)(i)+":"+(0,l.pad2)(n)+":"+(0,l.pad2)(s)+(r.includeMs?"."+(0,l.pad3)(o):"")};const y=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function v(e){if(null==e||e<0)return;let t=e;const r=()=>{const e=t%100;return t=Math.floor(t/100),e},i=10*r(),n=r(),s=r(),o=r(),a=r(),l=r();return new Date(t,l-1,a,o,s,n,i)}function w(){return(new Date).setHours(24,0,0,0)}function S(e,r="ago"){return e<1e3?"just now":(r=(0,n.blank)(r)?"":(0,u.ensurePrefix)(r," "),et.ms<=e)))){const s=Math.floor(e/i.ms);e-=s*i.ms,s>0&&(i.ms>=t.dayMs?r:n).push(s+i.s)}return e>0&&n.push((0,a.toFixedStr)(e/t.secondMs,3)+"S"),"P"+r.join("")+((0,i.isEmpty)(n)?"":"T"+n.join(""))},t.fmtIsoDate=function(e){const t=g(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=v,t.fmtLocalToShort=function(e){return(0,o.map)(v(e),m)},t.nextMidnightTs=w,t.msUntilMidnight=function(){return w()-Date.now()},t.fmtAgo=function(e,t="ago"){return S(Date.now()-e,t)},t.fmtElapsedMs=S},95892:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateToJson=void 0,t.dateToJson=function(e){return{_ctor:Date.name,iso:e.toISOString()}}},12487:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=void 0;const i=r(38639),n=r(73872);function s(e,t,r){if(null==r||y(e)||y(t))return null;const i=r.get(e)?.get(t);return"boolean"==typeof i?i:null}function o(e,t,r,i){if(null==r||y(e)||y(t))return;let n=r.get(e);null!=n?n.set(t,i):(n=new WeakMap,n.set(t,i),r.set(e,n))}function a(e,t,r,i){if(null!=r?.comparator)return u(e,t,r,i);const n=l(e,t);return null!==n?n:u(e,t,r)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,r,i){r??(r={});const u=!1===r.memoize?void 0:r.memoize??(r.memoize=new WeakMap),d=r?.comparator,f=s(e,t,u);if(null!==f)return f;const m=s(t,e,u);if(null!==m)return m;if(d){const r=d(e,t,i);if(!1===r||!0===r)return o(e,t,u,r),r;const n=l(e,t);if(null!==n)return n}const y=n(e);if(y!==n(t))return o(e,t,u,!1),!1;o(e,t,u,!0);const v=function(e,t,r,i){switch(r){case"String":case"Number":case"Boolean":case"Date":return a(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return g(e,t,["name","message","code"],i);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,i);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,r){return c(h(e),h(t),r)}(e,t,i);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),i);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),i);case"Set":case"Map":return function(e,t,r){if(e.size!==t.size)return!1;if(0===e.size)return!0;const i=[],n=[];return e.forEach((function(e,t){i.push([e,t])})),t.forEach((function(e,t){n.push([e,t])})),c(i.sort(),n.sort(),r)}(e,t,i);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return p(e,t,i)}}(e,t,y,r);return o(e,t,u,v),v}function c(e,t,r){const i=e.length;if(i!==t.length)return!1;if(0===i)return!0;let n=-1;for(;++n{Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(e){let t,r,i=!1;const n=function(){if(i){if(null!=r)throw r;return t}try{return i=!0,t=e()}catch(e){throw r=e,e}};return n.prior=()=>t,n.hasPrior=()=>i,n}},41400:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.later=t.delay=t.delayUntil=void 0;const i=r(42659),n=r(35556),s=r(31586),o=r(68708);function a(e,t=!0){return new Promise((r=>{if(e<=0)r();else{const s=setTimeout((()=>r()),Math.ceil(e+.5));e>i.secondMs&&t&&n.isNode&&s.unref?.()}}))}t.delayUntil=function(e){const t=((0,s.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return a(t).then((()=>t))},t.delay=a,t.later=function(e,t=1){const r=Math.max(1,Math.ceil(t)),s=n.isNode&&r<=1?setImmediate(e):setTimeout(e,r);return n.isBrowser||t<=i.secondMs?s:(0,o.maybeCall)(s,"unref")??s}},50357:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setFieldComparator=t.unshiftObjComparator=t.pushObjComparator=t.functionComparator=t.dateComparator=t.eqlSubset=t.eql=void 0;const i=r(12487),n=r(68708),s=r(34666),o=r(32639);function a(e,t){return(0,i.deepEql)(e,t,{comparator:h})}function l(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function u(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}t.eql=a,t.eqlSubset=function(e,t){if(null==e||null==t||(0,s.isPrimitive)(e)||(0,s.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const r of(0,n.keys)(e))if(!a(e[r],t[r]))return!1;return!0},t.dateComparator=l,t.functionComparator=u;const c=[l,u],d=new Map;function h(e,t,r){if(null==e||null==t)return e===t;if(null!=r){const i=d.get(r);if(null!=i)return i(e,t)??null}for(const r of c){const i=r(e,t);if(null!=i)return i}return null}t.pushObjComparator=function(e){c.push(e)},t.unshiftObjComparator=function(e){c.unshift(e)},t.setFieldComparator=function(e,t){d.set(e,t)}},26905:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.errorToS=t.errorToArr=t.errorFromJson=t.errorToJson=t.asError=t.shortStack=t.errorErrno=t.errorCode=t.errorName=t.IgnoredErrorNames=t.ErrorDelimiter=void 0;const i=r(40958),n=r(22573),s=r(96249),o=r(31586),a=r(68708),l=r(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find((e=>null!=e&&!t.IgnoredErrorNames.includes(e)))?.toString()}function c(e){return null==e?void 0:(0,n.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,o.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"],t.errorName=u,t.errorCode=c,t.errorErrno=d;const h=/shortStack|errorToVerbose/;function f(...e){const r=[];for(const t of e)null!=t&&(t instanceof Error?r.push(u(t),c(t),t?.message):r.push((0,l.toS)(t)));return(0,i.uniq)((0,i.compactBlankish)((0,s.flatten)((0,i.compact)(r).map((e=>e.split(t.ErrorDelimiter))))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}t.shortStack=function(e,t=9){try{if((0,n.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const r=(0,l.toS)(e).split("\n").filter((e=>!(0,n.blank)(e)&&e.trim().startsWith("at ")&&null==h.exec(e))).slice(0,t).map((e=>e.replace(/^\s*at /i,"")));return(0,i.isEmpty)(r)?["(missing stack)"]:r}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,n.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map((e=>(0,l.toS)(e))).filter(n.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,a.compactValues)({_ctor:Error.name,message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,a.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,a.assignFields)(new Error,(0,a.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m},96249:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=void 0;const i=r(59455);t.flatten=function(e,t=[]){for(const r of(0,i.toA)(e))if(null!=r)for(const e of(0,i.toA)(r))null!=e&&t.push(e);return t}},57924:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.andList=t.orList=t.fmtList=void 0;const i=r(40958);function n(e,t){return null==(e=(0,i.uniq)((0,i.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}t.fmtList=n,t.orList=function(e){return n(e,"or")},t.andList=function(e){return n(e,"and")}},73722:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const i=r(50989);t.FitSizes=(0,i.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,i.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.countIterable=t.sliceIterable=t.isIterable=void 0;const i=r(31586);t.isIterable=function(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]},t.sliceIterable=function(e,t,r){if((0,i.lt0)(t))return[...e].slice(t,r);const n=e[Symbol.iterator]();if((0,i.gt0)(t))for(let e=0;e{Object.defineProperty(exports,"__esModule",{value:!0}),exports.revive=exports.parseJsonObj=exports.parseJSON=exports.parseJSON_=exports.addJsonRevivers=exports.stringifyPretty=exports.stringify=void 0;const DateToJson_1=__webpack_require__(95892),Error_1=__webpack_require__(26905),Maybe_1=__webpack_require__(55835),isFunction_1=__webpack_require__(32639),toS_1=__webpack_require__(54993);function stringify(e,t,r){return JSON.stringify(decycle(e),t,(0,Maybe_1.denull)(r))}function stringifyPretty(e,t=2){return stringify(e,void 0,t)}exports.stringify=stringify,exports.stringifyPretty=stringifyPretty;const Revivers=new Map;function addJsonRevivers(...e){for(const t of e)Revivers.set(t.name,t)}function parseJSON_(e){return retrocycle(JSON.parse(e,reviver))}function parseJSON(e){try{const t=e?.toString().trim();if(null!=t&&t.length>0)return parseJSON_(t)}catch{}}function parseJsonObj(e){if(null!=e)return 0!==(e=(0,toS_1.toS)(e).trim()).length&&e.startsWith("{")&&e.endsWith("}")?parseJSON(e):void 0}function revive(e){const t=Revivers.get(e?._ctor);return null==t?e:t.fromJSON(e)}function reviver(e,t){return revive(t)}function toJSON(e){return(e instanceof Date?(0,DateToJson_1.dateToJson)(e):void 0)??e?.toJSON?.()??(e instanceof Error?(0,Error_1.errorToJson)(e):e)}function decycle(e){const t=[],r=[];return function e(i,n){if((0,isFunction_1.isFunction)(i))return;let s,o,a,l=toJSON(i);if("object"==typeof l&&null!=l){for(const e in l)e.startsWith("__")&&(i===l&&(l={...l}),delete l[e]);for(s=0;snew Date(e.iso)}),exports.parseJSON_=parseJSON_,exports.parseJSON=parseJSON,exports.parseJsonObj=parseJsonObj,exports.revive=revive},56409:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;let i=0;t.Latch=class{constructor(e=i++){this.id=e,this[r]="Latch",this._state="pending",this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}toLogJSON(){return{_ctor:"Latch",id:this.id,state:this.state()}}resolve(){return this.isPending()&&(this._resolve(),this._state="resolved"),this}reject(e){return this.isPending()&&(this._reject(e),this._state="rejected",this.error=e),this}observe(e){return e.then((()=>this.resolve()),(e=>this.reject(e))),this}observeQuietly(e){return e.then((()=>this.resolve()),(()=>this.resolve())),this}isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e),this}},r=Symbol.toStringTag},30301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=void 0;const i=r(40958),n=r(50357),s=r(31586),o=r(65812);t.lazy=function(e,t){let r,a;const l=[];function u(){return u.isStale()&&u.setResult(e()),a}return u.vacuum=function(){u.isStale()&&u.unset()},u.setResult=function(e){return r=Date.now(),async function(e,r){if((0,i.isEmpty)(l))return;const s=await e,a=await r;if(!(0,n.eql)(s,a))for(const e of l)e(a);null!=t&&t>0&&void 0!==a&&(0,o.setUnrefTimeout)((()=>u.vacuum()),t)}(a,e),a=e},u.isStale=function(){return null==r||(0,s.gt0)(t)&&r+t{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteIf=t.getOrSet=void 0,t.getOrSet=function(e,t,r){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const i=r();return null!=i&&e.set(t,i),i}},t.deleteIf=function(e,t){for(const[r,i]of e.entries())t(r,i)&&e.delete(r)}},55835:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nulled=t.denull=t.firstDefined=t.allDefined=t.ifDefined=t.defined=t.map2Or=t.mapOr=t.orElse=t.map3=t.map2=t.mapTry=t.map=void 0;const i=r(42279),n=r(54993);function s(e,t){return null==e?void 0:t(e)}function o(e,t,r){return null==e||null==t?void 0:r(e,t)}function a(e,t){return null!=e?e:(0,i.tot)(t)}function l(e){return null!=e}t.map=s,t.mapTry=function(e,t){try{return s(e(),t)}catch{return}},t.map2=o,t.map3=function(e,t,r,i){return null==e||null==t||null==r?void 0:i(e,t,r)},t.orElse=a,t.mapOr=function(e,t,r){return null!=e?t(e):(0,i.tot)(r)},t.map2Or=function(e,t,r,i){return a(o(e,t,r),i)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,n.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e}},39426:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetaError=void 0;const i=r(68708);class n extends Error{constructor(e,t){super(e),this.message=e,(0,i.assignFields)(this,t)}}t.MetaError=n},23838:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupByValues=t.groupBy=t.MultiMap=void 0;const i=r(40958),n=r(76790),s=r(50357),o=r(98553),a=r(49769),l=r(55835),u=r(51926),c=r(59455);class d{static fromJSON(e){const t=new d;for(const[r,i]of Object.entries(e))t.add(r,...i);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,i.sum)([...this.store.values()].map((e=>e.length)),(e=>e))}add(e,...t){const r=(0,a.getOrSet)(this.store,e,(()=>[]));return r.push(...t),r}addUniq(e,...t){return(0,i.pushUniq)((0,a.getOrSet)(this.store,e,(()=>[])),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const r=this.store.get(e);if(null==r)return!1;{const i=r.filter((e=>!(0,s.eql)(e,t)));return 0===i.length?this.store.delete(e):this.store.set(e,i),r.length!==i.length}}}clear(){return this.store.clear(),this}keys(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield t)}()}values(){const e=this;return function*(){for(const[,t]of e.store.entries())t.length>0&&(yield t)}()}vacuum(e=((e,t)=>(0,i.uniq)(t))){for(const t of this.keys()){const r=this.store.get(t),n=null==r?[]:e(t,r);(0,i.isEmpty)(n)?this.store.delete(t):this.store.set(t,n)}}valuesFlat(){const e=this;return function*(){for(const[,t]of e.store.entries())if(t.length>0)for(const e of t)yield e}()}entriesArray(){return[...this.store.entries()].filter((([,e])=>(0,i.isNotEmpty)(e)))}entries(){const e=this;return function*(){for(const[t,r]of e.store.entries())r.length>0&&(yield[t,r])}()}tuples(){const e=this;return function*(){for(const[t,r]of e.store.entries())for(const e of(0,c.toA)(r))null!=e&&(yield[t,e])}()}filterInPlace(e){let t=!1;for(const[r,n]of this.store.entries()){const s=(0,i.findIndexes)(n,(t=>!e(r,t,n)));if(s.length>0){t=!0;for(const e of s.reverse())n.splice(e,1)}0===n.length&&this.store.delete(r)}return t}inverse(){const e=new d;for(const[t,r]of this.store.entries())for(const i of r)e.add(i,t);return e}findKeyByTuple(e){for(const[t,r]of this.tuples())if(e(t,r))return t}filterKeysByTuple(e){const t=[];for(const[r,i]of this.entries())i.some((t=>e(r,t)))&&t.push(r);return t}toJSON(){const e={};for(const[t,r]of this.entries())e[(0,u.isString)(t)?t:(0,o.stringify)(t)]=r;return e}}function h(e,t){const r=new d;return e.forEach((e=>(0,l.map)(t(e),(t=>r.add(t,e))))),r}t.MultiMap=d,t.groupBy=h,t.groupByValues=function(e,t){const r=h(e,t);return(0,n.sortBy)((0,c.toA)(r.values()),(e=>t(e[0])))}},35556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const r=globalThis;t.isBrowser="object"==typeof r?.window&&"object"==typeof r?.document,t.isNode="string"==typeof r?.process?.versions?.node},31586:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fmtPct=t.pct=t.times=t.clamp=t.base10Ceil=t.base2Ceil=t.sigFigs=t.toPrecisionMaybe=t.toPrecision=t.toFixedStr=t.toFixed=t.round=t.numericOr=t.mapNumericOr=t.map2Numeric=t.mapNumeric=t.id=t.mapFloat=t.mapInt=t.toGte0=t.gte0=t.lte0=t.gtOrElse=t.firstGt0=t.gt0=t.lt0=t.toGt0f=t.toGt0=t.toFloat=t.toInt=t.isToNumber=t.trunc=t.closeTo=t.max_=t.within=t.approximates=t.safeDivide=t.absdiff=t.diff=t.finiteOrElse=t.gte=t.gt=t.lte=t.lt=t.mapFinite=t.isBigInt=t.isNumeric=t.isDigits=t.isInvalidNumber=t.isNumber=void 0,t.toSum=t.roundEven=void 0;const i=r(76790),n=r(22573),s=r(42279),o=r(54993);function a(e){return"number"==typeof e&&isFinite(e)}t.isNumber=a,t.isInvalidNumber=function(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))};const l=/^\d+$/;t.isDigits=function(e){return null!=(0,o.toS)(e).match(l)};const u=/[^-.\d\s]/;function c(e){return"bigint"==typeof e}function d(e,t){return a(e)?t(e):void 0}t.isNumeric=function(e){return null==(0,o.toS)(e).match(u)&&null!=v(e)},t.isBigInt=c,t.mapFinite=d;const h=e=>(t,r)=>a(t)&&a(r)&&e(t,r);function f(e,r,n){return!(null==n||!a(n))&&([e,r]=(0,i.sort)([e,r]),(0,t.lte)(e,n)&&(0,t.gte)(r,n))}function m(e){if(!a(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function g(e){return"function"==typeof e?.toNumber}function p(e,t){if((0,n.blank)(e))return t.defaultValue;if(a(e))return t.nton(e);if(c(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||em(e),ston:parseInt,...t})}function v(e,t){return p(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function w(e){return a(e)&&e>0}function S(e){return a(e)&&e>=0}function b(e,t){return a(e)?t(e):void 0}function P(e){return a(e)?e<0?-Math.round(-e):Math.round(e):0}function _(e,t){if(null==e)return 0;const r=Math.pow(10,t);return P(e*r)/r}function E(e,t,r){if(e>t||!a(e)||!a(t))throw new Error(`invalid clamp(${e}, ${t}, ${r})`);return a(r)?rt?t:r:(e+t)/2}t.lt=h(((e,t)=>ee<=t)),t.gt=h(((e,t)=>e>t)),t.gte=h(((e,t)=>e>=t)),t.finiteOrElse=function(e,t){return a(e)?e:t},t.diff=function(e,t){return a(e)&&a(t)?e-t:void 0},t.absdiff=function(e,t){return a(e)&&a(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,r=.95){if(!a(e)||!a(t))return!1;if(e===t)return!0;if(r>=1)return!1;const i=(0===t?1e-5:t)*(1-r);return f(t-i,t+i,e)},t.within=f,t.max_=function(...e){let t;for(const r of e)a(r)&&(null==t||t0?t:void 0},t.toGt0f=function(e){const t=v(e);return null!=t&&t>0?t:void 0},t.lt0=function(e){return a(e)&&e<0},t.gt0=w,t.firstGt0=function(...e){for(const t of e){if(w(t))return t;const e=y(t);if(w(e))return e}},t.gtOrElse=function(e,t){return a(e)&&a(t)&&e>t?e:void 0},t.lte0=function(e){return a(e)&&e<=0},t.gte0=S,t.toGte0=function(e){return S(e)?e:void 0},t.mapInt=function(e,t){const r=y(e);return null==r?void 0:t(r)},t.mapFloat=function(e,t){const r=v(e);return null==r?void 0:t(r)},t.id=function(e){const t=y(e);return w(t)?String(t):void 0},t.mapNumeric=b,t.map2Numeric=function(e,t,r){return b(e,(e=>b(t,(t=>r(e,t)))))},t.mapNumericOr=function(e,t,r){return a(e)?t(e):r},t.numericOr=function(e,t){return a(e)?e:(0,s.tot)(t)},t.round=P,t.toFixed=function(e,t){try{return b(e,(e=>P(e*10**t)/10**t))}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.toPrecision=_,t.toPrecisionMaybe=function(e,t){return d(e,(e=>_(e,t)))},t.sigFigs=function(e,t){if(!a(e)||0===e||0===t)return 0;const r=t-P(Math.ceil(Math.log10(Math.abs(e)))),i=Math.pow(10,Math.abs(r));return r<0?P(e/i)*i:P(e*i)/i},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=E,t.times=function(e,t){if(!w(e))return[];const r=Math.round(e);return r<=0?[]:[...Array(r)].map(((e,r)=>t(r)))},t.pct=function(e,t){return E(0,100,w(t)?P(100*(w(e)?e:0)/t):0)},t.fmtPct=function(e,t){const r=Math.round(e??-1);return null==t||f(0,t,r)?r+"%":void 0},t.roundEven=function(e){return 2*Math.round(e/2)},t.toSum=function(...e){let t=0;for(const r of e){if(!a(r))return;t+=r}return t}},68708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flattenObject=t.firstValueCaseInsensitive=t.maybeCall=t.allKeys=t.filter=t.onlyReqValued=t.mapReqValued=t.reqValuedOrElse=t.toReqValued=t.allKeysDefined=t.isReqValued=t.omit=t.pluckDeep=t.pluck=t.pickDeep=t.pickFirst=t.pickNonBlank=t.pickCompact=t.pick=t.mergeObjectsDeep=t.mapFields=t.compactBlankValues=t.compactValuesDeep=t.compactValues=t.definedValues=t.assignAllFields=t.assignUndefinedFields=t.assignFields=t.fromEntries=t.entries=t.values=t.mapCompactObj=t.notEmptyObj=t.isEmptyObj=t.keysWithDefinedValues=t.keys=t.tap=t.isObject=void 0;const i=r(40958),n=r(76790),s=r(22573),o=r(32639),a=r(55835),l=r(31586),u=r(34666),c=r(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null==e||"object"!=typeof e?[]:Object.keys(e).filter((t=>"string"==typeof t&&(null==e.propertyIsEnumerable||!0===e.propertyIsEnumerable(t))))}function f(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function m(e){return!f(e)}function g(e){return h(e).map((t=>e[t]))}function p(e){return null==e?[]:Object.entries?.(e)??h(e??{}).map((t=>[t,e[t]]))}function y(e,t){if(null==e)return t;for(const r of e)if(null!=r&&Array.isArray(r)){const[e,i]=r;null!=e&&void 0!==i&&("object"!=typeof t&&(t={}),t[e]=i)}return t}function v(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>null!=e)))return e;const r=t.filter((([,e])=>null!=e));return(0,i.isEmpty)(r)?void 0:y(r)}function w(e,t,r={}){return y((0,i.compact)((0,n.sort)(h(e)).map((r=>t(r,e[r])))).filter((([e,t])=>null!=e&&void 0!==t)),r)}function S(...e){const t=(0,i.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const r=t.filter(d);if(t.length!==r.length)return t;const n={};for(const e of(0,i.uniq)((0,i.flatMap)(r,h)))n[e]=S(...r.map((t=>t[e])));return n}function b(e,t){if(!d(e)||(0,s.blank)(t))return;if(t in e)return{key:t,value:e[t]};const r=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of h(e))if(r.test(t))return{key:t,value:e[t]}}function P(e){return g(e).every((e=>null!=e))}t.isObject=d,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=h,t.keysWithDefinedValues=function(e){return null==e?[]:h(e).filter((t=>void 0!==e[t]))},t.isEmptyObj=f,t.notEmptyObj=m,t.mapCompactObj=function(e,t){const r=v(e);return m(r)?t(r):void 0},t.values=g,t.entries=p,t.fromEntries=y,t.assignFields=function(e,t,r){if(null==t)return e;for(const[i,n]of p(t))!0!==r?.omitKeys?.includes(i)&&(null==n&&!0!==r?.assignNullish||(e[i]=n));return e},t.assignUndefinedFields=function(e,t,...r){if(null==t)return e;for(const i of r){const r=t[i];void 0!==r&&void 0===e[i]&&(e[i]=r)}return e},t.assignAllFields=function(e,t){for(const[r,i]of p(t??{}))e[r]=i;return e},t.definedValues=function(e){if(null==e)return;const t=p(e);if(t.every((([,e])=>void 0!==e)))return e;const r=t.filter((([,e])=>void 0!==e));return(0,i.isEmpty)(r)?void 0:y(r)},t.compactValues=v,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,i.compact)(t.map(e));{const r=(0,i.compact)(p(t).map((([t,r])=>(0,a.map)(e(r),(e=>[t,e])))));return 0===r.length?void 0:y(r)}}},t.compactBlankValues=function(e){if(null==e)return;const t=p(e).filter((([e,t])=>null!=e&&(0,s.notBlank)(t)));return(0,i.isEmpty)(t)?void 0:y(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(null==e)return e;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickCompact=function(e,...t){if(null==e)return;const r={};for(const i of t)void 0!==e[i]&&(r[i]=e[i]);return r},t.pickNonBlank=function(e,...t){if(null==e)return e;const r={};for(const i of t){const t=e[i];(0,s.notBlank)(t)&&(r[i]=t)}return r},t.pickFirst=function(e,t,r=a.defined){if(null!=e)for(const i of t)if(r(e[i]))return e[i]},t.pickDeep=function e(t,...r){if(null==t)return t;if(Array.isArray(t))return t.map((t=>e(t,...r)));const i={};function n(e,t){if(null==t)return;const r=i[e];i[e]=null==r?t:S(r,t)}for(const i of r){const[r,o]=(0,c.splitFirst)(i,"."),a=b(t,r);null!=a?.value&&n(a.key,(0,s.blank)(o)?a.value:e(a.value,o))}for(const i of h(t))((0,l.toInt)(i)??-1)>=0&&n(i,e(t[i],...r));return i},t.pluck=b,t.pluckDeep=function e(t,r){if(null==t||(0,s.blank)(r))return;if(Array.isArray(t)){const n=(0,i.compact)(t.map((t=>e(t,r))));return(0,i.isEmpty)(n)?void 0:{key:n[0].key,value:(0,i.flatMap)(n,(e=>e.value))}}const[n,o]=(0,c.splitFirst)(r,"."),a=b(t,n);if(null==a)return;if((0,s.blank)(o))return a;const l=e(a.value,o);return null==l?void 0:{key:a.key+"."+l.key,value:l.value}},t.omit=function(e,...t){if(null==e||t.every((t=>(0,s.blank)(e[t]))))return e;const r=p(e).filter((([e])=>!t.includes(e)));return(0,i.isEmpty)(r)?void 0:y(r)},t.isReqValued=P,t.allKeysDefined=function(e,...t){return null!=e&&t.every((t=>null!=e[t]))},t.toReqValued=function(e){return P(e)?e:void 0},t.reqValuedOrElse=function(e){return P(e)?e:void 0},t.mapReqValued=function(e,t){return P(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(P)},t.filter=function(e,t){return null==e?e:y(p(e).filter((([e,r])=>t(e,r))))},t.allKeys=function(e){const t=h(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter((e=>"string"==typeof e)));return(0,i.uniq)(t)},t.maybeCall=function(e,t,...r){const i=e?.[t];return(0,o.isFunction)(i)?i.bind(e)(...r):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,s.blank)(t))return;if(null!=e[t])return e[t];const r=t.toLowerCase().normalize();for(const t of h(e))if(r===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const r=w(t,((t,r)=>[t,e(r)])),i=g(r);return 1===i.length?i[0]:r}},97790:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.opt=t.isOpt=t.Some=t.None=void 0,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>s(e()),e.zip1=t,e.zip2=t,e.zip3=t}(r||(r={})),t.None=r;class i{constructor(e){this.a=e,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(e){return e(this.a)}map(e){return new i(e(this.a))}flatMap(e){const t=e(this.a);return n(t)?t:s(t)}filter(e){return s(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return s(e).flatMap((e=>t(this.a,e)))}zip2(e,t,r){return s(e).flatMap((e=>s(t).flatMap((t=>r(this.a,e,t)))))}zip3(e,t,r,i){return s(e).flatMap((e=>s(t).flatMap((t=>s(r).flatMap((r=>i(this.a,e,t,r)))))))}}function n(e){return e instanceof i||e===t.None}function s(e){return n(e)?e:null!=e?new i(e):t.None}t.Some=i,t.isOpt=n,t.opt=s},39926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pad4=t.pad3=t.pad2=t.padNumeric=t.leftPad=t.padding=void 0;const i=r(31586),n=r(54993),s={};function o(e,t){if(t<1)return"";if(!(0,i.gte)(s[e]?.length,t)){let r=s[e]??e;for(;r.length{Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=void 0;const i=r(22573),n=new Map([["child","children"],["photo","photos"],["video","videos"]]),s=/([sxz]|ss|sh|ch)$/,o=/[^aeiou]y$/,a=/[aeiou]y$/,l=/is$/;t.pluralize=function(e){if((0,i.blank)(e))return e;const t=n.get(e);return null!=t?t:null!=e.match(s)?e+"es":null!=e.match(o)?e.replace(/y$/i,"ies"):null!=e.match(a)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"}},34666:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cmpArr=t.gt=t.gte=t.lte=t.lt=t.cmp=t.CmpReverseFlag=t.isPrimitiveArray=t.mapPrimitiveOr=t.mapPrimitive=t.isPrimitive=void 0;const i=r(40958),n=r(54993),s=["number","string","boolean"];function o(e){return-1!==s.indexOf(typeof e)}t.isPrimitive=o,t.mapPrimitive=function(e,t){return o(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,r){return o(e)?t(e):r()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(o)};const a=["boolean","number","bigint","symbol","string","object","function"];function l(e,r){if(null==e&&null==r)return 0;if(null==e)return-1;if(null==r)return 1;const i=typeof e,s=typeof r;if(!("string"!==i&&"symbol"!==i||"string"!==s&&"symbol"!==s)){const i=(0,n.toS)(e),s=(0,n.toS)(r),o=i.localeCompare(s);return i[0]===t.CmpReverseFlag&&s[0]===t.CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(r)?u(e,r):i!==s?a.indexOf(i)-a.indexOf(s):e>r?1:e=0},t.gt=function(e,t){return l(e,t)>0},t.cmpArr=u},20214:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.thenIf=t.isPromise=t.isPromiseLike=t.thenTap=t.thenCollect=t.thenMap=void 0;const i=r(59455);function n(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}t.thenMap=async function(e,t){const r=await e;return null==r?void 0:t(r)},t.thenCollect=async function(e,t){const r=[];for(const n of(0,i.toA)(await e))if(null!=n){const e=await n;if(null!=e){const i=await t(e);null!=i&&r.push(i)}}return r},t.thenTap=async function(e,t=console.dir.bind(console)){const r=await e;return await t(r),r},t.isPromiseLike=n,t.isPromise=function(e){return n(e)&&"function"==typeof e.catch&&"function"==typeof e.finally},t.thenIf=async function({p:e,predicate:t,ifTrue:r}){const i=await e;return t(i)?r(i):void 0}},57153:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const i=r(50989);t.PromiseStates=(0,i.strEnum)("pending","resolved","rejected")},30976:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pickWeightedRandom=t.sample=t.shuffle=t.pickRandom=t.randomChars=t.RandomChars=t.LowercaseChars=t.NumericChars=t.randomFloat=t.randomBoolean=t.randomInts=t.randomInt=void 0;const i=r(40958),n=r(31586);function s(e,t){return Math.floor(Math.random()*(t-e))+e}function o(e,t,r){return null==r||0===r.length?s(e,t):a(e,t,1,r)[0]}function a(e,t,r,i){if(e=Math.ceil(e),(t=Math.floor(t)) ${t}`);const n=t-e,o=new Set(i??[]);if(t===e&&0===n&&0===o.size&&1===r)return[e];const a=n-o.size;if(r>a)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:n,size:r,slotsRemaining:a})}`);const l=new Set;for(;l.size0;e--){const r=Math.floor(Math.random()*(e+1));e!==r&&([t[e],t[r]]=[t[r],t[e]])}return t},t.sample=function(e,t){const r=[];for(const i of a(0,e.length,t))r.push(e[i]);return r},t.pickWeightedRandom=function(e){if((0,i.isEmpty)(e))return;const t=e.filter((e=>(0,n.gt0)(e.priority)));let r=l(0,(0,i.sum)(t,(e=>e.priority)));return t.find((e=>(r-=e.priority,r<=0)))}},5670:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const i=r(50989);t.ServiceNames=(0,i.strEnum)("main","desktop","web","sync","info","test","logcat","logtail","list","billing","worker","test-worker")},38453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=void 0,t.splitFirst=function(e,t){const r=e.indexOf(t);return-1===r?[e]:[e.slice(0,r),e.slice(r+t.length)]}},50989:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=void 0;const i=r(68708),n=r(42279);t.strEnum=function(...e){const t=Object.freeze(e),r=(0,i.fromEntries)(t.map(((e,t)=>[e,t]))),s={};for(const e of t)s[e]=e;const o=e=>null!=e?r[e]:void 0,a=e=>null!=o(e);return{...s,values:t,length:t.length,has:a,includes:a,getCI:e=>{if(null!=e)return e=e.toLowerCase(),t.find((t=>t.toLowerCase()===e))},pick:(...e)=>t.filter((t=>e.includes(t))),omit:(...e)=>t.filter((t=>!e.includes(t))),indexOf:o,ordinal:e=>o(e)??t.length,validOrElse:(e,t)=>a(e)?e:(0,n.tot)(t),mapValid:(e,t)=>a(e)?t(e):void 0,cmp:(e,t)=>{const r=o(e),i=o(t);return null==r||null==i?void 0:r>i?1:r{const r=o(e);return null==r?void 0:t[r]}}}},51926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.includesIgnoreCase=t.firstIgnoreCase=t.equalsIgnoreCase=t.splitLast=t.compressWhitespace=t.replaceAll=t.eqlStrings=t.wrap=t.leftIndexOf=t.trimLastNewline=t.newlineRe=t.ellipsize=t.ensurePrefixSuffix=t.ensureSuffix=t.ensurePrefix=t.stripPrefixSuffix=t.stripSuffix=t.stripPrefixes=t.stripPrefix=t.trimRight=t.charArr=t.substr=t.strslice=t.strlen=t.charAt=t.isBMP=t.isBuffer=t.isString=void 0;const i=r(40958),n=r(17586),s=r(22573),o=r(96249),a=r(41801),l=r(31586),u=r(59455),c=r(54993);function d(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let h;function f(){if(void 0===h)try{h=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{h=null}return h??null}function m(e,t,r){if(d(e))return t<0&&(t+=e.length),e.slice(t,r);{const i=f();return null!=i?(0,a.sliceIterable)(i.segment(e),t,r).map((e=>e.segment)).join(""):[...(0,c.toS)(e)].slice(t,r).join("")}}function g(e){const t=f();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map((e=>e.segment))}function p(e,t){const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.startsWith(i)?r.slice(i.length):r}function y(e,t){if(null==t)return e;const r=(0,c.toS)(e),i=(0,c.toS)(t);return i.length>0&&r.endsWith(i)?r.slice(0,-i.length):r}function v(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,r){null==r&&(r=e.length);for(let i=r;i>=0;i--)if(m(e,i).startsWith(t))return i;return-1}function b(e,t,{normalize:r=!0}={}){if(null==e||null==t)return!1;const i=(0,c.toS)(e),n=(0,c.toS)(t);return i.length===n.length&&(i===n||i.toLowerCase()===n.toLowerCase()||"function"==typeof i.localeCompare&&0===(r?i.normalize():i).localeCompare(r?n.normalize():n,void 0,{sensitivity:"base"}))}function P(e,t){return(0,i.isEmpty)(e)||(0,s.blank)(t)?void 0:e.find((e=>b(t,e)))}t.isString=function(e){return"string"==typeof e},t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=d,t.charAt=function(e,t){if(d(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,n.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=f();return null!=t?(0,a.countIterable)(t.segment(e)):d(e)?e.length:[...e].length},t.strslice=m,t.substr=function(e,t,r){return d(e)?e.slice(t,null==r?void 0:t+r):m(e,t,null==r?void 0:t+r)},t.charArr=g,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=p,t.stripPrefixes=function e(t,r){if(null==t)return"";const i=(0,c.toS)(t);for(const t of r)if(null!=t&&t.length>0&&i.startsWith(t))return e(i.slice(t.length),r);return i},t.stripSuffix=y,t.stripPrefixSuffix=function(e,{prefix:t,suffix:r}){return y(p(e,t),r)},t.ensurePrefix=v,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:r}){return w(v(e,t),r)},t.ellipsize=function(e,t=80,r=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),r=(0,l.clamp)(0,t-1,(0,l.round)(r));const i=g(e);return i.length<=t?i.join(""):i.slice(0,t-1-r).join("")+"…"+(r>0?i.slice(-r).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,r){const i=r?.maxLineLen??80,n=r?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const i=(0,o.flatten)((0,u.toA)(t).map((e=>(0,c.toS)(e).split(/\r?\n/g))));return(0,o.flatten)(i.map((t=>e(t,r))))}if((t=v((0,c.toS)(t),n).trim()).length<=i)return[t];const s=S(t," ",i);if(s>n.length)return[m(t,0,s),...e(m(t,s+1),r)];{const i=t.indexOf(" ",n.length+1);return i>0&&i{Object.defineProperty(t,"__esModule",{value:!0}),t.thenOrTimeoutAs=t.thenOrTimeoutAtError=t.thenOrTimeoutError=t.thenOrOnTimeout=t.thenOrTimeoutAt=t.thenOrTimeout=t.thenOrTimeoutMaybe=t.toNotTimeout=void 0;const i=r(42659),n=r(68708),s=r(42279),o=r(83104),a=r(85556);function l(e){return e===o.Timeout?void 0:e}async function u(e,t,r=!0){return(t=Math.round(t??0))<=0?e:new Promise((async(r,i)=>{let n=!0;const s=setTimeout((()=>{n&&(n=!1,r(o.Timeout))}),t);try{s.unref?.();const t=await e;n&&(n=!1,r(t))}catch(e){n&&(n=!1,i(e))}finally{clearTimeout(s)}}))}async function c(e,t,r=!0){const n=await u(e,t,r);if(n===o.Timeout)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(t)+")");return n}t.toNotTimeout=l,t.thenOrTimeoutMaybe=function(e,t,r=!0){return u(e,t,r).then(l)},t.thenOrTimeout=u,t.thenOrTimeoutAt=async function(e,t,r=!0){const i=t-Date.now();return i<=0?o.Timeout:u(e,i,r)},t.thenOrOnTimeout=async function(e,t,r){return t<=0?e:new Promise((async(i,s)=>{let o=!0;try{const a=setTimeout((async()=>{if(o){o=!1;try{i(await r())}catch(e){s(e)}}}),t);(0,n.maybeCall)(a,"unref");const l=await e;o&&(o=!1,clearTimeout(a),i(l))}catch(e){o&&(o=!1,s(e))}}))},t.thenOrTimeoutError=c,t.thenOrTimeoutAtError=async function(e,t,r=!0){const n=t-Date.now();if(n<=0)throw new a.TimeoutError("timeout ("+(0,i.fmtHMS)(n)+")");return c(e,n,r)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:r,unref:i=!0}){if(null==e)return(0,s.tot)(r);const n=await u(e,t,i);return n===o.Timeout?(0,s.tot)(r):n}},42279:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=t.firstDefinedSuccess=t.firstDefinedThunk=t.tol=t.tot=void 0;const i=r(32639);t.tot=function(e){return(0,i.isFunction)(e)?e():e},t.tol=async function(e){return(0,i.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}},t.NoOp=()=>{}},83104:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0;class r extends Error{}t.TimeoutError=r},12168:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.plurMetric=t.plur=t.pixels2size=t.SizeDescriptions=t.megapixels=t.MP=t.fmtMebi=t.fmtBytes=t.fmtMB=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.fmtToInt=t.fmt=t.bytesToMB=t.decimalSep=t.thousandsSep=void 0;const i=r(22573),n=r(30301),s=r(31586),o=r(46891),a=r(50989),l=r(51926),u=(0,n.lazy)((()=>new Intl.NumberFormat));function c(e){return u().format(e)}t.thousandsSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0))),t.decimalSep=(0,n.lazy)((()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0))),t.bytesToMB=function(...e){let r=0;for(const i of e)(0,s.isNumber)(i)&&(r+=i/t.MB);return(0,s.round)(r)},t.fmt=c,t.fmtToInt=function(e){return(0,i.mapNotBlank)(e,(e=>(0,s.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),""))))},t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,s.isNumber)(e))return"-";const r=Math.floor(Math.log10(e)),i=Math.floor(r/3),n=Math.pow(10,3*i),o=d[i];return(0,s.sigFigs)(e/n,t)+" "+o}t.fmtMB=function(e,r=3){return f(e*t.MB,r)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const r=Math.floor(Math.log2(e)),i=Math.floor(r/10),n=Math.pow(2,10*i),o=h[i];return(0,s.sigFigs)(e/n,t)+" "+o},t.MP=1e6,t.megapixels=function(e){return(0,s.sigFigs)(e/t.MP,2)},t.SizeDescriptions=(0,a.strEnum)("tiny","small","medium","large","original"),t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,r){return null==e?"":(0,i.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(r??(0,o.pluralize)(t)).trim())},t.plurMetric=function(e,t,r){return r??(r=(0,o.pluralize)(t)),{count:c(e),desc:1===e?t:r}}},65812:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=void 0;const i=r(68708);t.setUnrefTimeout=function(e,t){const r=setTimeout(e,t);return(0,i.maybeCall)(r,"unref")??r}},23541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isError=void 0,t.isError=function(e){return null!=e&&e instanceof Error}},32639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},59455:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.optToA=t.toA=void 0;const i=r(41801),n=r(51926);function s(e){return Array.isArray(e)?e:null==e?void 0:(0,n.isString)(e)?[e]:(0,i.isIterable)(e)?Array.from(e):[e]}t.toA=function(e){return s(e)??[]},t.optToA=s},41583:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toErrs=t.toErr=void 0;const i=r(40958),n=r(23541),s=r(59455),o=r(54993);function a(e){return null==e?void 0:(0,n.isError)(e)?e:new Error((0,o.toS)(e))}t.toErr=a,t.toErrs=function(...e){return(0,i.compact)((0,s.toA)(e).map(a))}},54993:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toStr=t.toS=void 0;const i=r(98553);t.toS=function(e){return s(e,",")};const n={}.toString;function s(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map((e=>s(e,t))).join(t):e.toString!==n?e.toString():(0,i.stringify)(e)}}t.toStr=s},92636:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=r(6858),s=i(r(73024)),o=i(r(76760)),a=r(1708),l=r(37805),u=r(41269),c=r(80061),d=r(94361);function h(e){for(const t of["bin",__dirname]){const r=o.default.join(t,e);if(s.default.existsSync(r))return r}return console.error("failed to find command "+e),e}n.program.version(l.version),n.program.description("Welcome to PhotoStructure, your new home for all your photos and videos.\nSee https://photostructure.com/server/tools/ for details about these tools."),(0,d.verifyUidGid)(),(0,c.addHelpFooter)(n.program).command("main",u.CliDesc.main+" (default)",{isDefault:!0,executableFile:h("main.js")}).command("info",u.CliDesc.info,{executableFile:h("info.js")}).command("list",u.CliDesc.list,{executableFile:h("list.js")}).command("logcat",u.CliDesc.logcat,{executableFile:h("logcat.js")}).command("logtail",u.CliDesc.logtail,{executableFile:h("logtail.js")}).command("web",u.CliDesc.web,{executableFile:h("web.js")}).command("sync",u.CliDesc.sync,{executableFile:h("sync.js")}).parse(a.argv)},90858:e=>{e.exports=require("@iarna/toml")},58587:e=>{e.exports=require("batch-cluster")},6858:e=>{e.exports=require("commander")},36507:e=>{e.exports=require("croner")},66261:e=>{e.exports=require("events")},77988:e=>{e.exports=require("exiftool-vendored")},44652:e=>{e.exports=require("fs-extra")},28787:e=>{e.exports=require("he")},51168:e=>{e.exports=require("luxon")},73872:e=>{e.exports=require("type-detect")},92460:e=>{e.exports=require("util")},31421:e=>{e.exports=require("node:child_process")},77598:e=>{e.exports=require("node:crypto")},78474:e=>{e.exports=require("node:events")},73024:e=>{e.exports=require("node:fs")},51455:e=>{e.exports=require("node:fs/promises")},48161:e=>{e.exports=require("node:os")},76760:e=>{e.exports=require("node:path")},1708:e=>{e.exports=require("node:process")},57075:e=>{e.exports=require("node:stream")},46466:e=>{e.exports=require("node:stream/promises")},87997:e=>{e.exports=require("node:timers")},57975:e=>{e.exports=require("node:util")},38522:e=>{e.exports=require("node:zlib")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}var __webpack_exports__=__webpack_require__(92636);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/public/3rd-party-licenses.txt.gz b/public/3rd-party-licenses.txt.gz index d0ca55762de96301418925c2551dbbb88fb3758c..c162140132980ddd96baf3eb20ab4bd8f458def2 100644 GIT binary patch delta 17 Zcmdn@gK6InCN}wQ4i42r8`&)O002VX2EzaV delta 17 Ycmdn@gK6InCN}wQ4h}hwjcgWs06;Abp=}h delta 15 WcmaE${6LvazMF$X!($`cEkOV&;{@3N diff --git a/public/app/app.css.gz b/public/app/app.css.gz index c5e698e8e2f630c3b1550c9328ac861d7bff6c59..b5c69e814e2174345e4bfff28aadbc8a6d108827 100644 GIT binary patch delta 15 Wcmdnwv&n}|zMF$X?a)Rx9W?+d6a=mS delta 15 Wcmdnwv&n}|zMF$X!DAzvjv4?bjsz|M diff --git a/public/app/app.css.map.gz b/public/app/app.css.map.gz index 587a79da0d142a0188326140b1c7380cdf662d16..77867ca4aa71f19efdc559df7469ba0dfb271680 100644 GIT binary patch delta 15 WcmcaEdtH`IzMF$X?a)THi+lhoj0GnE delta 15 WcmcaEdtH`IzMF$X!DA!aMLqy11_Y-7 diff --git a/public/app/app.js.gz b/public/app/app.js.gz index 56b46570d584b9117c1f6117f82636e9693a3064..9d48f94ff3edefd53f7f545f3c06b2d7e946b440 100644 GIT binary patch delta 19006 zcmV(!K;^&N@CM%S1_mFC2naC3fd;h(0mE*8TGbUXob%PxvF_pkL=bbi(QDKPgMPgU zrKr?!Uhto@#g>$#v!KdJ1uF@VpDyBp&u0rIxn1pQhq*f|l6sB{r5@^Vh-Ph~JMIvj z*-8?+!Zop(0qi21MOqn@l7r&J@wad5>TwM-k#NR36wX{fDh?;<6yrp(>G$rQEu^}C zCmVF=-O&|3;48@P5v8 z=JV6_l=j_9zSB4C*dHeI2?00fWFRR)L4AZc3fF{ToI3Slad@#9Er%Biq_n?%`&lG9 z+!IDjnkW%Vohn*REUfsb|HuFG|1zq7!M#==Sa+7mN^ke&4NKqErReFQl`I%(JzKew zA|2j60Y?M7P(~8V>;@7m8_Qo-x)^0)8AgwqEnCwtTm{2}gB7L|=;=VBI^ZJr2dcL! z_jW+6;_2DkS-u62uB%I`(sitJ(ET^ngrq8cs($6}(vUh7>E;v4Nk-p9B`OJjELF8+ zsUnp+M>VRwD>bhDb}@pU$O)hphxG97((xfFAISrx+Fu|iDcyR%$PLULG`bc0!E*H4?(cN5mK8lH3FQu^Q zIsDEZ5PSY?QA3k9{guygh41ly7cb-Qd0=qyUoB$uPwZHcJW-aToO0Z8VB*DdhXlx6 zyFP*tR8tQYaWJ9j$#-v&E;#;nfwOxydFDTulQf^nSS-tH^d~oTr=MOp-3q597JoMj z35wC;8bwDlBRu-&jPMxZSp~RemM~r9czwlfv8;|6Xh%`;(0+)o?6`7&M>fg6`*|i~ z(BI@_UU*k1OOY-W@^ld;41c~DwT)RkeZ{KC z3$Ec``j~;GjDo3E3>mP>L`cs9ZF)k_hu!+HU%#uL%@fa>?fS6QjGr!ssn9@vtI@0v z8{N7Q{P5fF84dAn*S9`L};=D%Ac zeN0n?$c>4^-As`7AKN9Utpz?NMUF&&q<<1a6gx_%hI*74>f%3tWt2>kjA7#U$k)HH z$45k<{DjlP6q@mh%_w4cbel7}oAOj|=nCQwlUQ`u?8u~VzFjuUT}Lma$&KMR=O45x zl{>Df|BlCVWSm~16m3_WscYuf|HlCugRfe5LUth6IcnMKG6shUb|Im!7WTIb`{x32 zr2J~ZM+3csReD8#vh}q_w&6WC59sE!r+3uXkeZG*_wd`rjp3Ti_aBW@j>+2j+mbZs zx}ihbRHyIT){rnZ?@5cE;BV8qvGw2z+m`JaH$(3pS{MFoa;hE;<(FdR;uc@Bxmft> zy&JyAt(1IlnI*If4K}}7Vy;>4-55~Jy4>UwGXuqKvo3spE*``3|1|j#)QhtKTJ`(x z*w1vG@(Yeyg<357@pU6=PTcp;&XW^O z!J%Hc)2RHrP{T_%vYIlvjP4@r{l@0Lf$3(~d;}CMw?dj>%pxXz1@AAI%IOXCUHp@0 z_-)6>YPWxz<`^2!BR3dHgl5^_O)K`(d?SW2+wkb7hK17!y|ZLi1C^0OxzhhCDj{}PP&%n!^Rf@p z&42lS{1U$|itjd^z_}2_A`0CRe{>;CJ*{9Vyz@`B{2-_yi5i;AB{KMzNQ9#I^2pGq-hVQb#{Hvjp6@KFq~JST9YwhfQ8I8l+GLATI0bQ`EZT#`$CH`>AVCpBiJEV3o z?H(r~Ld_0mL)!gLek|4eB3ZXPUBo;Z^!bQh9bfuBEYIF$=-QK!s-u}ScDu#cn#h_sT$O4$IiIY-D?t~gJ5b*UmdRqe7h$?rP_`cCXCUC%45f%wSjA|T zj_TMQaSxL#|3kN2<2-8w9yGm{PbcCd3*(}*l-dVAcH#=lzBIaf(5Z(`6gv>%JRyF&FNz9 zojLQDaAk?AfEJjOf~n)X${Br=!&1}De|d3mwkZ+^oy`|EwC63i}g=LP%pZvRO9e&cWM^KiF+ zqY6YLtVapJfx>qpqRV6OP(yEHGc%R6M8@m}SDNNGPG?>Kn-Q)pc&%~r3-{>g=VY)K z!1ERIb-O9sOCn>2Wt%I1lwj>7>qF&mP#;zYl8`}l_46zHbr^ox6f)K$ML_2!OYIOq;eyUL*lU zk%(IgP3iiEL8wr(=u3Z7wq)N@pUDzU1{Jfd5&>5N%oG|E=U}IQU*irRsJ*(aN4=kS z^to_+ng`eR;eFuD3wxD)v8_+F(f99?KY;sXQJ=Dt3J6ij*?dx+KHJeB2Ai}*97Gav zkdlZakH^^EZ6Bhi1>8!cLwiExgN=`L5SJu$ptST#N(WL>i3Xm|Yd_z6@$}Kt?<*1= z4oNTB2m?jOy$L~onv^_YZ%b!%oCkN zTB=$>rIoY6Wvy1TNFMd)T&O50NL&#l6IaBAm(E>4bXmzt?Zk}+I&nqqjKtG&R)UY- zAl}ihO^K~`{Qxe4W$SO%GkO;aS;CyeB)&(uAhNub(CRIJ8vXff&TkH9wlIj0+h-q8 z>&Rh4ITAsYNrY5x6i{$k+(hlS6{;q&^RL`F_-*B0SS*vP5bjYVP@75+eJ@gm=o=zm zmw8Ym0XZjzIw4x*yr9#GTAY%zoRqkcWZnr4tEjy^B?SGec((aw^mbYvZ!)_@P}_!- z`PG=1(9l(Xj&U}eq)r2OeqK8rfBfi1fl@@>cxf!8x1xh#tn^(-vrzSx)!AgO##)sZ zONj2Mj=7vdRjM-F*l(5`rkHMI=~XAbbHSgew+NP1P6r`+GLVki>6$Y_+ROmlp@(Z7{?iuvo*NOOR~Fe@$QP2!LVCX&PlXW8KrVWMXU)l7bY zG;$@qAoD6TP$dOg%T`k-f-EnpgH;l@{RQoo%AvC=SsyH5qNL5ROUzE(Ss?KhhlldX zHTms-G6*Ywxsj!E(&Jdq#;^&fMb!gZL}QRXE$$O3@Qj*AL#vvodo;98nO7QKbKvR_ zair=zSG@=8iz@nyR~NsA*4(>Xxu+y3Tm}|_JBu7r@1+2p=kZ{fF8Jacf{+0Ncw#Fu zZcukdx+4-okT7x>CxfIr$S}HiE}B3UFQ_{3ZpA_JK z3x3zgr@nhW%xkTNCyFlQKIccazLo!uKDc+FjQ++dobT^nl(Le~53N^ATo7V|^|vZ_ zB$5pxYGNDwHMI@qnN^HLhg~bFIzD&So)68&FuFWF^L!kmx!YvlU7aHGX>1f}uQaIt zAOD}y*t_Htcs%#UZ?9&7o80<-W{#16RJvp7B%9)?9NB+lGTCJlIST8hMg5_5PYeA; zt9MVRv&n)~BY{lPKw!YuFm7Kx2LBQ2chlf7#lBsuuG_sd#;vciAPQ@y_Tm%v@H`7K zEe9SFd%yfkC{ms)NlWIlGvDz6q8B-L3*q@92cCwwnS^NEfAoq#HTs!`YeKqz-38dV zc{S`)lA=$EyPk7L`lizHY@wZ|?&t8cZMbrz{W>HVvm!%)9QsZ$wGhfFilib~|67Xk zyv%`pEOsYBAN8zX5WwqSX}BBm{Vu3SE%P)8x;!(fNlnw*MzSZw-&8@|)9`hw-YUbB zDzYUxzG40ouW$=Vu<7UIcp6+REP;<^7m73d* zN$oh;KhsH`L1VL5e(Cp&cGoEP9Hdet>=>oIweK+9>TI#{{IKNA=Nv_U&uSZ1T^a;p z3)_^N42P5Oan`lXa%^$<__q1sty5=SFgLe~=jL#7CpY!2yz@@+Fi1kCSd?5qsMl0k zb7U)6pwu>ys_#g~>T$ zStACi0K@TKw60h(U)@pzA+%D9Ob9>Se``g#lRhV|C0S?+SnYkMyDy{Gr(?#}i7tej)Pa_-50M(3@Z{`4QWaH@wL z>vnPjKfm`IXn7G`xQ*y9Xo{!s4b2q~quMC(l(x$&S*;YDK3HBc53kwo!^^PUmT%Q} z9$wssnu7k1Gp*XU8f-y{|EbUx!(kh6EZXH4PrZFS_0GR|>V5Il`{Jqh#ZzxDPrXUT zQ;$8+iCPQ076!5V2Xu9L+z-9+0&e{B`OHM|98bryud zjr5mIS)nt?=T_q~oLIyGU~(^f>~WD6q-JEix4xVC0URxGU=#NU?lAqbUDT>rFU?kW z_snHcQy<2Eqj~H=j3hZ&4JF-!tzOLbBY>(LTFkx1=Is(d3P%`bi2+3@U-dPP4+U)t zjY~<&zoRyVjnsJebbYa+Y$3X|FxE5i!7G1mg!Ak19ZDX*q*s+HY{)g^xX2idkaLO< zPlu?Ab8ilXQ)OtCQ)8}JsbNyD#d$}JOm5sQ?e~Iz>|KBv28t$gS2cn*#}X!naA53m zv(j6pj$_d{OIylPE@niBhz%$jcjyq?`SUC!RANXTSgK&+k+%{@k0KYeR2{o0z1t^x z1rfu&I`bTVQs7N?1r;Jf%V=DDeWX9gL$1sH{NnT+&Nn&1qly(-=EsLEO^>g--L&nN zczor5Oer2b4KW?uwbU+NFG;u|XwPH^E2pb;#>J-FlA1cLbX*}4?W&gYyr;&rj@+(J z*_&vkl^3rS`LQF=6{Rq?;(*~5nBE}9GSaCksksX>p(__7I?(Amm8ek?fy)rmsF*4E z$v%|wuD!JjZgtH0AOAU1liZWZVeH&##!#YvkBY~`^R%Z<@POpX;L>+h-qc|>F^nCD zOJ?ib?wZY9WAnl+%2s1dMJMFM<=-4wzGRz?^&@2TVG?W@C7nrA(@9C1z(o;u&3M zUNU_$O{Ys-Oj}l3aPM5zhy@MkNW{Qn&Q)!vX`K_AQpNSlbmxXP3byWk^2R zb;Uyb~hM*?`_6mkaCkdm0>cbJcS;t1fy@|8g<`t3dZ6c_`GL2t_^pja+zNbgzu}yUOwrm~H z4np1tvq{A_6Ssu}H=*w3*^kvsB0heL9z1b~usth7_Y2|0NtAbhiaG1kv3_@di-W_2 z*C{cc!@WF?6Q88qjFZopVSR*Lcf&^7mzc(u2cH6P6e_|+{msi@oNmU}P6F{eyi*dj zj&-xkyq|71$Dp4#2iX$pq%0cBU+$?F?2_k~tnW&yp3z_8QT_k^?+3}DM5phzj?FW+ z5Dv%kQYpY&RxVa2&gwf>DR9SsTPI8hb1~RwbJU*V>aFWpxG_Ng==fO*;5gyqj^c|n zF-q|O1>1&S*|lp}nj+lYMq~22lRcE+5(;6!AD8s`Ux0iOud&7L_`;{dAhlwNA+Tyv zpF+7WG)@wzymejASH>1hEvt`ItfdtY$t6He3TE})^W$w3q8_X~45a&i71J;Jq-b3< zhf{z8Tpw_k>o>~Q^MDIIh)?(5nlL-CC}G8){xbh z)*Tm|9!mNqiL;v<{o$Iy9ygNw=)`Uoz%v?bjSc8U!(}+LE1LlDj%(^e^6Yr5q9WFD z<}AZ}wuR(*S1Dh>Whl;nMJW=i&bfsoklPnhe}5Q8iYK>nXe~TyB2qjN+va<3-Q_6< zOXWNNVu6*b-Xt?SE_nulN~=kcRO=r;<-E8fx?a0gXk<&Q;jf~eLWFfFN)k?W*{o!R zx0o$gdlHlNH3G#v&&{W@QksW~+gdoQvb!966Zh4NM@L$nUy1vFup=7jUTLfUIZ|0e zL1?zbU&ySE-BpSm^EIA7C9=d6uz=v;^J?I(l2j*dR(*PP=3B}VY&MlxXTbs1pO)R! zc-)#S4@Q1`d44{7FPvd>kJysQY=PraoJbR-F;@Ol2W)8gtE=q@MAiR~|Lw{1QaL(N z#fkx&gHA1UP&&AOu<11mZ&%X%%QD(bD#WGKtJiaQ{8bhTon-(m5Y@b2BPQw{A;6a$K#7t0} z^QyPX(3GS|j8~#f#je!3AI1EY`w0a4V62H*eO+pf<_YlbA-8>tZ7` zRg46&-Jn?3GBx8xZq#_r-eR&{0}-%XF<0mm)YPeVU6^;%s! zEs2N{OD9S&2}lA}0!mI_#ZmORl9ROfiBeN$NPkpT+8OMALFnuH8)MjN48c7l7tR|$ ztHceoR4h0Tnhs*DJ-tjnIX$t-4Y)R{EDvd?CnEAWe}6*tyrcCv|A*0dbklZpO3nYEUty=j-q053I#Ws9bVKT{fY4lM3t{BZPvUKrzpFXTr&IABiSyLx;#9RW_*vm$ zMdi)Y_%OOvmmBeD%29sBMCjqu-^jGh8;JgIvhoH7WD(*SK@AN%1qyXrGEuM zG0A9=3caH?`=(b+)YZ7ic$4}GCMufTVU$+Un8~DaSdJYylj#zT(N0c&WSr(>IRU|8{*ilJb)<%xh z#_LteZ;Zkqs)$LxlV{pt2eY!0#qNo&EAv#T3c1!O`kGVMCZ6?Sydulwamt~XzK^0YG}JkNS7(&OI9{vx zo<0<^6yniD5s}FKYqZoXcs`10U-_kN9fk` z<|{oP$lG}YOQm^@kH&n_E4hAptuo)l$oLtFmzIGFN~ILzgq^~L?9s6YCJ^RJ!r=rH zh{N_x+un{H#Nr%iCgzWSAjonnf-IA#6NwR%ysc~=f)%w*WfzvyGfv=2^3)T;o(dxH zwd;Q_pc-ZY6+*V>QIOi+sivRDY;!1CvpIK14zBJ-yFyHh>%52gn3l+M>$~qRiL(-a zT22AtovQ=Tx|760!jo+MF5`_m)`7}JVqd4Kd8GgyYCtE3LgL|nESS0zHIVouP7lN= zY0X)meHUw0uA~+Sc`%Yxc<*H5w;Ga=9Fj$1d1a42;5ulBd5y&h#ly<5xHpLoW5I>T z8i}RDvkm?H8HrH$#4Gi-pp=T6aUZ+qVP5L_g|Q=y*Iz(%%Ojba#QPw~Aa_@6$vOQD zPUng~#1=p8xf4l$Y^<-3UP_4C$hAJa7HpABKYW?%xtehgfz2KaST^x#EW6v+lbP=_ z)g`W8748G!wQS$Hddff7Rk;ymTGhgz`+kLT!ZXgjqcQ8|MC-{TsUgzlv+GzGpKL}L ztl>8yrftJroM*0a-8Nm5_(?=_3Niv4_L$m?_V9U-aBGNvg&1X2w{CN)Ue215@6c{w zb6Gh@g<4p~8j_rDVI*heROe>D5azR4kv^o7JE<*dTemrNaN&S>hp55m{oU59qdcLqTeECLqAXv={`wQj?i5c)K?Y zxW7-zWs8X=a;R$!Lds9hU?>kQ&LI^kuEen?i0tiu#%zMZ0GC9Iqg!E0^R*)ZUV`~L zlrWz3ASDjQFpLv_4VXI_y5$&UCa%#f{&BK7$wvCTgCVw?S9 zoBd*&{bHNlVVnIbmrjhfY}7EbPgx-vsWHR5Q3>zSQq2kVcix=b#pdCSRF3U5BxzQw zrEluI4+zmT72_Rnx8evqeMLND$ate`$?!mbr@4j<+NWK4%jb`gmW0}iHlG^ItP;JC z71eaE#;x7l=q++%-%Fn~LP0)$Y|^;X$6|CG(!^<(VmZ}$>3u!B>(P06i$*4AC6NUm z|BdeXzOyk-$$&UCS09eF)k%=>v!|mz?5T}y4d4`bvKd`-GUBt%@a-l}mO~8D7{=v) zC^sl-Y0Nhz^@3%qe6+;EoYFmFAU|wIZ_K7*W+v6vQ}@axF6bOtgA(mbB-DCaBX!-# zv-u>y5eIFY*v~hkdz+CTMXpEQWU|Xk*~MQhYg4-Gg71H zn{9bDs3qia0Dr6o4uvh9_Q^~Q-k~>)fGoF`hsz=Nqd#PD`w_Hpvvh{EDdmC>Dt9a! zkNrd9#R*x!`CH;+l+$q9OdyFB~3+nwN=%B?(27m zl0s2F34MmKc`TW;fu89E%Id3^n=(GsM)7Z~J5SGz8sF6q=e$WOsw{A0ymglnbR|!BHL=;+#KvfXm>;6I8>0~t4~*$NKeye{hx3C* ztz}!RT^RC=!z$cBOCoElTX&d$KuEWo?dr;P-`b@{Y2(uJI2WF^rCS;M*Mtz5VzrY$ z0l3{0$L1_c9d0#9HY)*zMx&evh&3^skv0cDPw+`Gd~`NvqfK=yg*Fl-r}ISX&r=D9 zjaF3Z+?+<#leiJdQ)|u&H*&vKiEw2@&VJYhYCj zdW%KSLtunx+z1`HzoA3;@kSkmbS~00&T}QYJl@zK<4nZw3lXn~`ugc+^y)l0MMci< z#-ut!Yv0ivUI0EMZkFYLCv_Nj3%8u7({pR@V6kOr(GfrwhOA9rD{0%NYcp|J^iG`f z=P_tyLB5}NmC7MMAB962&E=A-sevbo0P{^R0j8eLzk+-~J64L=5v0S)TOnIk{$5a_ zwizGnhTGC=itiH6aw_4YV68~+H${GJlEfW4Gwq_T8BDg+x|5%OxD|Ep%vr*%M*RYF z_w4)}z9`CyZ}_wkwU+0z#H1a* zY1#1MXs72Jn=V~#vsB|4HB-e%4cnu3EmH^=Ihf6YC`;(01^v43t_$iz&w}d2UBfn* zPA)2Sh$FOw-;063G+hqb2fxpBGS}TbaJib29FE2mKEbJuOT~-XVRXT_wIE)^F^-V!k$Vs=1#a@G+d9 z?O$#AZXsFlBC_D+J2`mC%#x~>Fgw{S&ugz%6@_!kbLKD{=3t-o4&}WC?>NkGOp-{- zEu|n4Ttr}r!BIBwZ#R!7a1a2cwJOCa059Q~q&;$f<@K0#z>!a4=VS%h(BM{*VkW(G zm~e+ldV30eOx!ZjFYzEoI(?fnURH+mr;&2(Fg--nJnxuQn@3*4!zLP=A6+KK=c|jH z5&E)3cAOzEZliMh_R|d~{7A0UoY<|Jw>+An(khMNGWi=ISI9JKr4o9!2zyd$&e*$D zot@`@oF!D(QNF(}>&aFmOK7LKpfY>rKk|Hr1_Jer;d}m$_ zM7Z)^(kND(Mk4a+RkfAj)SGZS+VeB}I>CT{W+r8OLiLw1UOLw97(PaeFL#Wv6P=7EcM62KM9}Ex%_^oBK@Y$x+f)ZDeo#wB5#P=;GbxM7zy@ z$=z+%WELRr!^9eWA`2^ZhMA3nku#I%)h%kn*rw73ODCqUd@5ILwh1F!tkHzVZeu^o zr{=L_+=g12c-qSE-t5LoV&f)S<&SkC$BP!_P1DGJeFO_KpKKBEpA+v%197o9 zoSbD$OGji=Sx86=lKNrG6t@R@<^Ms65OZJ2wbz0^-qXPfMbe=W$$n6?2{QS3svCP}l! zijdMvQG;vJyf3U(Ukcb9NcmiV27&&Mz+UN;a)4h@)P+;o*-E2sUx&eeFt)VRSOG`i z1OIYkDpe|+MT2$N@7M+VyUjl=?TiRDaKkQL2CiR~v~1O-w{%Mr$A4QryHJT@B5&-R z29&Ed`;}J5d|*^nh1J58iK;ZVREy=emd?6LQ@E_kL29Lol1lyRGiUs^;Eip5pQ<}a z_nlKS9C!=eSL{~+Q%9Yp$gKwx3xj3CK=i$zryQ&%MA27xkHKP$C(kDWm{qx`FWQNVs z6qDq{5e)^zVh=nidCU2RCskc!iUY9hY1G~gB#ovSw-Bl6ccDpSb;{3yo1Li)zIs8+ zv(i;N4XT#f-x6(qa~%~4vjVte#VYTcyrj9oLdsaH`2~9w`;3efG}%3BRlhrZ-_FOo z;;}FG82iGV%q|yyVDO9m2H*PB!O!;?{M_+P#QNm1&-WX9Gum3}-{c%nu9-7kiWFCn ztWh3D7-+H(5GzXo*BZ#?a*Pt=Dj6|9b0lwB^+qgk9~N$Z-m`EiXlq5Op%Y(=44Wjg~{C?BQ%fQOE$dYa` znYY?5t}M-V%qsU*jfRt{w*$AaRicCRiJCTtei9FVk%Ckf-;G`sZkzDgiQhjQKYLmW zSg4zwZzA+g@=!5%q$5ogizH@p_hxU-J2{&$w33;?-{}H4@zyCo8DpuHxS)*Qft3q1 z1)HR0yj`*gS@!i`{3adV~Wo86TOw7<-jnlqBhI9q2X0n9=eKBj?-=VCti z-YA%Vyva%AZB4_Fgq(u|E|Cyu4;=)9ADlby6hD1HYrwQ(Xq}$To#oEJLWtF;XP)=g zDw_Gd$=czHs0`K8#U(M5IkQhqXXi9XyuDo1awZcVtXREV4K6P(+#sxaun1HYPDM20 zpxy0#>SVdk!igSBeG%|@epzrR_flQUb@x2$A6n3Jt(ua&dl>&@t09MgzkMrv*BiuuO2Rt_4L zeLhA2TsujwKW-p1UQNdwgi`pg(GRA^IuR{lq!oMclRr; z!Dtr^AGnxmj9$pL6#5RA=hDJ`M#aHMsd&$bfl>$NoM<+PqdK3H2#f&F+(cZNlbBN> zq*8{@IT1zZCN!q1UzOWYrNxWA>u&T>%&8cX^I&Gbl+!GU2t(_DzChZUJJvye@a~{n zXAX{!-Gr!ZQV{mSW-u3ss`Ty!GIf+td*hKRX<+RCqCzG570c$#ltWckzMS~Dl9nos zXS8ujOwGskGYaDw#-K}k z$c91$gfm+PaD+Z{OZ+a^!!rbb+PxPw9(H2$DSSTWF<&eC)~MJ2U2rR}tR0c#Eke9S zN13ynoD!EDY$>Ct8j1IH+>GoVj9e9LGl^WTe1bzPE@ei)iYo&|Ot+sb5L8hc$sA^U zOdb9K)>K&+s;adhpGlQ|U%0V6n`9=;QW{3d!5z%SkDJlY$%F~t=cO%w`2J6jw&436 z^)-IjT35_^s!Wc(}BK*%@36UOE>?-sLhJK4sUV z+ziNKL5FJYB^0w;{0G^XpOfYI6I+P()vufKulq(E*>QCmb@{@(3jRo?n%EOHnS(>v zeFmqwQ)|&!Y}dGfQK-)AT2=7Od)@$yjW z0PQd;n5`61?;NpzCE6BuED@3t=7xm%TrX~13(rVdmlalGVJ_ZzQIffM;~vtH6CnaM z&7~v5!WShN+SDQ&*rWa8y_6OAeQ! zk{?~a8=7Cesh`{o(_ZU2EgEj?s>N>_NWc=eYDLM4Q|;SC)+_qi(I)X&onQ^4&@Bh+ zERp*aGtb0-?wY|~zY7xIG!C^T8R1JQIMkOQOwQEyx30VsHt8wM))lNS^! zPt5qx31P@FJHoI_jHo?RcP23w%?$L3s-lD!;M@N8dDMORj)bTn_vi8=Ogdu;DkU5T z4^obUffZF`H4raKAQ|e2*-vu4%X*(=YVoBi?uEI37573DH|>}N>VuMh*n}PP%ZUrO z$8Q;U$W3ucXtwl@+0{e;&Y9Hb^xxVqCFWM2zZ?>qi7qdU7ciEFasbksWe~wSt7R6nH@pLb87*D$SFVA?o7ezTnmlt1hjP8+R)W7(W zWAsaZj?phUM!)13-JWCAyZDl0v>?am?BdU!V^m3*&c$dyvsPdYf7s-ej<*dl(i(;r z@>{Eehd)IHIj7ygw|5ORaQd3?(2?Ku_~EZWW$c& zUXWcjc`*=VXKGH%k-_{x5$&Ab|Y+;P9)1T1YsS$cP4| zYGHD$OwOxVi3ky6grYLbi+uvQjhrNZ{>7)}Bq<@~mr0t;?0T_+wm>`rkWEDA|AuWhE;sv(ujaI|WG# zr`ir3c9YKY#myaL+iFR#Kj%|rkntseN9stCQY)$=89r}RI*`s zT(>T9P=J~mhrkdT7H?&j=)TF@15MqDm8@e&RB{H$MyW6Cu#zVANz*DT@4k7txP5!) z=D178t9uu^EIydk-js3kNBj9AI3(4J63iYvGE#t0f1~Yswf|%vpI7gD@&}> zgXb1!z1TZ7o`}K48$F0NdayOsSA-X-)L(H?U1YF>iE?&EM64XgFjXYCOj+lO%6%u9 z9V8D9Kyg*=r)1r6b;c`K)m2R;Wl+Ofjsl(B1=I$4*DK#p@I)5woXGWEqxWC{w{6y#id z4z~eP_5n!E!zp56S`u=Gl3b-%=5W;tG&#?J%zZRs2{7&Y1CD>R}0K?@7X3 z&OS)BO(b(kJEyO5BLXEY%W@XZoOx-sfL52Qi_YgI@f0mN%SnlUbFv2|q79sSz2uax z2+!SG=@;+PYz;45Im-~fz{J_DT}fS`WF)_|nj?N^0s$4x`j_lhTq4TkFJV5a8G*Cu zu$|LIxt_VxCHAV0fIrL|U^8>4mATV4-8}XU0yQP! z2z4S7R)BK`4NZ7|=0x8Wx#k$rw-BL;m*~w()Tr550#E>&FxLo11OdVM__CIWvbRLx!T=rBSvE!*bep|xW>8Q$& z=HE94gn$EoPNK^EhC4Y}(eoy#g5_UATIow#P-nT3V&;L(BO5zQf-rk=TyehBq&R7|H}|}^0q3yG zGEKAP9xH>==74`-fHb-l1Mxo(LfBHYHTD_$t{ql?xVs|poe{?D%Gh5e6wvk;!q@(1 zPrq=^B(KcFsWC~pkvmJxLK*}lJ&~P07UPQ%tjSNDl|7fs`}6Yk!kf58btYC}#zoM< znc2!ql&=43*^yOd7+fe@N>($|9!Up%UC zvPD0Cs@nT#QZahesU(sPuSQp|w{#`>CsYzgqtSDsQ*a~H&Hfc$Z&FEqXu$7=mL?ec z-hBS8J9XAG&mX4Eb&(;`c1CfUXAU2nRt}Yy4@`)B=Vo|$0o{#KZ(YAv722R0Q5n}` zHS2rggyhF9sKoqX-QGm+&qn&n8;viZ0V>CT3sy0|L_xSr+Z*$Z+2L$hkGw1r`k>_O z%a8?PlUS+x4QJgjjby~=kl;6Y?nyA%aA`{_yP-oo!2M}i@)^^*{}^g5preQ7(6A26 z+xoANB=%k8T{tW~`U^>_oR*H?3%ylovB5^iA*0IKr8=mH(hfdSlES#SRz##3IIwHa=24}#WzQtU@GVy-Jw!k%7mt?-qqs)*19Nz=@izp=+4ol5J3(_MrgVb)svW^!?VGP3Tw z=dSOg6$z_C%+zQ~_#yqs-IX}B@%f^h+f2nM5QWY)HK37e^A8M(t5DvU$w!p0z$|z! z9Td1(sez1)p+Hq(Ht<5te~%V4sIpB6-1cfhUQIV~Ow8E4xP^F_Wo=lCyOqGGxHb6L zr5s|+w$v(!D;}OEzh>u@QC{tTKl5Yl!jk+}`K0XpTD_O~UN3!)MqSNW!HKDS64UhJ z2&!o;g4+(;Ym?nDQvJSO1m;mM_?g>@cNVyQYA#~9m+#-|7zyn*eaSJVJ> zwV>QV{B${U!_>ND$D+#}D)XB3EoV(-_u15r?n6!`=@33I^Va5=2+(BK~MnM%2S(}cb)N^e;E18`L|hGLQ2+T z3rkp%_FQT@$Y-i@h4t)5E2?c_K`^p(0SlvbWLzd(zXAmq$`})_zK6-PH#Sl^lS$d) zlnF266 z1PgDLuf4YbJiji0+W-A$Z&UAvc`w&BG(#0>ySYdgW|f2XI#pVN>A93J`}wO%c|nra zMR~=ZVgGt)Vk;c3Co=6f%$B3d-eELmSMw`N-X-e`y{{G*F!qmsU1Le}D%nQVhUv^Q zr{u(ccR;LvCLo46Pz+HeMnN)NVIs^0}SJ&`1OVQsfUAe)1?!YS@tI5HjLmrU4|Wxl%%rcyv8X>A9#A1WJf zI^7$)ALN*{qWsPLbuwr3-qu?jo|aJrVTM%D4_`icJXDRV-B(G@%wqlinfG2vy3sC# zeJtJ}hep)~(O}Kih8hq`!ntMp&ec=?y{@V|x)g(|ndQEJUqJ}wq7-t=g7Pbs!Uwmt zC2D1C|1et(OO=L*CSjI=;G6DbD8A*hfd7`msJayaVHW)qedssUM%0VgvfjFz%T*2* z-6GkErMBh7egBMvX+-q0QStO`*{#v9BZ7c!agefQH(EB|w5 zK%zGx-q9$3{gF17+1}_DyBP5#5xJ0@=dvOn&qh4YrOJjCeQ`MZx(>cowLFT8+u%hM z7Mu|@l5gltFS96;Uf-MDfv@BZTmz%Tpd$~vXlVJ)Waj;;(Mx8Khg$^OcPSkD*T9>2 z)#&{jF+cxV;BDebUR{@e+WusaB|6i)k<&SP$TP`*E{6*C(E%h1+x1fw^HbynkVDST zJulR!Ma-ELS2h^)^Aark7d}ljX~~y#1E@>1(?Xx%63Y2L7^RZDle949POY#GL!2!~ zv2D2{UJ4L)jyYZ=8L#kuTPrNcD_hDc7zeX(nTd4YI_>jGGNaBOvCL-~Ax}*tF7Ubu zLU(Z>`H9i!e}i*Ft$%8&^;6$qKZAV??L;9(5--v7Rh}Z{>QA6Zxw_b%zUO#99{L&v z`A5NX&Lka2Z7D6rdIo1LcX)PTL|k26l;wXa=n9EL5Obwo<}fSV*WiC+t>%|VlQN%i zZt1n_2h8m1{M8(nwRF}6xyhnYaIH>e!PT7`GxbX}f2RA!m_R3x&KgO6xf`Ok%jdK$ z5Qno`+o&@JtIt#S>ex+2Unx-kFfC`xpOe7HHVcAX&L@P8*ZiENrW;!sM2cUQ7u4Ha z)%S(V7O5@YWL}f6X8|XSn|eWBy~DrJ)|ds=xqih$3N``}8hGLIek|xN{g$2?r!6(V zQHCa+e@p$1R3N;X&F3T)RF$hMi3k3sbUvFSNIp?#twyUw|ND>s^1s6rB6({0V+=s@ z-#S6*KmN=A!gY_~#Y*e%0Js0+zx=Q4z(CJ@mosp1-B0!`snJ8#D%^Rft;_kOM8wY- zPub}fn}mz$P91+zn)o>TsW%6H5FF7Gxf3Y=e=xDNm9(F5O|^dCRpu1r#y981c}RGC z3D;a(rWASj(!l(nRECp=vk7ih6gckr?9y8bF4YCQA}Q!6`Z=^tR5Zrlmln*?f?xci z@`_Yz7fdh1``*=Z%i<+{ad{ce+|ng&RcAIw-YmKfXLBBrFQ}OE)~Wq{`S;~9^;DvE ze@WUUA=XlZLjSla!?~$^CTUt~v4omLb*2(4N zOkIM1!R1+0j_MYCBth*Dqxz##7&XGb3Y~ThY%VAklq_=@RR=;TpKK}4Peix9Dh1^Yyg*@vOk+q0tTQ5cf2jg5 zMMZ9;+Ng0}$7LK}&)h4fw8y$i-ylxQVyas7mS7CK6jSAf0?rea}pk zwdXTA**y{N;xk~5?`BX(``PRoE>Yt%cTb>4ZT`U#A2|!xcQQjB^KD|l-nt6uq1D+% z_xPhzI!X4NgnaNvr|{Ta21OH?M>#|#ZyX1vT(l!z1J?O1}qzI#s+5!#oqKoCNs#e<*v*6*h__(Kv+9>LL%w4g+6 zpG!nF>rd|xn?zi}#9fx)RLDX15~eeA1GRO6Fscn!+XWug@jejJWBe?XS6nFaKp~}n z=7<&LS9XF#3q<;Tfy*?Ke--W083{ggW2TNIRkH=>)MOUC-3cSr&Z%^;52(~oJ`1Em z-wCGMA*EjV!;s>4!M*WLAklBeG(Y~3h_Z`Nm0b|y0qp}QdGU8_w=FRwb}|R4zRx05 zUM=}z4loKz+0FyTfhw7Ld!j3=iH5D9LQPy>9QB0aINJb~UN7gge@;*i?iLne{nl=g z0nvY_c1bM0 z9*6nwO7ff3gzsJhshh}YsJAWy56v9a@1_Q^!ZoFhEoBwDe@l-(G4DYxy{nyacr>lt6YmpG?fme`1e>E&m3B#V2{vz0_;xH|)h?-e zo4dKVta33uvwOTdv}!c6v8o%Dg6S4dPQ^(kW@8c~qKGPTlD#(e*oP|aa;vs1(c-6$ zc?(UsnmS=ne_gs)2Zif}z)`$L6N78wY^h2m7Ac!|YA9ysyJY*HqwWqr=VTc#iH1s{ z=cO0A!NGPkbrdGLK+b^k$jGrTEP&YBem5kvEBekega=&W0e?<-aP}gutX&L-ds2Fv z*c^utkfxZ3a0WJ923h099y8y?g1@4{N#DPF%7w+gf43}pFk`VYZ9w@BO(6i2gZot+ zH^+2OA-$iw?u27+Kd}^e-o&}9&$-ORH;_m?hEk|#-bXOUvXO|BM_h(ePZZS%D7;+G z!j0^EmoVUbHb!Qp6oBqa54=5=yVZPpK-)o~8jXQ*l4eh~*nrNwF!UB#4_H{KCoTsm zr6*Bbe?2*Am3sd8)v>|L-BQj+nIkg2N-%syJ`&|h?CkUs`IthcDQwBZMWe%p>TIqA zD_QG&rx%bot-QV1R;M$vmJW|EZ1#E{UR>PRT#jz|<3a-Q{o(w==6ugbs)k-BbX>6~ zAJ%1^X4+O~`EYpy(K)wN;?ac?bcqjBc5-Jje|Z4=2V!%OWgclFx!#EV{ldOp!Fgyc zZXI+ZnL9V&^e`One|d59Ic?vjq1#!ls#iY!%e+;h)K3}>-n#Cp>dc{%i<($C?}yE{ z?Y?Ih2%UsLHKa61YdV6WOmxPyh48F&>d=NWdTjDAH~4s!G_;?ur=F^nS#9Q*bB ze=h!9Oz!&YggY6b6dfex`}2yeE`Pd2MG!BDYVv5eJihsCDS-gD>NaY)TsY!?WJ_+t zZ`t|dh*xF!er+?kpr-_{m!1<4vNr2B4TMD9XUmt~io=>9bmv`|Rb*XHQOFJo^6OOWP0Ue^F#hJm%<2gbHy;{qSmS$KeEYR9w1M9?^^l zA|HmQrxH|vz^ZMCOzX*;SM_b?VNN9}`&ITWZ{bFd zf66>gSF5sr$-EMi^kUi}{{!dY+}aDd1pr>boa_Jq delta 19003 zcmV(-K-|CH@CMuP1_mFC2nZ-hfd;h(0mE*8n$JV2oHYLSZCyF8VI~pIScbxx>qmv*B$Z;EBsTrt-Lr*M_GDv! z4!t{C!el{X9^K-Q59`b$>B5N_(`-YE-PIvYW=`7dTX(OdLuQtg$m8G0ksIF6na+HE zx}MUWTgi9&h8_FDWIiF_=9~&7At-6Vy9CD%ZYsz|MdU(U;bZ4CAimr>I3V}GFj#AzPw@SySfZLJ+zX=BCTgDSJI=y zvnSw4U>Ax=Vwc@O;$&ml%SsobEG)t3QL|-h8iuQ2cyO@7bOJpcNK*$~;Qm1MR^{Ff zh)p~_n>)+5;LmksNmaIv^$oiJrkapcq)*kZ++7w@haug3LMh4Uo2Wb`fu*W{mMm4E zQs<{erFW&mwcjpA&=ENSRN{~v-d#FAq~s%cfHeCHKhd)m}{@3+g{_AjL9uW}Vp^L{ZOg`4V`Pt`c6!Qltkk1W+6c_ zT3n;xXl8^*|C|vXLo}-Z*Ua*ziyV)yxGk2`F$3)+D&E--@s%A{?Z_s7*mpnAWDNS7 zoXiXF3MDDhWkQ}VqGaLE7o)Zj>9ELb@C8`4C+=kCl&$i@d0!Prl~S)+U%jtb6?wrm zd`llQu#`bCwTdAFR+$IsS)k2M==rc)ANK2a^|N{6S+iXqwwm$N#V{2X$Zs{8^5D}|lc_MGVfQ<>=~}-RYxaCmIVdwsacSn|y1x+Z zB`@`nHxEYWw-%wX>7Q&2sALS`<>KIlAVchwTrhUQX8v~U&gSL47|{bBxY_)7i==;P ziV(Rmak!fa(Eek)1a-B*$E3)S=#KPHVu)fV>C{kJ42z{9zJ{?wTE$^v$=+W~uAwr8K!QeCGUvR;6;s zHFe+dc#e$IE0lumiZgZ1-1`4GKx6P#>rTkd<2pYrdtAogFu^V)^wq-tc47ZqAdZw@ zE%<1lcd$yYNUpwr*2p%z$EE?@oc8jL`WjNx(dHh0ySOpjlKK9lamp!KJAPY|0$n$B zNSo^PecKum#^ya~(G&b_S~s>HTw&X?J>zER-9zibpG{8HqoMp#tX$mUOEwh?U%hw3 z_qdgk4=%HWcA>rIH%rVl%e@-|idlD?d}3yxxNX*i&&6YZSpA@(kZC z?3sq+>jg=Fg2gapT3BtcYsOE@8l1>}m$__RGk(S}{0yTKPUyNQQwHq1#GjpEAff~=b;nZ`E zWH59pKY(?+)gW-vhsqYF#;9a{@i!Z>J(1qgXT5mAfFA$lySW zT>b%P4AkuQZ_^wj<9Xx)BT3LK`@3nyewuHtGh{rYyGs?vnus3i?mbwQaNRRMO7l{0E&s3B4lt~<`I@F!xEi!UPc2HAn$EtyG@#FxvqKaL9VR$96~N%EIbl}(t-sNpqmfVS-Mt~hu8DB` zx1&PNi4472kgX#{+d4l(FAtxfff<|(%g!kFFps#_oi66KE=%g@2Tl}3fa*51eamxy zl&Pkx(XBCj{|SckN>t}kk7lhM-7lkYcw5F1$1I==HnojEe!RpVP8Ur5BzK3@EvDV$ zBt)p$;cQ5|-^q`onqMSqcBc!NM}s~e(W~Q2--p%Ny9`}>GEy}(lg6&sGxsWO)q0_h zch9tqoTqYs`0Juf|GU1i&n0msR3E`mDOTdN*fhB!gI*gO?3d$IXcr`vrU`$}oGnty>uiEx!Uh629BkDszanwnFrU^Eq zJnXnwE)b!7jbJu9VTqq!tRauDpcNZVA_HV_$AU8NCQ+;)_9@?_3{F{I*|0fX%)K*b z{t|91Q3cQfb5byMd{;T5Z*o{_y7@0J4$d}3;-ItnA`b2$4hEYq;@}r?@QXP3MI78N z4kChtxR=d{4mZL^cR7)Bjo7(=$#AwQNB^UP^~I#DWv4g#LQ?$TuZoJcP7q~3(dtjU z3Xd|r{m^W{NNb}$N361x1J)^6@GDNpqI)whC4UOHem$SPr9r24#<|tf#iKaO-x$Xz zw+8M1Y%(zeGyh<-(j2wxzGqA0=NqtY5N09Hs`2@nR_#&Ca1(sCoNuy!{P?Y?zzx>> z(E9t*y7S9=XjwGXCG1Q0{PA>VhJ+{U!t*;-M_z*2Mee*{f8OmMiO+BR&3zv3_HR^i zXoU1A0XR_jPDFHh3?6FeZER+yl9tGr-QX(I{Ko0b3t%(CwFR#=PJH1W9sQgP^a6Ok zLauH%WqV0v%dl*7g%YfPon(Bd91iNk>Ohh)sIGn4@9NPl2$l72^vQ`0Y!M zx{{;{`!^x9gRLFk%{|FZ#_8`BuLS>PaNhS#!lCn45DkbjQ3wI>mXB%E7RiewpePb? zOQ9)U-!KRjY8HLzZ_1YJTk11ep2?tMwpAkFN^qG%W8xg_^lRLI;RCf-xAmy^^Nv0j zj!*O8x<0%QoOxldvM;vvsW$rlUGfKTzbxugc2WT$Dmj}^s?ldV`omz8mWYE$A`Vg# zapdtBySwc}^t6CmiF9aBhx1qDeff@IQ)xaiWk3y3Z&S*e}4(Lg7ysGX5`TFy%F(Hq1& z`n4&s)vh1FMX+rBt$If9LLp0-lbFQ!2o*$zw-Q>tMWa7|pUwHr;mj5W5pw(N1L_<( zY$!((s4|I=%8ddFE{mI}{kB5IBzFFlI|sk5+zX3kauvQkiUev?38L>s$`E}+<=-m*HI%+*+{@?r^* z9n~?HQm9Hrh8z3Ml0y{JjV!(D#CIaj99~v)XH)c=@z_@WV2Gpt zmWP6heU}I?_KsHlP#9*V#k@%zGQmU=_~0x%Tp~pD3}KqdFOWj6 zq!(mfg$AmmKx^4*>O_#`MRl-B(zd^#-BLMpRwe6$1x%Eb8Fq=;i8~7)9AK0kx=lK#OP$(x=6JBK@6F?`UXM6E%;9)+zH!!)p#&9U_KQ zo#(3eV0}?VfAQ+#*U*}Kmn-*_1cl4MB5-GsLu$Pgpz}N)EYk&FoI?;YU;s~SMaB*4 z&Pa7cLI{#Y4&y|SbO+f*7tci#sG_B7LG%oNGv$HNU4viB;L9I^`D~d4`JEKVN4X$> zwA=^c`LGUF&N4k>o^*93(pikQg6sJ9@5_?!925yk?62%B~{1g&f4>#*%(Hbr)QpzV>EZ0?7OQ|L_Up;BJGt1_5b7l zQyP1hd;*W>-uUg+EO3)s-_Oi3l1g`fES+RhJe4E+k4z@JY$8Wt-L$AbwC-u4zi9RD z33WDEkZL55NeT!I*c!&|tHPzf8rHxApti1oE*=+FhDP-+O#fFst&6xiQ)QpS$tAeCoROHSp*xB1iout+!22Bj|Jc(#jSXtf`J+;E+cBvf z2m5C_$unqd_R25)p3&|a<(`97ii91bl(+UBrdypYR-PZ0ocWxi=vi%l!>UVzKx|=~ zaueZj0zS^TwporX4j0#|Ndi>~6iymdM;^jJmd3N_Ty-<-9OCM=Wc^ zAQfOZ-iy{1OXjOvY9NGGYFSHI)OZslabWA({bM=0g5~@pjBnmzN9}#C<^GPr80{ej zJxW8klTTl7;oY#_nl;N^Zh39b<-YgyzTDlpzMqwIELhGx+337~mD8X8;}%Z!uw&g$ zZs6zlegiEpq6@bX{RK_&6uzOk;$c)5C7#lDc_pirg3|}fE9T)f+kJQ$w%hWp`p(0P z`%qKR|8bU8`&NT3DDgiP+G03t1CB+z{Nky%kEh=G7f-z}o_b$A^}cxO?d7RA$$09q z2Rcz}LoYM@YHFu{?W4ox`bImc>xiePoFmuWR8@Fy(A&2gBo2Re&OO6!HluUg^xWh(1Ns#jQ7@eGe3Z%1rBWD9>E=^U$%={73-zh>h7Mo zBx>rzcr=fH9f*-62dkl^d$84u*?t62l|zfU*Vw#W0!ZNq!z?kN2<5B3#_^$`ZJ}`~ zNBMWurLd72@1CwLR+KG7mlei(CO&xO&y8??J-$Q9V1Ut#WG26)QDN>a{rUh>^*SyQTeJki83kFvCF6WbUd)(B@de#1IaQU2ax+ z%hYfz8fR%sNy^2H=n%01MdJ<~Vmp7Hg@j5B$pcFjOFZ&c;^;gS(d6#p@*rHw5jO>|o_|mCm@>bX!tSryS(@kyz_^<+_vH5%~E{7!jGX zz~gL1LS~CVRY>=CfoO6mw!4Qj^I3Rb-P(!KXx1)ouX1a&Z@*Bf^YI<(*L*&I z^qv!t%U>-7P>*t&&y;`B?czmn;@Sao$_|*5&*Oke$JcBOFSC?Mm950=>_ zPp0W~iHm8=N^86@!`PEb7cAoWK-Z`wfm`a9{(V?r0Mx$4G8SvQ;^^!$*rW`}C%fE8 z#4l15UtCcst@b*?&0M`#(#q}z?eLB|fZgFsbnD9C! z#&fur$8qA5l$&w#88fVpkn3*PNc$4g*z(|00FFXMxTwE*8I04-*xE@TeusBTqSmo) zcA59n&E^>N^X4F1LYcm-n$0`Nxc0mAf`)rQ7Q(U=qJqtGm=pP+FO931weB4odktRkd z9-v^`@GHA^4NFsmyW40?UU#yG5?n$d4EW=cKK~1lFXA<}xE){kbQq*oEHMODP3lu9 z_l3qu0+qL}>-oyqf~jTok&3mn0wTEt$VtJhzI%SWZ9>$8m4|_Jzhe4-MV}O{i{@|& zP=IR#?sEO+aD?s4pXf#%F*%fp31?6mPiN7*=4wj#IxlC_n>@k`Ke6QbddC{F8q>Pt zg407e-z0H%bE7|8GuY!sk{_Me%>sBvgRQXvy=b@$XLe;10NzPdz0b4bv5JaV$CNd5g`7%86I%AvLJsEJ7NL~NVyy>*wT94wXZ z{EG!vu6mQq?6}++1S+j2MN+MQ_>}YFj_7*rR-utCv4+2jdI}NNp(sf>)g`l%)!kyY zT`mNPFCHCfb$%u8!;WZwqxLNh-)tPT8OR(8gVx0vCSbth}Q{!=K zvOF01@#XpX?7eV?%{^jECbI>OOK~Dikj7Z~PaUwK;jgZ?BM?>pKmNBT&r9X#L=`Ir zYz{iL&_U_o!lu`MEWBMw^E10grj?Xw;6=*Iy;=d(IOBS1cG?b7c5C{T+@U8s32W{< zJKi$ae2?CYUBInG-n?0VBZJx`TTfydRj!MT&{Q!J z#CC&XSTD0dWMDpzcCc@y5*8CUGz=XbrE_U-n-P6%q-oURQI zE4;S1L|N2-WujAlzpz7tny^a|xGvMRN?eNIob+ifR*{>QaB*=b`*|#_^U|fQ{{-pM z)&kA0Z}rt$Er0v+Uh!>^8Or$^pwj~DfZhsiLEW`O?e&V3zAmtH*vWW z&eSmrq=Z5uGk;zo1}Iu-!PsIWYwot}uu=luN%)$@+l{>zu9v~&;47@R{V!1FA0zLo4rW207HF0Vz|g7hKoM|FKBjHFCM91JW{uNq}pej(S~@*^WpY7IFjzoTRuUanJ1n~5s!2#M>MAUE^!o3f}v3p zu;I22y7f5I(P^>Is~JUY4H0=ATgD#WwU|}glWYU;^Z~CME!~~oEvY=f_uz2VAmL~N{dZd{#TT5Gt%PFHLJMjuc)}_ zB7Bd3HhF0|ZHcl3{mi7|oCS|q+iP1&G0ay_RHhrW5^kc_XxNv|Jejg{wz#+l9)vD` z*e5_>~ioa;;_anlW{y8=RUp)G`wM?Z$Ckm_(0)mhXJfM1EbxhXS!m;M!h1jQty zMJn`;+U%QNF;Q3JBI8Z!Czz;ca)(h`MPnwD%3(Qn;7q1VG)kkJD3(*XM3Uwc!}~iD zHgc7~GGX2Fy!LvcJh;B{-SeQf7IH$sU0Iw0a6%`_YM3dG;@+98=ww4J7(sBlN|u9B zj{NZ*h*m_LC$n(^9}I_a1H;^Z-1M$`0yp;T{H1@HY-L%PMpcoluwq9gaakKVQX8*V zDZeoagQy}V`A(i`haJqyN*22(x~|Mqr7GlFqv&f+U7L8;hw+Lmlgq*S&&W@_Vk7IT zy{tu)7kYE`Q|%zul|zllbx)eQW{n+vk`pY!IIW9dKl(n3#?VmbT%A#W661KS;(Pi~ z$Wn+$6GcQK_pi}Xv*7tCrhVm?wsj!BXWP-I7+XLUqhdsPnBy8W2Bl?l@hDZ?k(jUa zd?0V<5iFJFH9i{iMX%)g>9xvy6C>kiBwktuDkzmwj1zVW7qUmk9+*IwFA0YeOdt;1 zH*I@6b`XnmpqZFIf*{L(tq8JAo=zl2O!Bs}c?ee2HkDmiPR}@jE6Gz&2zx4sz}K$- zxqxbz1yl&xo<~7yd#9Ry9<$A%WX9XYtV8|?})Ew1w(=3`nS&#mviyClv^{AoD_ zh7-;6a5XfI)_lV``?r9aNM@w1N?KQ{YxYk@zeF7y+Z2P(Fc!VGVb z^M9gb=HYgK2Qi`oB>PN|UmMxCNrldY z(u0&Z7{f#!=ZDGo8O2(b1Und?Dbeh%O#-bYgXC998+?kA7aczd2W^lzwGPR}EV7C! zE%fnbbhSxXNZ-;~Oe}FMGSm7*aqF=AXgkxXr#sr??xrOM@uy))Zck?au=J2H&Qva(~zWDt(Ly2 z^FAO%(^QOiz}<=?@bne&j3MKVt|h|*o#q;UGH9Q6 zsHHLAl++8Bt@6ITTk69m$;yFWDQERGm%j1ZH?4*BhTiO z{6-wKabiE;jP7m9Z=P&U2!YEVHWdh7@tN>w6P>@r#iVL_8H!IelqeI!^rs3!oz!yy z?kwQHxUaMS5Vtstm@=2v2rSxUU3<8HtmG+I$80f>2TM@|k4C=UE*~}^s?11@o^Q70 z)u5J;#{vAY8aNcTblN8~HF$^KFaomNS{^Qk+>ic{!R<%T#?8_h(x#LPKB(NWY&`Z4 zi5Dki0q1Xto4NW?k!7M6qJ>H6DX^%UT(_xP#eX+vFsi@X6`yguAU88!aF%~=@ zT6Z3vE5r9#rLGT3q4U;VO3;-&-POcqYZDuz31WVT-foOWNIWp6^ZeX)M<31)8nu>f zv36m|GY+e811*WHt!~|60wLXha<;20*L`c38l{a(%i~;l)|PH%>|YZ?V2agF{siE5 zPaK=GEOofmAla-06dH|kA|Tepa7Nl3_&mWU#qiPDoQ*cstrXfwketpFtv^pC95z}} zsdIB0QBUGVBu}k5E8NKaRwcrf4M8Ui6h|)#_62jS$8K2ujV8>|fcZp!g8Qw#gTR31 z?r%Vwymjr_JkAjFo+Q**KR-XF#dR(c8MEGRGy!|RK^eYBp}Q!H+tW|f0j+^mG3YH8 zK@WiuqH!a1Z;l~?w6wo6)QD4x{CpG+X*8EhuBHZ_C<4qky#$zgI{ymt0qs~RVn>h;D{qBtS^0ZGh1zC( zup4emt0}%qILoPokAk%#z26l1wMi0p=*+Z>x@IuhQtM8B;#Smuy)$PCw;J^e%-yr| zbNHetE56~=M$}sVmm3qpp^mm(A9?d2a!*UXhDsdDqs#zCj^X6-=ElbP^z9~?kf1L`}=%WFA4J+CzHWeKgTI7<)dL8GuTVjQp(H1@Wi5{z$xeD zqRe&aN_YT0+t-?Z`5bR%n~n`_OyRlk+3A}wf9;GpBX=e`?EpDpjnxDk_f_@-sU zhohaIZ*01BwarqEW7JF)BQGf~HqXhp=N?z`xx*n!rH-l-8;grvSW!W0LmBmDgi`)&WO8iJg-bWJ7~nNs5{D(qY0K zCh6@d^f7VEM8Cv?80qwF&UjfF(w|1kvBUHbQS-cGR&5@62@jiSY<_f^7@w~$az^OO z64`Nvyts|Z?b}Z`obV&LQgdRrYToi_ib|_AhRft{fLtNdsFh0S*&^&osX1fsQgwEo zbCytlT}S!;x~wN#ku0H|;)2TTng7J|-QujY`|TRm!58nES+r|r1^HNIH{8CxSir%h zyd0%cPZm)rgC&g-#x}AOn;#NaDf$Y1k-!GiahFaST4cokldyN?px6)M{qvo9H4x#- zdr6~MaT?CS&rnwgY;?FrRi#*AxXT9GfYkIkDr^Ab>{Gf%Yy zjLh3oeuYkRIGm>3s=U!m?=RUGj~10A6%Z<+o(Swcy>eds)}f~Q1d}qo?FLGwQfLRc zD$y18!VlezVfMDvDqe!Y_UcY8oQ1CET5Xk zl5rbqW#VZozk9PAD~XMpXq7+KdDV@5XY|keYFYbg;Z2;m`mC&6A#^i5G2-Qe0D(dJ zuI;@Q{@FK|f$kzRb#xOy=pKt}`W}9N*s5tR`K>Yvs(a7D6Hhs5O4ONg4=%3B{eG(v z;|<%r)NvDUK<_O{HYC@u^LTcD(qoN1SROB0ls8Qy`}Gkl$b7Ozz<*A>Ck@2K;&5`7 zF)baDO_d|DMv{X{yZ!UM7f&BO{hkIt6iQ~|0B!BXJ>DyZ!|1c)mzGY{{UjKFcK-U{ zTyzE3&N8?n*yv&2+*DH8yG>cJJj()PraVPi+-q+W_gX{!v8|18?d17yQWb}UrabS- zKOpvgniDTV7};GG1F6+&Rwaqwe4m6yAT;r@tdWH+8a#_X-=Ii=AC?rRtFnZyv{stT z9O}c`(}!1js=$TUo3Gso55)j~6}@~u^B2DhSQ#q);M2YAbHSztC4h55g4Jskyhq&j z8%w=Xl4g)x{v-)v^}=TcvKzT!EVW_ojrLMMNu6!7EB>`0D`VOQSVgf5;hH4P7ArzZ zFGUTmN%Ow2R(&a8b0Fn&0U8AQKLUHDQ_2B;K~Wb@WoIjmx_uo6!`RY)Qey=ife-x4 zjj2?ra25^LVZUP+?C&=Ju(UHG)W8k9bQ!pQRnoFmm)_DXO&tGi_3T0=iiy0ja~e>t z+U!?a9rJ-vRTWkXQzoj?*itQ)-BDox?CDhH{RE=nr(tIwSA+k!W?`F*PHB;9vT z&3L$WD$Np6JJa`Znv?E-Tbn%}(igj&I;ZkZp3@?Ih10PBsI%qjGR%Q# z-0$Dfo0p--dXk|9o0qqEE(V6k1)o32_`655DqjDrQ*5lm-sO61~nzMO|UbMC5Utbf25W7LdBh)ACZdG^nLpOYCjOH)je z6Gt=@5Q{zVq~tB<8=h2kktq(qvZqmdH;^=%X52!grr(7ok<}?b2X1zzGWhBREze3< z?KG%bYJW?#&2?0NB+Lrnk`=4GZ}O7n1`8=;t>zc(RqQh|QqW}gs8#*$^nE)Y?~2F1 z*kkMqcQU(N{DHwQ_8WZbQwKlaWAJmwHxcWT$3EY0?9FIvsehAmK)GhlbSY9?L9#}9 z7-68vLO`r61zc+&o69jujH_hC{LGQOWz`$8zj+3_B~;{7q8V)E!)+Tr^L8ejz(@<9f>jKO1gH|FPYR=E9!&zHa!3%l&SJEe^K5!x zcAnF~G!2U|0GZ)W(CQZiJOz6-dSxQFVLNr)kFLo-m7-{+xKl#_r7wqnRVcJvVRX7#Vh=X>w z_o>wr0x^Lk)&M4vTt{Up{+stFYprI7c58jJg0~GQr-pG5D;`@YP1=`k{eyiNO2r+nv<` zX&y-3AEh-Dbwo}9#wdM^dN#V1zH?)9QokJU9m)2`%u?umH+%0+%0vwR-HK8}{LFgE zZ~tL>Nu2~fVm*yvA6lqqV5!5M*4AWy5E9@hF4z)WE*6fYiOzpPVNt3qhTPq+v<9PH zG<@J47s%96LhX%5s-%Ij|BDKh=vOS8GgA&#S^09}<4RhpG@jAM zDKSwisI`}%LPev9U&@Xn(LiP-iKiG#=uNz$u^1GvuyBidB|8q|X!l-!)Ogs5&8P7Bn8$pr=v$*+|98Qyys~ygj<*Q$79C~I za&k&sa4B%D?U#ab(BUY1HKl?<)8sm1<&7)MO40VfPuF z=1#3eW3gT121cRMTcRRMtRd!ja1ug{r0MQo!zf~yp1fbwULiDpFps;eX41R@bY{4S z*;%scPKx;0QGm_f0WJmz4lVi1*{Pza7nN#{iG;u*5eUQMN+ybq%afRaBsZTJcVfht zJgOFCk|+?p;%{P4+f5z`&lD^BWojZYDsov3#9>F3TbdFReAe}Z%8mmTNM-*WXu zs_+z)LvgVwU1yAs8?H_8!t+EO#Nlja^|4CX>;Fg2(@$C}26Lh9#BR%g6a z&W7=EVQa7Q`|j9J-g&fCclbzAfwp;GfTL@8r^P-RQ5vR3)=yo5s=!fQr7t;Lib{TT z{cdP}^`?GuGfaD}=d@_Jt*aKlX&?bh+^Q8ND^9g<6Irk5XGfdFV|9Wxj6$~@tg}S! zSIj&UyK4r2d;Km*eA778mXxa*eYVueZ4E@zi9imJ3PinanFpZYRc;ul;7?vqs5~*_ zLnnkG$Lt8hE-|9^Ox>BpSTr-xC#s4PUVv}=+vidDCR@@7JP299&5~vSK{$Ue#%r7S{+#bJW z;2}4~C862UJ7!l8{X1t;pVNP9zm%9;eg1MtY>xL9mxA2Gc}tP*Tz4R6PbafKk&9XI zhh5D6oZe+m{-lm&kN-J7Wm^0T7&7+qd`$uYV|j#2;OOODYm zIYz&Ki7hVv!9yf_qV> z|LwFRM3wDfu*+s>dUKLYL8R3dgl8#VBIsCu$J5z-Lc>OifzV8>N5b9(^6JsFa$eS2 zOvZZs9Csk+<(O7tWx?GoRu;lrRGPGRocH zGe!rD^GHuSTQgF~(DhAh4ROzFKVKm^PvE+fe1{u;gy9@M0!*?xL(? z+MuVvx+!aq$_s!%UR-4GBHop^>YS4es^2V8IQYN({eS@S_k+W)4r(FcSRx}Dl&Xcv zu`)TYVkII(j1h{;EHCy6=y~e1^0j-iR02x|1u~5h;UoN1|L-x}%fIeX}GEEFsa!nI7lS@~6p^HtrN8Eu3mQ zjA6x8=`s8Yl7!t6w<_qmg0gjJRSvD&)({tW{F`zDboMn(WtcR{5}PZEQOSmX;c?x% z#6baSY8(PXXjr_JU84IYZx1weCswkK9Z|^{ARDE=u)|84)F(}=ti1c?<>L13otxt> z9k1?nlx#X$#V8-fT~($Kd!tNCn9ebYW{WaRCI|F222>74*#V75#*pmgqV^SpC3{Q@ zHZ-b>DqQn(an0Ab=12O@JmQmo8h#iX3GP_gX~f2BE;e`oR7)meWgb3k(Mp)*6uc~=+ zfzmAPvO_{{%)^-6juUe`Ui=DCsX0jxd3lm=87*x~56s5ykz!W3axau5!aj*)9dQ>V zWhQ=ChFfN*&p;Nlmv&D2E=h+RSx*|Mx zYo%YjOS3h+aOEsR_yQAWw{|6Ug_4o{(rS+Qoe2a~H0xioTXBgflfQ)dsAdGtro(nl z7v*~9PNN`Pws=(x*qSfoK=&6T>jsYX@ulxebpZY_Z-C9romS>f+jR5THwe^}gd^06 zNLT^R88kHEnG=0~SLB*wMBhS$CX%n*e)5~oM5ek)7ouG@O*eOgyG5JZO>XR55Ss8Z z`y0C2N0EKElJ1E~=;-#h$1dZG1l_-V`_}$MVP}|fyo6grmBU(E(k+|bS~tSj$=byO(~C z2=%a*kmn25T=4{-f5ErLwQCci;llPA+)wfkv18XYto4bohXd!#Lq4OzUyT0&`FT;;T;o z^FaCNoLQ#Q)Crb<32CJ-X+fRkMv9pSHjixVED6Hw#c{>?PLtxK+1}jq-Ugh*F3U8{ zmV2xWN}B`zfdSI!Rt&`dJP2V+(bm{!=(~1U;qHom#CJv*vnykNl~6$2UkG3OpFRD; zIg`9H52wZ? zsA}(jqe;c+QKynfI=mWPz24H5FIdHY{1OG>GHq|nH)e;kVLkG)Na%x-voAvy zh)rUp>NlKq!!(i+qeFt<;7Y?wSbNumP5ljEN|<- zLXy~bk$2&+^yn`nsd8F6elPS^rNsst9fyo6XP4@rB1${>NJ$Fg;#v`re(}tkY--Yf z#Y=A$K|UPiv~R!_H7n{UyHu&r^lyxcS&RiS@1+4~mYLGK%c{gaKj+40v=xYj4W=Aa zbQld4g+lP|C>+i&l!>o$LziM!d*F9;&?h+l+Q0J_V>x3Kg2(C6pVYV zjjpj1qB|z@lM8!#!L`Cys;VMF7bHzHU;f4(gLEpb6Ha##euP zG22qBAg*|Ln*5rbQ$~5U|ICknwF^t~Tji6o^K129=6k*LIU02}X9Xvw@<~k7izBF} zu?TKEY_Cmr!$|e}dJ&jMz2IkVC*E1$`l-2y;gYvbtmnou6zr)W@aOQI*w7@BiXY~VKhRuX!g2r`2bcg)7ivYs^hUgTVx8r=nyQt zS-$q(0`UC00BZmDpS?}J8|J-S*U$`Ar0wP+U6@r4+Urzl38v>#!tCd-D&+-9S{LON zdxrh%p^2?=baNNzHf z=BU7?!Qd+n_e7F^=!Lc23W016-U_F|gja)ubg~(hZ<4(M}6}f=ejp`(Ttx@=nsilsmP;It+2P9L2Wf zj(90R*g58Skz~BW`)#eTAg^pGt6&_=!eu7Xee1N(C&`RDd&DxIWrRF6k+{I?CJ5cd zf#fGfqYusvf3^Opsn$<@gZ&KlF|-qf6iK{9&sTYhl&e31BIW90d-|T^{dnkW7~~%X z&pDHH9JQsi80#6FwcO#^g%NReby1f8sh}$)4nfS7dYQwla9@M}jkTIzB2CJC#<``} zt{*V7tMgZLT-MTA7vv_3M!~f@nFUvOZp_p#(U|TVe`5ljKsswA`Q>hi+Ag2dwm=-t zYHg#=7_2@|-K%3a8GWTd{lm1JEq_h|AKNSlb~&FAHeT~{mYQyCWe_QTSzb_Yb5-9L zE?cCwe3N-izMch~FmCDvdG!weMq6VRROk8?3n|zLL}=iJ%lomQyYyRnW}LRv{6-m? zbT0Kbe^P<)YBryfR8Uo}t|T7#o6`Agjv)C&owXXR7X9x({>%RkQ;6iL<&QA{$$#qv zrT_RZ{|nbWh8HWXzXRO^Igus!F4~`v!q53RjY94p|&pPlM)d>XFO%6 zTWk_8raN`~NonHa?5Exw_(5<)OXNpdaO8W`zKfNmrvXD#d5I zCU9mozv!*~M^Gf@!vy~cNub7x%S$Er0i`~){@Z{3pZ}-QOX8rFca`!90$L}Rmos$< z{sot3Q8}tx@R0+a-9g@bxVr+f5Y27uPqMLbSI^AT5Y-+)GTPI3R9xby$dgs z2Avi*IKY$Y1;iBOe!rM|K~N*chhCnC!~!I{=4R3kr3{OL6xuk@VkbQOD)5MBDC9T7 z$6?e6|0;CaHL$s$SWvReWmFvqrF^obI6o2H_No+=H}C?56*7$>A+XMfC6vVZe!miGI_GZo+f5^SYuU`Jc2yyssG@r4mgwwv6@aOwkZ`PgDaMqsB z&)hwM9<})gM||WgT;ItIdCa$o0ekBzq=!~#7v1BJ zPU$4sa}x5wADzNucNr8-V2)>d4SQd>qrpEo;2+)1mFG{ggMKRyb`6-Le{=U7?_1s1 z9~?6@Y?<*gPf;RHh__=20{iYgNknL0!U91EjTR4n>RZ2`+TagKGR*}-AkCx%nj7m3Bss0SZx=0RLA>3NRRQeP+oDN$ODCx{+T0I zlwa8i5-kwv_XRG~NLI8g|cHtR@<^f(kWpeR0$iisNhpRC>Lf(>g&pf4Ey%i1k~$MFvFw zosMVzcqegG!{Q-CGt7!uw;Fp-l$D$uZxqi}$3pKn(@5*L$3*e!elwME?V9M0HLRin zl%SbXUjgmJ3>I;e`UKk}muXtRxO>JbBgyV%Wj&FeZZ_@j-m!Du0XJetFmNU+rZ6eq z|0R&HGgbL)r(o#Le^;l}3eiT_%ou(039FG+%;B7m6rik`oX_Qj9BzO2j^hq?uZd(8 z+qon%+;TAYt}1_cQPkk_)v{Fq&POXDe6j5=IGM)Y&Dm_<9`X zzbnaaQWL&=4Ww=&r=i}u3_LV*RKJ@V#0uAxHnx;i=q^1Hf3b*0_&8>rF_#8RYj&%1 zhafRcx3&+gM8~`bx%94f%Hh$pa!TT}k z;aoil! zJ%#js?z$6>z5T>e;CU10u0H276W>50@fb>>qIn;|9Lq)`P9AX?PCZdnBcSkdISV(k z?_I)x^Vt}gl~Mq@FFo+~SngKy=>csAg=#bg#z~qz*+Lp60Bsc z^POHm;ag-e;iR5}C_V)|>dIjg9wYYWA zjb!fJfYZZpy#M9J&F8dzn}%*@wW?nE^e^*PiBdmlGLiZam|(<1goTxQ@^tej`ql`{GjWjV;vzlcx!{>3nkByjB4^Sk(S ze=)i1uM_TMgi>^nl<&_gwz~Z35*0zbAgalu-SYV6v!w(A+^XBC;d0@K|B)@Z4ZmgQ zk0V}{;rq4C&fO delta 15 Wcmdm?w?mIjzMF$X!($_xkvIS)R|EY3 diff --git a/public/app/settings.css.gz b/public/app/settings.css.gz index 6965760dffcd0dcdf03c1d2cece07d629ffadc96..bd32d6d014771e4342ac079320beee32d7437a34 100644 GIT binary patch delta 15 WcmaE=|5Tq%zMF$X?a)TH`{DpD4F!Gx delta 15 WcmaE=|5Tq%zMF$X-eV)%eQ^LQfdu^k diff --git a/public/app/settings.css.map.gz b/public/app/settings.css.map.gz index 917325def3b5ec3cc4c7b42c06f1d37ebaf0555e..f0e44324019b39e9ec8b7f6790dc1154f51cf577 100644 GIT binary patch delta 15 WcmX>ka7chnzMF$X?a)Rx8x8;^z63}B delta 15 WcmX>ka7chnzMF$X-eV)14F>=tG6Tl| diff --git a/public/app/settings.js.gz b/public/app/settings.js.gz index f0466dbac116f41a5769735f227d2fc33376b560..ded9dbff2dbb6145d143e4a5542ab8d2476ce782 100644 GIT binary patch delta 15 WcmbOiF)xBmzMF%?;Lt`k2^|0_HUydg delta 15 WcmbOiF)xBmzMF$X!($_xgbn~Eqy!iM diff --git a/public/app/splash.css.gz b/public/app/splash.css.gz index 0d48b91c64de9db4d20287acfe276ddf4e453690..c8efcc4ec7e4473392642f74bc58fac16b2628c8 100644 GIT binary patch delta 15 WcmZqRZs2B<@8;l8JG7CliWLAJeFOCX delta 15 WcmZqRZs2B<@8;l;_t?l*#R>o$@dI=K diff --git a/public/app/splash.css.map.gz b/public/app/splash.css.map.gz index c22b3b5ce954274ff50a2c7f8ccb91f20bdf2f3f..d8d40b88e4e1a6e0e1eebc9b51e8ca2b86cab9dc 100644 GIT binary patch delta 15 WcmZ3-vW|sKzMF$X?a)Rx4JH60CQ delta 15 WcmZ3-vW|sKzMF$X-eV)11`_}uoC9qD diff --git a/public/app/splash.js.gz b/public/app/splash.js.gz index 48c5c390b009464cd2dc5231adf9d0951fb8e796..d35575d334532b591eade28696aeb048a0d71038 100644 GIT binary patch delta 15 Wcmeya{#~6-zMF%?;Lt|4kHP>ikp-#% delta 15 Wcmeya{#~6-zMF$X!($`cM_~Xg{{<)j diff --git a/tools/linux-x64/sqlite3 b/tools/linux-x64/sqlite3 index e5a68c39ad168ea34bf4195e78b9429f65547f87..43141e41204c80f6e48218d02c393a2bac5fcd68 100755 GIT binary patch delta 339090 zcmZ@>34Bb~_n&*8kc7xYmdS<*gCs~MAta4uLd1lK#Manj-!({xQVB^gB7}!yt*Ew? z(x5eHODsujt9u9*SOqm%OzaX&GR3)Fg1w7;cysC~MRPvl$u2<|`LRxN75)mc z4c9AhbtdmnxB|}%;`JC5c*-WuOQQlWnl0nvjF-R7p-vsSY`KD} z>dAX3De!{+Tns7|xLyqDrim@<&P%DHtB+S5&&Or2z>{M*u2$fBaalKwSISY|mR3Qn z6b~ac)18;qE2vuWDN>Uk^HCfAL-p&f@lti+{Y+3$%fv*aCOqP0lmA1V+g&rP_OOJ%VV$Y;hYVMHcZ2Ci$~O$M_(x@X1`&9Pd(nT2jQs zc#U6ym3m1*y=2A9#VPR`7fC@ih`Zu(5@?Mrh3bU zDV!-|6?lrczh|&l!gMRk6x2$QBm{@3>^OC`f~t1qc!2^h6Ne>i@yhq%>)yU=^`7WO zzeEi+_=q1R4j~15)+A=Q(#k5)dsGlDkJ{61R8#68SqEt^4jZEp^T+smC8h9TYZIzh zmcQrhn3seePuX*F+)m$|C0#{AsBUbgU&iBGYycK%|o-l>yS1a*@ za(;2lWEZdem3&sT$~@w-$r@Vuxie{^Vs-DYB6^e;i$36wMa51MAiF2oDqK+%5>Q8u`k^;|v!#Po@z)_=2)npiU zSoznt`Y2RZBf(yQ=MUnwsg=0ZNbpqP$vwEL)hcjROLxYB&MJQeL4T7spjYD7ioz9m z`2{g>T2MyjIW9K|3bLUmuP#Z6pXK?J6}b8==f_wDp3;cRM2Z40oG0fOFHUpuDp<|y z%v9u2i6pgaY`JxFDNs-iCSIyYfooH^rFUF`SBlG0HKE#CTox`VsM_CZ%92&Cz*WDA zS5kw#3eR!!D+M`U^h?ut>0LOpJo{A_hH^16O*34(iL*wppr%-bHe7*gt#*k)foGar z>S*3HO&Q4J~>nZp#XaRn_I0$`qN@R{W9zFZ_Y`sa$~V% zcw5@!>YObQ=OR_F;#9qYnlJ9k*3g8};>qkFuM~SOObLoiMWRcNW|+Z=vo={lO|ar) z6}ZYO(J2bt;K1uiSKyhVDW@yVbP~_y1a&in@=RM5nJU9LUZ}uTtvS9=fotu=Zu5h@ zlIw7-Ri+@9iOc3|h+h0=epj!AK76sLhE->vL3CI!)GL2EZ@~XQ)VT{Z-PGNjNkPqQ%ehpkzzZt)WV}+~W!=PQrXf_@L+rIE#!Fv|w;4XX`gE6xyB2A@ z)bDtkMg=uryoFTNk9@323Tme4lBXc3T{jVQ}IL z>ym<8?#4~fas{q>$0b-&;A$&gslW^C@NvIV;95JGmw_tPi0ac<)SC~)UV)VyM}q>_ zH{e_|Dsk~vKI(`--b#{!suf+9X}rq~yyqzjYI$$5)3PA8sV_rc^0v5WSrA56I4=qm zc@3+19a|N6C2+h@fhUV(Id0}{MepS?C_BTJ4|UM@vkIgbvP=`D8daT*DeL*%*(>lu ztJ$Mg;1~lGgS`!d`J(VwP*Y}!I#f6473;ig~hv zS}wY*K=C_o<)?ybXvxJgU4g5E!~rW}LRD7rTdg1`yy8l)K!GQ370<1R!9a=E%HUxM zOS$$bQ)DW$YNbmGJl|@~l`C+Ab&*R7JX!o^WmlTwC_Y;mG)!gnggi%ApQCbXPqhlX zAcwQrUx62`vI@Tf$Jp#DO{^h?Qw<8L{u0NH3Ow10Cn#`KI;%9KQ2cwjOJxM_=jO0_DtiUs~tec|(*Vp80V6_4-69d); zBVYRC-(=CWHrT7OfY(qsw)*hO#j|TMo^DmWMG7j$uht=-_IR!9NxU*QSgROUy$ZcJ zcRibgHS2?sr6<-8CFNqkh8ZF1$6TK!jIW+wyTCel1zsth-Jprp-sh#pDyZs8j;APa z?O|S9x&luTLq6A#A~E*!V6U>yRyHZ}6pG6}*TfcWwT??c)!*i8eV+m^@aK4u0xuVz zevVM$L8&B*fROh6PCu#+*6;Eso###7# z{Q)sV=g zt5Sj6c=$?z7l?^pXhO=L@}AgFtUjkU`B5wIvOR0QXiI2i%ARwZhX_>la!=@%Agfjb{{{{O&NEAT?mWgj~G*7);Q1+`L) z+NX&vw~le2l4^|s7AbJmY~F|C3OqsFgl%Px;G@2zpcaT{_i4QItZ3N4h;%=m zp_GWBnB

    !+Eltfh)x$JbAW12p6~Cfnb_>M(lMUh$ZuQvYRKjG086$>-{JvoiHiC zE>7ji7YzJKJjWCIQxHwLE{0-)tq$kOa!kO)K3!tt>RJi&^mC~ypH91MP6+g1hDR$HM0x7D^!foF>3P;jjJ zD(^$3f?Dtu$6qP%d@HUpRUb>HIP+h%g)6AG+6)TZR+~|QXNpe`b;SvdDC&y4=v@3; zB%Z*(`J&6=u4ta4i7WQd=wqRRh}t-4ljKwoO`w&e_8T77s}(W2516=nX1%qvLmqUE-pKTQ~8`zB?T3CM5IV)fPvMZeP+B3@)0Uv;WpOhjtYLQeHplr0nIA~k<5r-m!2c#3&igRAqz z>8|g`ny$!W8*8QlFBhYJ`7qXe1+_q&f>hgB3l!9Ranmn+tc3~+2Jx|+ZLCEKs$L|& zei&<+f?6hqAk{Y3as^c{4*Qjjb>^=h#;RRWotL(;`YUiWxUpv2yoM{N7`r<2VXQ_4 zHD63TgMxj=-X%#vK^2VUY-1g(pyJ#h)i$r`3Tl~n3#qoTE>uwUqDvVYYe3nDu^w0C zv5mD%f#U{H_F=5$3MyI^NVUytrGlC-lCylQs+H9_TPTK{{V-Owf{Js4RNGj!3M!rg zAk{Wjy@IM251-Y9W@d5;Pf$=3+_>$Oq`=i_qT{(BuX5{ITDpRalXea_gXw&!F8mL5 z?m11YDvdX}T0zyfv6 z+h#IJf#-|2&VQK6u?lL6=yKu1Or|TSwwcWQANa!mfv;BJ))`Y3C~)h91*-Nb2q`P9 z;SmL{63<>h9c5kluN2fGkz7RmX69wptEh0Wo_gCPm`yAJc zw=QbL)fe$r>1~b}6gdmU!`Qm5Z z<>VutjK`#Wgt(R`CmBe@*H`h*ff#TtnB^aEP0qiFCkHUmcM>1)#QVDZ){Q5h@?;xN zu3Qg7@5JFo*APQZu5FVFst;b<+-eysa0~|AV4lscf0fm5`v1#@EAUD&;ASw@wh;&1 zWOr#zH-qu-e*9Z0T9BaLEqa$ThdH*K#l&Xf-%RnFaxAe}yn=)R(cu;E~ta+ZcClD~8@-;~sV=m>9%m z_!qr{J2E4mA)!e0yBo}W`CfN%Zn}!|FwqYacVm(~OuT(}2vr>rJN>~rGUbn8n$T1H z;t$N&Q#{8LdQW}}y%&TH4!egjEUUYd{%v*spvQ8LnHS&O3-(HR&V_QHB2S9=6l+MS z6;$;7EnTUhk@(Sr7zaZm-mqFc`v7ki zKJaIRlMjY?6|Cbsy}Gb^Pcer3kcsY;hb;bXdKm0wu;wiIPtLQLvrr_D*cu3t{|=M? zE|dQrmj6C|gz_hejUJ=$3t}&x%;U*!Optb)C-t7lZ=Eo~oKyMR7d$z~6Ivl>3FXOf zo-F6d5uQBbNux?RXRpc_*1}qz+^%FR!sRLU=$_c=DYnyAoXV3gp2m=(J(j265nNnr z{=7(43-(O?t52gEeVy%8@YI7e0LgIIN;=gXMtG6lWIC9=$d|grczcyJ`&X6fAi=vThuHBcNk zI-{x7m{a7O{Rl5$$gN1@rkaa=h#Mh)ny>hhIYND%28-r>uWN*zz{+?C zlc_LJhczU^Y#o_MSJZ-5k zK}U0b0BK9eC^#NSexok!VMB9L+R(GMy(%|b_a$<}aE%MsjDvX3SAs1ov0MfB#vrYms!kBf; z{;0(VpGS`la&DN7ZK_ngjixuo+zfk3+*KP{d{cS@=LV2?@-6rcBn`=8h{6O61Bqh| zm4@bwj(A4oFE4CptAgppgYco2@<0B;A8X5+@)KS8 z(!6E}nQKp{HV5A^qyr6Y4ui&!(ez{>92-N1(D8ww8%ws(P4&#bj3xC5c?{*_$fA0~ zLj_ey7eXHX;oQ)m3aPRn`^S@}COm>i`=F^i&LxFD6!s97qb*q=hYN_H(_izvgs_;K!o>N#Ljw$Py=fJ^H zgQ5mU4T&0Rp-1dgqw{4^l`b@deN%}qSql3vvP0t8GW(?~LGm`1)P;~+Yf=zMey zYpC`!-4m7d51A8S%$;Tb%-JPcXD@vUS*fJ0=aD0|ka0KOH(Pp`wJu$SbEzbjECb&( zQlI<=AEl9owD%zxm_~eQ*dg=GG!jRgYc<6l=C$A2gw3}!&iwmyvdfNih555d5_tzV zXOk$8I*aU7v8H44LYa&!FWU4{N^*xbpOF{TFc*U6koq*r&D>)SaUt=O>kBH=1Ec93 z&bw{cmdkj{oXNr5EfmvIY5(q8s;pPFQlk+JdGS75ubn*G0Bg48yW!gm(vJKEmJG5} z6XuK4MpXgN{#~`|d-Kjr6l5|Iys}6e+OjPqW)WBF*%n4;p)NTJ2eQaKstSb;*~HJY z2kQySEOLuCYZ>S%sGJ)@hM|@_EY2p5$F*uS#zNa2ekUpP0b{~VE zDP+B}ch0GLS5+08+fEm9RoVleE+8Fg)_M4G0j~Br->q6m+)xn(GvT}UFS{&%Qr zBCQ*Il&w~oj-pPgW4gq+aMZbBG%8q66f!Bu0g_Fm396d;CK5&uXTi@V5Pc`gpGagCY*|M7 z(v(T?ZW;O6_i!a!Jk|wkI%+hPNOiNY8XVILxVRjbVHL~~$$IDA_H3b~vPrIx`c^=| z3i4&Ws#>h0KJW33PvGVXa-`wa$F*?9lwfC4M=*K!nO#*Cl{dQviN%*+|AC^FB+%h@ zO)QMM#_p`B5eLL6%C|S+!K-blz zdGAF#>~Me;Qm-0Vk1W#G1!qyuk+n|*BbXk7SE= zrt=f(GD!>1dNtBHr$6rS(WZOSlwtDH3CCxnsk6W20_`@E&Ga)1+}cPQ#jZ(ae7|jE zY<+1o9gZ~>g%tHLJ(9E@xQCjGWj%R~Sqn@jNaK6f#f3jI^=J9DOUT`*pP3^p)td;3 zn{Z{nmYij74F3mpWA21-%R1!H`)QJ{PJpZeGJ;N*Kq?@OW0noA-a2pE$NfXo7a7;( zrbor|ri(r_&BAw*(*(I`hv)Zs(}N*p6A2{)VDl#21$)EEO(ckpybrH8k%Z8Buc@lE zvl`1`t+TYo(#}jzsHE{SE`K?|IEc7b#&3^<*KIYo1}Gj%6r3_`Bv zwU4iG#o?CV>hIvXYBOokv_Q`1hE~{;VJJE%>ME%P&-(_yp5u8RLa)te27C%fH~a>7Qu-CC{;!8!<9tNR7=w-FzgO+O+HwPb(9C?viv%U7cUz)e850|ySa9D(kIB#jR014jx;XV=m=#;{1^YNM%!j&Y}7Jb3OR z&1pb9blF8dqJu}m++D=Yq3uIvq1}{%;qzUjmD3x%WsT+HM!b>|`ofJ}q_fti22(Xh zWi3|=twFZGl@7%onr=p!j!9_T?=Z4`~{>dL5R{P1SiK zgO}}>8T=Jx)kQO>3|C{bx2&QH=@9JPL%d_%hU4&eBj(&NlPMQtUJch0mN-3-C@SIC z-0qFq$AnG#8ZdV@=FWe=qvwSYY(_c_F5lx|^@pIt_ryCR8x_1o_pfT%;yYABHW&Pd zS5;YR$~4watlSRTv&_Dhwy(m1mVa0uFLgn`p)F2h)=9MV!!q_U;i`}VSkH@Na6i9(;t_b1YI%;mpPF|Z2QqIuM_He-)< zIo*&3^~VZOPNK`H$}))wC{s~!xg&L2DPblnn5xs`EdN-@7;pqv(ju(x;dfTgD6I88 zSDD>z{o&+KMCULW>u2>{Fu(kXI8eIyH#0p%Jc$4I*O)-QE2)8X%0>>Z0ZT@z9op<% zBoIX8Ef|V$3wsUIig2m@09#p-3D=9zmO|^K2p9awvk-WgWYZ@tq3|$qr_c>b52GoV zu;1L^2$@B2_-l`n?o{&1uh&zueB?@IEGGN0DM`D;Gb}%nB?P{ zo=`&eH}fBd29fDyNKu@ridml$oTsW>e0b=ZALVRL)zxH%8m`Gw6528tcY%k$$o8>J zYszS!t`t-c_t}iIDCAx^gGJa@io4K^l~7trf@#c3cvXrTrrua+cO1Pg*F7-sI5CkV z_~SSl=UFG9_6Z`AAlP_ z2Ypcrt51>$hgqYTaq&{Z(VavkbPdQU;^Dj!KcHcK!+EHXj9a1UDH1_GgXB}_TBl6_ zhtp&zt(^l$@N!AnqR^ED>*<; znWvs1iwJY?%ScaB2|dn|ujr@Wz+Y#{Xy>UXaq9Ehhpm?t#qTig9L{hEtUpJFqKy7? zjwE?pYQ@Bmn_SItuZhMU>JFL5|3+pLIzJGk-;qlTem2)Sk0Fod1JHZqLUc3Ebm3pR z^srT$$0aafE0s14gbf!+(}pt#azEAATIz$Zitb3AkKy(Ol$%dr$VHr^R)fv6E|MLT z{uKy;S5WQGgg#e@zOJ#c?D(ZUVys^W%MqgkK7nIbaHTDPnpa6X>ev^euaaqwb_r}N zzA0UIg~L~gSL;p1Ju?IQAs@9)R7q(Sg4K6}L%O+Qt{c?~vy0ENnNLdn^f~ z+#e&TeF|w-a;T|S@=*&t(FT%zm1w zTp>+^0T$B8A;J1;gd7X$N1nnp3rTL8znf=T$kLpvX?I3DSD@axAH{+~2KjH2G{HRl z0r`T`@Dot;G3kU6l-S3_pA3YlkI6h@gy)aRDDn&jJ|QzuXa4qtETqF0n+I2rayz=Q zJ#>7It8yBgd`<>=c@))Bac_PgGmAcRRSga)LSDUtjxUf`XUvmdkPwp5-UH_}FRV>E z)Ayy)&SQdXd{4ziDF;@W`{>2bNdk4JUIz-P$Z(BCN%PVw~}U zGi^h)?od}v+Ykx5sA)?w9;T^jQ`*@Z)~RU|>gx?hF!gxug$&63IUFYoJrj1KgG?`n zw`%H(fk1B;+LWw^D3+wbSWIZV7v#Ip)?}Z#*o6)zbq45aq3%J!sgk~fAXgfs*1kug zvPuZLniE}VXWCK&yIiq*Q7-V1Njvgw3p63*GR@J;&ZGTe5j?Z_Nx=s|;M&j--cgZ6fR zeTmCxRBp?(E2Rkp}_)QHGo(R_0^8ap(;b>+uCV6aQFIG2>Ph( zj*n|#&e70vN*DN;$9U7_gl3I_H$HR@xnus+mnPOAyWq4IS^b;&wU*W;bYy>UY(!_1 z7+BDV?rKy+WK&*>vo7s_@~#S}I_*#ya$K6#gc zQ}Qs8LjvUVC-41wC*Q?&_%4A?dy&R(w+`0;eW4 zhMu?yeVfo`Aqg{3_)DX8{y5tzOE9u|biQ=z9?#o~5v>kKRgP>&DOzv_ah} z{7jy4mvLpYBfM!!*O9LQno)ncVHg}{X;yD|*o^AvBxi8(r(e)-lHmt`8bbG$faFj8 zNESE-&}I=n0t#ZpfLbEZR7`IvUF^gu9nIctitfIoLgG8nK|>=Tg-v^q?!aX zO-KJg4o(=P3+Mk`70a?8XRJ!Pf%d&6UXFZ$C6GEb+q>vPMUn+SIJN{JH8!_{bj^`5 zxdW4wxiz7FbK11N*DXFgqvVWF%y6DDg$HnTSUrH9A3 z82Yp3ZZnEp|6dnjd}|tv%6e^U+Mu2rR)}FcY$W&+K-xreW^Ukdk~KNO_JzExwqMMneN5WW$l*N`Uh5t zG`y2}Py`)HD2alfKcb%GK3u?P4Os)NBWV-l(|}0a+e%5vVOu1skVH5gNduU} z8c9Em9F&YhMxpJ)(%e~Usk;o^lsaP?Z7OHB0*j-vBWnyQqPZMsEztxDMvN z?Wq%K>5V^$fP%(4szXf>XR=ts0VT{dxQ4$R!9uEO4VaSd082a2CiTK!qEP3xU(nme zaX|D(7iM5*_wVUSCsaNEM2JBpPIN<376Lq zF8K2I09zrriq62VovAKrd^)#Z8{z7b3-^#i8{&4}-(@n!!X2Jc$K#IjX_|93vpN|; zFEu|7t)l5Ok1ZcF9%K0EiF{abI2dJAm;#Yqs1N$aA9tZm+zSplshG*h7D54zm+`V4 zEbBsBQTvafqzjrxgQo+DK{KaK3HZm*Fj`d%Lu1fX`V!W}&_->B9kkVu8q0W3`tce6 zyDzSeySO^Kgq*WDpy0}Vfi!s-Uqh^Bs_pu(du|ryDDp|S^EK%4A_ znejBd(Zd2hlRHDs;p)JZ*+}K4l8OsBm+Yn7pW(N78Xx2{h6%mA6QFne#F!VSvq#~V zC7;j}>wE=Fe*R1XF7I9T*en9n=vm5@|9iguF!BIM}y4TgGT&WF5l@(Y=9keIKqD zT)&Og<%Jm=v+x@3RB$s9ms`Y0ua4^d5c%SZ^id@A z`Is(g{UDn6^fpVGp1X_>wz_}8XRBPJiacb^if&O7ZRD`R`iimbBK@RbJl)!-mm8I_F3>idp_rP5z*l-hLz_Nzz~J0hb6KWe=k*Y2D4B z9!?w3Cjk24G`LP4{%Qh}nRSNY=LFn6Fv|$q zv|(ffn~xT{oU6{+v#=l5Q!BSb*-XlV!V$CwDxh~GXd+wnBk2X|kqG{yXs|=^MkiS} zpkX|UPH8v+gN{*|b5MRvN7JUo=FY)*e~Hv26%`@&8MWppy45fHb0=ovV5Hq@ETEP! zoRKG)^*iSj>>o|X(T^H|ZVc7d+4}2y5;i`DnrWI3IE0!fUI*0moh5Db+H}uQe;GIIp)9~6bKZQ=mK;PRG8dCf7=1er0 zcd`N^rqG^Fck@0}5e_S-px=D}j!vP0bvv$P=Tdmj0FTIU^50CMeKTeUqSCCA(lBBD zPGDicP8hae{LDw^?O_+Iy2)$5sk1B)2Rhfn60DL0oaQL*afI<|f><>W0t3>qxNZh~nogV5{!wHq4(~fG z7vbAEIozp62(4Qe z{B;l16NR2OYr6n8%%nc`?#`F-toQgd^U0Ysl#()dJBxOpAyww~v*}laesmV@enwMh zxSP4(9D2=;tc6zDNcambXVVcRAKK^8FC8Cxu)SrDLAq^zm_w5Y4fqSXETHG{?vl?! zjP!ZBnfETF*_1Y#3+-}g6UPZIOjIy#J{%_GV(6xOFzm_22-h!AnTzHKu7Snq9iM`! zi>WTWoX5`D4Vkjtmf5ci^5_*853dmbV8<0)rZAPaEfyHt)KvAwX7`q3ZUq3Uz$0nP<9o;Cy+T7bJ023(gEU_Z-XM*%%XYp;T7n{ckDm``uQ z;4L|5cK(tUQTmG!&VG$yt<6Sw^EJ9G9exM>7F-dve}@rU(2>6aA|`a(Z*Xi2I%s`I znN3^iTvGSQGa^ego=!iJ(!g^Y)zwSxCyQw?{(d=k$txg!n;i4a*+!$N#|SvSjrJ!K zpwV{P*!SbUHB{Y9(a)LVoc2Sftaf|sQg?ENJ`sj(r|~FWh1+SXX8Zfd)h6AmXRX$V zp&(?lB}o+2aagFgM$|2i=YyS#+cHs82B+9JbNtX#;%^xzJ{iIvX`qDst!4i_&LpZPt zWAXRk{w~~MOU$))(;aqrY54~;qO;((na0r}S3tiHm+&{RVjuF-d>Jn8qn|gg)rWZXi zSDg#yBPFzm)b92>QOS4fq)f;=PW7b9eDFAJShHTmFV-UW*aH^9W5r)F+FoMToS|`~ z-ni3NdNO-JdJ?3SAq!5KzbK=}2(9@Ij6Fx=o6Nt%<`!@Hm}1nixs&yB+y?hf7BPE$ zg0SsYLc97Ly+N|f2Y$nur5$dqI*-mvy<5=YJc^(hs(z>Lu-Uc;j~UZMwvD zl@aYOb}cJ5_ke6okE#O^cW{T(8DZ@mI;zQr+FVuUJZNA&S(5@E(D%n`Y&Cd40Nq_& zuD4;}T{-acfi1ZkfY!_S|S+9t5b`n1H$o-l*18kc2cV`ytea34%A$>q2X(KzB{eTXmhibsh z2WSFqf`1;+X|!bxnDUU$a#D3;1zs{9bcun#AJP?csi%4ABWh1*+8|i-m`+x&Br-44 z3c1ZZA2d%;3J1ZIC$uN|2@XHODb0h*C)9wdJ*0yA*Aeko-f$OX^KuDBRnXxy&DVUQ zf@Tr7lnydUGU6{-@{RT&UeJC@n>x(zFY`p|U|#x^4kR?RJv@3w?_!;2|D>sPYdO|X z~yUA8|eKPy)}3&{=lnjg1p3)evrqMZ%Vx`Sw#b<9KU{%p4r!UF9Nb{7*ZPn z#(K=aMYthD*k^B6L@zmAf@RM!oVgA5Jg5EKJEt&ffPKAVDvcdc8kg7lFkTaD@B%G+ zJYso4N9c~UX6w3-PH#O-ekm0q!UF94WcQ_{ihu?$=|~zF0ogBUK={%N@B4|Y!j;61 zdaj&DkoT_vOL#~U-gy-JN+CkPa%^T8V2p&(sMsdz!P1|JG`|e7M@Z9yuTDAaLB=jymF@d=T zPl>RZ`Uk)&D)_quwc`7$ma*Ma`Xm_6P+7|ilR30k(ThmMf1d#_{~>E$!yZQ=5I3_Mj>1w+$HDKj=HR!7j&39mt{BQ&F(Uc*mygg~L6swP7kTdY z$7)ze@Y6|Xjm|>KzdqEG>7|@LfYAq5r?Xo^=xDBlaJ3MLEKXHpAI`u|wa|#Rdkg2( zLQC>?m5b1t9EUI$9MGEQFvRBa4{tb;?g;=W1fXS{xt9ldKFxN6o6Pq^!)yhq2 zU>n%uDs;hbiT-vKmg?LdVXsix=iEWX#>6>EB3EU7mwJuA?tTg1x(Qkg&i>*i_|q|| z@X}3a7&-rnRV%i)7Br%#Fy$d1qw)P1hrUN_W9;z|65WMw$QSU&U8wJsec4*iZ`ga* zVgmQvCqjsaV5GfU!z>R00}4;zv4`M8-R^*+Mi}qyf5}>m1-<@NOl^TB8X=mTgx@s6 zV7fjOLOoF`)fZujr{F>N{b~N%Q>aPYv{~Gg@nk8sYLq^I21Q;%cbfPNoVm!3X_N#24l#ozkO^%fdLPrK>B4$kCWNMAp7utq|0VN3S&tkp-G zQgsH&ghb0doKJqK9tX>747mx9y#>!E_q|bN+?k(a(6CIwRPtNq&5^H+!}sHWFJ*6 zx#JVl{7#?2;f6vx*9v#JM2Gh!f>xQ;TA@D4sJK&yodKn=fuu8myTPQj|F7~irZtvf zlpy0x=20+TF|A0(q&7TD>UI8l|AB*C4`%2jA6B@x{0_T^UtM4#eX|1Fmya@>vp++L zWAS0n9;V6=cNR{;oo^g=gW18@6Uk{79QG4hu)wIF(A3!<%f^~&T3AS3ihKZ#8woi? z2j4Uj_PD4_AmdANHg+Zgoqa;C(quo|iPOro-Meea30 z7TK^z;&H1Ht?xQWmU|a+F60FE5Y<=64je)BEx6KH7~}S485@c0H0Q7bF4R%!=Ds>X zB>t%*tW%cO!qz9L;DpS`)Wr8l{5?=N6&l9;>@4@O&O}=u|5=KFbu6r-b?!Of*HJbE z=OA(m(`44c9?cs|B+DO=)>LRgXWf9!O@%g^qsOhQkD@ul<|P@6#czSirh>aGT;@t3 z*=k`FOF7`#O!&-q!F3b?`HPftG&R^~qul=2Ea%=7K7;oip^xYI|2wGul_F<3bW=j!!TqQZdVypXCW%{X1m&ECyLZ1&JbL_RTnfS(pO z7XrMB%dsoixv^2Gb@o|bQly>bP}p41#l1=)_yO7^RmOd$l^)<*mz=7!hDN-=t^E*e zeAo+H$xT;FUZ|8=r1;-tWMFQ(z4Y!9Xj=$Pn!Gfj{jwJ$Kdiz}vBHPD<8mkBy+JvM z!$d;*>n4nEA#|gjDX_PN@UdG@)RS_p*v)7Y+iKe11izMohU#v@M=gafX@kp9-ctAo z{VSg!A%fZugnmIn0KGl{<^~CE=vM<^Kc@9sUcg1nn!rVsgu*iTI*?$Yq3h|IGP8U} z*qBv&0kjGh`V0?KF{bs=`Qun|dCK>3Wa*TAkbU~mH zJA*8)Z`i3pDPwcRMB8koT?0$7aD}c(G8gNGUWESO30|SXfW|Xl;ZBY{O^V7YCDOW5 z+$bXcabElds*z~ZJLZL#!m3cAi3fRWhg0%6O;+?6FR4ncEB*2loDCH`Ge+PY0aP8? z6HvmL7Gnn`hB(v}-8doV0aj~v(_qqyepl0iATy9XS2ovqj7rt+0l5o+#|{N zG836poslWt%QlR$15PM@x7M-Em{kY z)U89<@jn|1y9+h{joCj;*h}f0L?~}7M0hkdu&Z+X{ty0qK|}1RjSxQ4JMHD$R-DaelHQcy$II+=g1Mtl#1B3f^9^s94@C$K2&pjN_y{d!>hvju zv=ahrlODLMun&bL{C=t(TDP_LfY=Vz(8!K(pqwtne6mA%VQPgV|bcquBQ~cn%AWGQeo;%>b)#8sJbP`_D z;HA*Bvk*vyr7){AirH83VCgLEpf7sB>S*C1iG}Pg!f1lw_%3LBlbz7eC^R7p&0UPb zHv$;~72So&qymP-2}b~J(|rSmYhhoHwxu4{S-4VrzmOzwWjISjV1IKn^UJAsZ% z9>=-en&1sLdZ2&Q_7K#H7ecUXM7+?HZrBII;!(5Rg7xu2WAZZ;#S3kz-9Gp`Uhrf3 zt|$5#-$QIq%$sM1DLrwC4L8I3o+u5G^1BCI?kTuZwHcoD#3GMDoq+pC3A9Z>pYIE} znjnlvhcPBmXyLmJZ`E5a%Vs9VWckVJlWckG`wo^Q3iazx*&~}ll2><}zSTB^)N})P zu9#PFJP~El>lHjt6dKmIe^py$dGuNil;-wsjsBGB2I~B*lSF#_5<+?j!T6&W!+N2M zIPQB`*-OZx(QUxHx6mLa`x;k%p3;Eze7(3Zne)VD`S&(~#Z)o|A@{$^LWx-j?@)x; zQRS0;XpS_qeRZ008|L&zv$c31tm!Q@V`2T?!VubipV_Yunr=Ad@qL9x2v6xNc#_Vr zsIL&H@$4#3lx$(d>D&%9#^o#Z{tiy{6-H90WC-aec;SuW?)?M{HI_r0kCC5gko2+e zJ59I=K}onHZMkmlnuMMp`3L6q7oJheE=U_7G}0GmBg3>9?ncSNPcNBbuzk zJG)w*S??jKrHd<|bO7%5Q+C1Q0YY#m17^X3wrgbvU!dwk0Se&ozrQv0ut9PYAw_al zNtF#l1_~W$Q6YRj5WS&RSK!Bi=!v*rF<%}i%o6DF2heY*FpzfN0(*uE4`|QxurXO^ z>pmL)9X)P(1zFv-6n3AB!@(8*jUh75e(D+stf}V|dD3 zoAIF(eSm1w9acYnlQI@PNudWsjuYCjBfN1!F#Yih*gQ^XWh}|zlHHnZ-j8HXr2Zi{ zgB|{66?0}#d$P-y>sN3IPmq@LGO1^o^OwM^3spWe7%#+NkYv<&3^AD2!piX&jra%7 zj>niu-L;^efGXvWH4rgDFlr~9#G&Q2-{xrB6&~z(S7lj>tC-nhJx;==2|^p^F8Gfw zSXRphT9ssf67Ee9y7@j@Eqh@JrlXeOm_J{>i6nn0^=u==O+?3W{t5Hgi9+2Pq@Q_4 ziqL~LNbiiclj#T^pF3yA;b;Bal73ZBRwo0u+@31nq3Q*=I}L*lOP@e+s-TH1NpN7= zw!(zJHc=t179CVsZ$>%iG(@f%bHCN)vlIzu0HqRtq{BITDqAv$Oge0yn=05-I^vKy zce;>BsrqNQk&d=qN34YB9m-Z8=DiN;nK*-2av^%Au#P-7m(LVF5@@3cv+rj@E@59t z;%^(FPAr*&dxO6@EJGNFey}|hWC}j6w=(|irLdqVUW?4cwG{dW9%Tyc+*2oW5zn3_ z?{3VX^~;6!bA{=yGu_$gaBCeqaX=GPE%|#u$y{MWebXL!X4Y4@;P}|2+gsIIvUI}) znezlQZDN9mEDUVznF|xLFs!l*7H0`914hhct<`qUzJtqy8Dw~HfxJS`{)OQ)48ebn zFmp8?!tE@<-?JWOM@90%bWfxx;{RkqqikWc*Y_AoWHQKZ+%c!O#xfK=$&AS7gD!i2cieY0`jN3vK)LK2J^tn0yA%dT@- z%OZ_+BtqgA_kCXzakGv%=KWSr!v6m6`}%xjx{j`{dg`g?dFrX>d8%6>HN9U5a^6dg zbQ+Tn3AUO;Y3vfn140A(WeJ$w6v|kluUoEVdA=~S@>**6=@^*?|~*6tacCU0adQR%j<83)w^V;c5R-1u{^k0gMg24C@w2{>pVF}qSPKe) zHH!m_zXa>EZ9nU)!N26{&-ysA{Ag;rLcd6~JfRCKpda77fINPI26OsN3jal4p%EAv z#({3|g?iRUQ~qctx_=iUHgDMG`AD*KgG`%nFRVFYFTsXr+0IjW{? z(eD$*#xp2tn|_}7N2+>$n|_7JMWG$~=3;6V?cSk(iRf#acIspOE-Z2|dEl#q`d&TY zhv8x5H4c(zI)q$Aut|qN3G1bFko}ZQ+LI0mwN)m)PKV~FY$jDuAc{V105e=#1vFH))D#P|;1|3oX@`wx)cIi6_Z`Cfl^n)ew7l?0r^>ylP zs#`dR`!H`Dut~fxZ*2>sIK$K|k?sbj$^iHGjiu-e{ZX;jzvPw)De*P6%)|z-KMl#$ zhYGdSUo!zC*q&q`)GraY&Y<2|`Y@l$zhWhzF)+ra`}VHL&vN{cuRR$#hLR3JZW&*X>jvV>adPj!rzdaK z8miv|^yx(}4q*w`eMv5d_5B3si4J3LaU_eD9M&Ie5?;M<2K0sU;Dq3}-1{%qx<;ds zF#6U*0(yysegMbe+N@Z;ul=R1-dnUX8^ZSjI-afX09X9-Ir_4qTQD`r(YFv=B-6|s zeS+9GlfLBWeSK4_7Jey6tTMru-fAv@~|uNZ#jo3gL4(;5>LjhvPhV$;8o zkgtZk;RwWaf)68U!f}05OyjQO`ql6(?tVf)RCLOv>=XJ1kXgT+z+{-3Qt6ZEYqth; z_@ut0uuv_1O0O5iwwtJYu6~erI(DfTs$<92P}P9_8~vQCH`kiD%V7=Yrisfn%E2EI zCS%Fy9;eCq{k3&)K3x+$!06r2=zYWL;?@Ce$oz1kp>4aPQueAM>7=gNAs763+<}Z^ z@ykWXp%iyUe@ryor`l)ryM_CdcNWyE(mg73PG86COt3>fn7~1U+GCFDbkz5}-n*7< zCpV!rq^{7I|1FytB^+K`F@v^`9lj+nn|mA5Z|AV#U$vf2odc&%i=)@)^wWJG?Qpb_ zf@$Xqq{R_OpAh)!yuLrqbzYwbf8I;eF6g_6UVZ861${%qY+na=*FN;Q5>>be;-jli zy)QzwkP}2*E&(yObfi_6^gd!pZ`yN7-^|lL2($jXHtU7U`z9GKOE18sYP2W%~ zTb+dKIJ8}=re4<%5`;SH(;NB>ksmGIhK}MQy}J#bfrt-x^p|+J$h)B7n>(s!@9I~I zqRV$Q_JO{)-{$swTDPAC{2=XI`kf<$Bd+3t_Vna|zN+7l|EckQ>9-nf+f(g_`Vj~Y z_RB+Tce6=-2zoxUGQD`HA0)EMYPU!Fxe^@qZ29_%&K?|s0QVm9e4_8ocR5e=H3AQ; z0Ma?!2Kgjnk7Gz(%{v2>A8flLa;WnsDo;62^kb?7pgx!W{?O_at|dcxER^*#9Sdc! zO;?_JKShTQ(}bt`fC?EuYo7o{RQU_;hrnsQCax4tNwAsrp|&`q99@12-PT%xK0MWz zDLLzwLn7nrGR$VlGPJSTLdsF#GYD~CmQ&wn`bu8D9uCsN>%e9JBADVq^h{s2luhU0 z1iQ=#BI@9WIktsm>G(4o0Lmp*pXd4=f~ec9o_eA0AajG9clrZxfxP<;tQSmsZGk>T z_+1VBsE5r}ttnXjQEOg(ve$<%! zTu69-$tr#3ZtcN#LvNyGW9>@m;X=NhBUXbL&|!LCaJ(Rp`x{&XbL-Mn7&^d9`~LL&Pc>YkJm56`=o*rhLjwXo2>1e zqQef3yJ>AF7?W`8cEWkQ?sz(8ZKroUWmwyxi@Y@5+K!p5UFGBq#fa{^w=ksp`Qk|u zGVl5rGw->XgsYjiorK&dUTWOK0{{xSdz=&Tn^zOmq_6|Y8G<1i$9;$4gdeH4>3^ynUXfj^1=e?2t` zXN`Lxcky2GpS)R`23BY6Z0zKS_Y(ZHgXJ~!GH$VOx^uw>-Bt%xOwh5r2w6tqCQiTo z^2>8YEMi|iNyL|_QkUGfwJ6Z!U#(u9VzwuiJ4L9W~Ol+KGEP9q+%)CcivEb`gX)kM)B#2L%ag|UldcM7)bGBRrV8SxBXl-Ss)Ohn z`u@^9p%E?YFSQcC7*yO8ILS#kqxKvjO^^}v%PlXs>4;_2McQuZVeTx{4?!}N-g0xqBvVzVgNXEpYElcWl z^BYFEh3KW%=1p1uv0DOB-iUI|JSjt~g*xWsh)qgKoep&k>1>2tQWxJKCBv{d!;qd~ zVJA^PAv73IId}@r$YJB~%b}FRcw2mr43u!vpq0bgFE7kX$%t=ofZHY7y=S7yqzEtk z#Q<1!R6r4@#&+-F$V8qMd1)*Te}QL<(pYu$2T!xnHFx#i50YN+oN?N2$6>3Bd1?NJ zSf~fy+78i&@lwN};tWm1okNJbz?jC-y2M&BX$c54^T;ebv;Fn+CmcXd@#n`ivfcZI zM7<|SKEBPD^XyJwRF4xY|EGLE&6^-qMWhaOf|M@IQ%6pepvCE_uKrQ_Lx55(cCzFL zuZtm*rSITYzIU?JR(x4cb)6!$;IXbdO_eSqtWT{($t=LMa(t3hS-ib~Rwe<{%hQ)6 zsg$5l$!St8tcK`mXn8G7m?njAPl0LDKY|wxnJ(2Fd}|XFI|$Fj{W(u|2)>57!WpH6 z(2DHS6gLR+54hzY4#n6$)a1`@c%GKvradD-Ap5g0-yhEt{T%t#@Vv4xzYd;PFQU)W z(V@ZQoh*&uPRPj;cW>C1EO`qvC?{E}glOUU$x@ZX#`8aE(f11D-)ef@M{_^f-(B|2 z;1i#GoBbEX@`^9`f7Qn{o`3JH)5Uw(z4zkbg*n+Jz=1XMlOkI4BJ^ni&>skTd@NEq z>M#R(_G7D5Rht|!KszV)dyAETTML55`sZJR<3VsnUbi&NK~YdVxL?1RHsGbAcaSz)F6Mb_S>U@!?-#Mu^E_$xY^k2mmiEt< znpb+i6ns#P^2)z3a6TxP>jdaSY0^OPc_PhAlf1p>+n`g~g=ype z67y%^CGR=3I}I$tiK6F7vtSH-YK}C9i>_8_9k%0-tkNoo^|R(ml@ZK%%Upg8;Xzphc2JzOxL9jbPflND4%h>qm>E@tB-Gi=`(*dx~8mwHNIZ>DMLF5=5P= zPf};BS1U;s5$tR$fqkSvnJLxq?K%kT-;%-iDc@meW-Aosh;(U-q_RsPTNk4aOR?fF z(Tt^1ePI>tTPh_A{uHrH3KahxKtq;EX1`4X(1d1hnKuM{mq*R8;Fs%_=F`b#QiSi{ zKYHl0O#$U`A}F~f-}Zl(Ypie>$h({>Ete|bpeK4c*v~Awuw05PRyBc7XA)mRi9bu# z7(iXQ0>%C;H7s`df(MuU%Vu1mxj*B@eYEvwsV81^T_OF^i{19tZXy5yZf#DBC|L#c z)j>app#(cOyLV~FgE=`U5v2mcqgH3N@B|Wj3sur0?o@WXGRQl*$OR z>CsB5R$}dnC3RyH%#9;z;b9y?HAMvB0njs~?A3-TYt6IrJU1=EjsGMET}C$qvqhiA z3_Qb9R)-(Rm5tf83MF+G_5ptlD;(_jC7!kR)}cL4etYz?SI)TMn3qKFKKv;yVi&I! zXXDdW$L_trk@-8%tR584$L^R<3ok$$m{a((UxU_ylY;6&?Rk~2`B{beX>15@Avvh} z*Z%h98J4o`@x%M;#cJZo!dl{QQHPtURaZ%E_|*tMtd-V?cSn%lI;pz&Xc)Cv2gX>E z)~}Nq!sF)lI`AO_wOKE%_kH99DiL?qknZ9pe6Sqh@?7;?u!hrAVuN%7jt$o~fIN0u zvQZlD-|ZYwDPaVsJ|~ZR=ro@sPJ+fa;pFF!W9poZ(jdLx#;R!2>iSzCZy7X8nqU@= zm@P6^&nYte33gXet@o#-2u>F+fn{3RKx(!HTz?il-2#$Roe*PUAvpGtzocJq`ZsW^ z)K*xprf-#e1x~KFNu7i)RON3e)ML!AI07|xiLsn+9S1&B_GKS+#NX015yJ2D9bf~Z z+G8gg_Ptcn11C5ijF$JAHn*6ZgTOA3jfmS$R8E!Zx^D&y5a#q{bM&|J_}4=41JlA@CrVb@w3am7zD=L$7y9Rh^d?CP5u`ORD$uvAncf zr2ml7K7C=_#dp-T==pBxrt|4BS`j;-Ufd&96a|Ss?3FfSKq+b_j|guUJ` z)hRV3Qo`m;i1$t^5Yeq-P2o>v^@iK$0coiCeh95QfNcOw&NHOtWkL(QA;wK`&yMl~ zSL(s{cqu?z=)zH;%pZSbhZQ#Ao(6YNXtP@NF}T2#$jm)ERkAdOa2Wmc%qu+750Rg zCd;X$aG~7zUVQrsxu^7M9K6LzNwGqP{r3FbAg7LXfui!zvP;9^aa=q{$`YT&Qf`hE zEc`>_5$RW<4E=TltME_N?WojRgm%C8aVbXdrVYoX-{HX;dqNWRh%?ysv=l2;P*8lzaW~A> zFPp=dhyuf$^MF|nJBCsYJzEf8oM|lGQ9ItrDI6{2SL8gX< zX*_eOSTyT{XM>^%Pg5k(DO-Zcw5SX9GV>uN+GuK}=>vU|_t zZE^xl+2^H-UT@ZO4jZWpzLx(F|IJ}i~G#zpw2(j!7I{FiOz^n zj_t2mi00z-5N(BHQ6er3j!|s+^zpG;fZg@ zryxti->t~OEL7(|4zwA`A1$mDel%eA=4l5cYVeO2-Y~;iyd&3J%e`eA@gB(SAeF>!~0;Oido684<`SlCkh80Jpq z3&+B)A%V!QMOMQA#75o>SN(s2jGOlZFZ!m|pxkR9n}^k|*Co9O$IqTOC7+V>@AEe@ z;zfIIYlQiU$DtD63eCPL-R1|(x1>7aoqhDnE#SjM_53Xm9+0Clccddq-E`wHgnhI)zD^^Q!6%$r!Sz7fE!Ow z;ORbJ%UuWaG=%@ca@Vdrt$wR-Rx3Z2wh7o-T*{aJh5zlzC(=lvpBnyDIw=ZKYOxnm zd#+pP`BJJazVs#QODW22?{vpLYJ4CUV$!Fpw_i#)WqLXjAmwUMNJL3kYYt0eL`y#X zue7+-;4EJ1V6ed%Ns}t*5}I(XH|ee9?_!z!b@y0>*1wgO(dc)Q|B`o7B&~V}(tm~` z-%GE=yQL`P1NL_}Xz&MVm(v@_C@>&cMAZtU8Q{Nv6-ed8=bm)BK&lOx+Y6x1YOD7C zD9wkmxg5U$+CLcZ* zFbKDKG_xb3YrH#Dsyqm? z%m0oc>4VGo(~t!3ba2O-KVy#bqC~S$V88oSd=g#&Kna^c?l)=Zko-mXVWs6VS}-wP zc#t7wq@>e@*D|Ce^4~fM&Pg8_T>g+Sg=HC%`8tf|E{vg-bRPJ``)F%ByS0PxR%#+8 zwBqkwgN{1+_O0+}L+T4W8WWQ~h=!Dh{4wmRA>{@hEV+))CEIFj_-sghtd*U`jevNt zb`XubIXJoYK6w|uYss~obJWLo@J0Tq_$B$b3h`L$RxNZZ)*A8RA9r2;AcrzMsi127 z=%j**iG~zJ?S|ah(~!y=jt)cW`6nz z?KZEHj>;e%hLjXkP0kYMYaiT?Rcg6mvW^pCg{Ow}PH+wgFQto5Gg)5e-*j{!^{pW# z>We+m4(KLLW;(!jC?EV~059(g%xVOi)>OQ<;7!=nrn@C)0g@#pLrMu`a@vd8?4kwAO=B6$GnKpkk9bU(fdKUTCC;=TUgmEI~qN^cwKk~KD$-L*h4+9;2 z0B!pEVO-(01oi&=;TcGCI}GjJV@Lp3xtbqQz5$&g1h#c+%1;B3!yyGjSe><|j~?DP z#;`=2VR}_$7^i(fa1Nazr8E*;sq#`gD$ts-@%^J_Oqt5<^t6UdVTTRL-I227=g%pe zYs+O!vH`{qG?OMZAi8$;rj8eMX*Ut03Kr`d7k*Dwmg$Q;QG4F+9;Dar2u~Ay@kh* zG3ir6e9NQ{&cJ1-ggg@*^Kd;EHXqM9KwYZe#LW2d7i@`VF*VaB2ly>p=B$g)&_=G3hN{ha&fHi+$Q5wT4hXYsxxZmO-2v7;1Zp3G@%S=LqZj! zHPRk-Ile^Es(vfUQi7Z1TwYteJkXF>$X1NnULr53Xk?C6o>vxWAZuPFRL00TZl`$R zxd=#k6OjNy<5TgIVfAYb-TqNqs2#m^e5u3_!rK~h)^)t4ea3|D@sI@8>QfK2! zd3)eDko-k&NZE!5Gz z%faNkw~`8?4JkK~%L(B{{N}YT@CCt4Ici8TB8fI5@KcD*G~bs^cfX3m33Op>6|*G| zSDe`bsZwcHTfBNi?O2*cisI!&TH?nlgU#>tVE?G9HauP;_8CzqO5jwvI3h`veb`QE4Wb) zw&w8se{SZdcUec4ip}k z&JBguKT>n5GeHn{Jf>rTY`i`#bhWys2Kz}63~K!#<|>xIvK_HQEFevM69mn|*C2MV zs$=(~)bDF^&L5&$g4s*~o+R$|Sc-Q8i1GgyMEBG`>M=nt7}d@7nYYl^$|k*Y(Dbk!4Pk-haiK#-k3$eD(7Wmb`UWEc7(Gn!fZ7zf;|+gbePT|7c__ez(mm(N(sC7 z%5W`nJkQk9G%AwStlUq_#x0Ll_RxddxojE?LT0uk_vJqh(Y`fhM6yysWx5>6YKRsO zl^NM?z4*2PWtbRt>#8A|?G+$dpJ>je0U_G7U^NAZiY?essJS1uUc8z-ZNd9+c{kl20k^lt z8cesbO~6?0A$Zb{9hntt)u|I(B;G!t zuI$9-3Z(|eX{s%k$XUa*OKuPgZ@w*m7e#epCUNaQWa+{N3zO7WU4Z!zoTIxji+FPb z<#t0cR#nOFteH@gx^)Lpm`jP>*|2icjhxaxKg#{Lx8gbymjK%+Wbx!K+W>Ov!D1?u zL54A`eBwjy-%+Bl^o0?NJqGvA**-PrKU&nxB5tlPxx!` zNaa<=TvET2#mZ8-o~)&dX&wJiQ+|n~GsX90b&8n}ez7}*AiCL;RdU_*1idSoZrXw@ z5_++^aG?w7#h}NhDZL=VFQvo1*blgCD7-g|6#CMX-mIp{vp+{_ZQq6y8gu3&$+i_y zGP$-tjeP+e3kz{Sr5o4hr{S>4Ha9{$`G~c|x!JvsmZhh?nXk(a+dpCjw{n6WYZ!U- zVFRH`o7jhS#KF+1KCB$nj!*lrN{H{{-j~G!t9$olt;o3_^Ov{VIK_tB681wc`!XLG z05G2tJ&^l#P&%sJ5A)rC()+QXa+be7;ymY&aT+f0us7w%Ru*@R@R;hLP(4Zbo~;s( zhtcofv##P0H~RcNn<0MKMyYWu8XDf?aac#C>|~okmj<%MWhlo@cjkSE=-_Mr z7_t1oKEM14<*zm9-7}gwh;i)B!lc7wj>AgM1U4O~EG)B;Dkt1WRgTL6K$!91VB;L42(}n`iTf<3+CHSnz z?W3`ArhxF+xLobF0qt%G+kEwxVJuDXm9GA$7?)aLlCS}?J-tH45p1zrXLt?9#$C?e z#77lwYe5f3u!(58??@Idu4+arN3#0dIASE`4iQ8~GJjZNmmbBgHb3&+SL`raZp36h z&~payJ-qTA`U*qJLXBxW=3cTnwr;;+(jei5W7rj2gJ(v@T29;QQKQjdccZBDXci|F zr#+*=?n=eb2l9li=jxC4G}mKo@qKI1D5^Dv?GrOs;l65i zyF%?YSo_%O;4&j!T9lVQ%B?Xgg*?N&wLFJ4re|Z>?-ho%Mm6jo&Vekab@9@7ack_| z0eOabnLNjPJpDb6wJEgT;FS}KCozctZzf*<5^twvDg~&PvVHso)#65 z{2sf9Zg|F-Sb6RJqw&S^44HxW+U_%Wv$^lqae} z_ITzap8QO{39MUGGgQoLg!$9NR^F3cFl)j>)x0^OOW@_5HF*%7`CBZsAZnfBAu}5s&py*Nn$33v1OQ6WC!vw6CCfKe8{F zmARAH74bqoj4N0(@yt^Cb23|lgMsg+V6sGY(iD~`2p;rtDhn*xq9boyvw2VCL2e89 z+&81fiLAR&m6jxev@W76i7e15?4Wj|{a7lV#3ndT%+yk^7SWs}whBt>plNKbxVk{y zH;ok&#ee6~(PY+K{Bs_;r+|94q1q{+-Zf}?3i{BDHl?uFr4lp2S+B}0TfZC(! zOcn$456eup+GjdcN!+J0VGS41H8KF+Z!1I1W&v*S=$^&Ggx2b+S?mqYg3PpJHalIm zRO%PI1(pe4_&V?Y>I?dkP|aj{#gnaQdKzTSk@P$b>#DWtHitciSIKwkCo5Ya;HYQW zJT?Hu_Ia$XQ)3t2)n1W~VR%#5`K+?|yf`J!$AXQg5A)eP@qRIN_D`&f0FBDs1+0ok z|EVC#R+C=H>&Fq&%Gyxrg@D_98nKW~uA4Oy$dMl9p8uPMRD3WmW`op0a5EK|k!1~> zk8_V@+qCKVp2{p@7jY!?(NmY;i8^Jd;!?IieBYVUm$G(z zhL&NXYEa!}Y#{`n>}9Nv&&NI3+5|)iqR34ws#M;KFW*cs(1tl}gwA&U1ufsihIX0e_}p2Gw4jbm|flV~Sfx~gtw34GRqwy^%<={@Sg zEl{Mvb^q#LtVSckUJ0La_$?Lm;|YF0t?hs#-BJLSWZ?>^Mux;!3H`@m- zy2p0t+*VNg?QE8Kt_@w=&RU8&L#gTx%;j=g$bY7ieFy4B(!QN6#Hr#$e(V~NLLYXr z=u)+Me8e)C_JA{ApvI`3UeH4ZRijSntf_e9IW0+NJ!p)|>XwXo@CCYfj!wWLTzJW8 zK_@HiR&k>LBAwOp+>byv4rPv`H1Fgb3RYRuCA&Z_JgCPmc0l-!%Is!C#dkeu=5DsH zvJLyIB1H{Ui3-<3zS)gBq$@4hi!I*>n!k^AhEw9BeJsLo8Rrk2ExiR# zuzhS#_4b2A%%>^)S#+)C`>;-+8gN4y=r|5aO+bwR#~Y~#;R)9sXrKPZ1H^E8v7gl{ zbrU`0?WN-to6sJ-t(rNGRin@Ym_r=!9smc1PwN37Up(an&sg+OvgRf~{ z7!bILRYX76`ZvpPgrH(T< z0SmI)3D(koc{nGJ|M&y4JpAsYSbl$3d|NnlbA64i1}!+j8kO8y7sLO$Z2#f0#BA5k z(A^Ut4&PDnlWYj0wkMoq_1xC1D}+Er4uO^HXxB-EzVIRMQz(>*3N`S2Sxa3{VYLjR zlBd~X@yH7L^E5L#1@>{n!f?f^IgNc@wLhpzE-3cx-qbo5`iI*aXlgENAYN)oYA)-K zJ-*)=RvPw=4bHH};vcIi{tVRUL=VpZwr@|8(^*ylM-qW&*`I>A)<{>*u^$Cr>Uf_0 zBlJ?;E-=KVzI=$5TmmcF4u2PD_~+1_ODq80k}o3_NkNxEo=Z{}`~*D70-c9A78#SA z?GyuR@6^hW9eA)9STx??c1_2!Xw79-m2Xro11t@w{uLG~2sHc(&}rRVT6zUk1Scm~ z*l2;N=Bwb!pwa`cLCEe$o3F78xCnCkbv8vj`HqAe=zMpobc0p&srr`tAZ2p#!()#w z3C6IReCV(Cy1_aL;<0+P<0d${y?Z;j|XTb*-CK_fL|}q@ruzt%WHnb zU|j<8&SELdcN`o*n2e%=2W+_b@OK*gkj29Y?8ZZu>`^m@b8Q?aaJj}FZwAL7`v}Sl z)PBS^!*+1J4a2;wP?bDvm*4Fm#7FLq(N}!TYH>RI7!qz0jd;w)J2|!DIKh5WpFC!Y zh#lISC+sLfUGIO&lKuVxWH=#M3_{Qv;3?-Ijj^DbeW}+o@Suh2kI%5-6$YqIFECOu zJDIAz1mC}KK;8Y4?NPvW<3F%g&PEI8x)JGR=*R~aCDbOD0>~L&G_in%03=%qSibX; znOdFezVzEi7B1AITOUyvL|&g*w0Lg^_4vd#!kmwNX2C$32A|ntxHO&oj5}9^UW@(Z z9`LuHELRphY9K(8IWEczhp#c#aM^ae1Z@}OzhD{}C(2!f>FPhCTwLIWt9rRSHyYH- zsayb&kQz-^N$x6?qKA^)9{c!)3@r|#-b`)_3x_RCZX>?%p)X7}iN{1T$?`5lCHyR- z*`?G;kxdPM?*|GP=9bXJoYoZ%n~vjUquskz0`ik5K}thjyfY`sPJk*zZOzy?oX#k6 zr{Xuichea=!4Bx@VhVPWJvp*D$%94bJ3nYr%aLM~UQF&%qRAxOBDR+sOoP!u1}ZMc zg6s?~F4rzyb%<8;rn5UVQ&N0=<39eKSZn1)w5_;2&uQ*>tvr;>E^=q*18G|7k`t|W zkp}_446brXZk*&Qw=1471%=5uiftdGX|A$2u!CIXa4~ZGU(V~1uFP$FOQ^lku^8VH2SW(RG?es0X&VRCBcKBMm?|-tdc2KWZ zlkW;b6FLwmw--OPS3PQQOm9l%YRY58KU3(Zn({z5b_m*<>R`p%-L1Cfqy))rU~<jycyv-Nxg3(RP$miVC|CDg-`T|sB+$uaOa zE)yd66#s2N6GP-UFtr;YatQVe9-%UBNT^Q>LNQf4Xm_ZbLR0F?E)-K=4&hQqVtu)S zcp{X3t1oYWO0rc0`5cB{zM~pdTXTdXyI_yV34Q3_qD3M*>746lTN> z-3_EUM%gSb4J08<_M|)`u&x_S$9J5SvCtfjHZVJNMEn3FTxC;FeEpNfPjcqPZ6XwyW=5nymYe@^aw78|3 z>eoVEE(D#fhnuDiDQ?i8zS3?t=HkV)n(n$AV8(`IJp!g(3lgfidBh-H7PWagp(+_;FoaI(@ECcDApRVv=C_ocC5W&8wviu!$lhoR5Vj=G zc5(sC!b`N5ONy5>sY-jfGuH~XmqW!rGSnUId%zYNgjcl2wrtUW36d)XL*Ep zYp;5%GjPL0y=2h6jbu(~?c5R+Xt}msqRL(6onqca^?Fx%AE?n1`nkJ24%W-dw2q_mZJ4SnWkEd&>`@Uk&af|0zB=O}G2VvwW|6xpV93(KUjf zYUfLQS;m8GETw6EWs}fF&F(AT6QJ<@<9oS=nCMQIzL(1<4)lQc>stWu{SQrFnXnP~ z7soZ6X!YeO_8h4~F?XQRP%VT1K`^VFap#@kxc zm9Tal??VHuy%e(T_6(^w3v1>1H zTro@!xWjh?*l%7wdV}ex^bdP%O6~O(wV`skC;W2KUgkTy+&a^3&cZ_ zN*kvd|1*8KvUn2J9U`v-vRxS>kA`nY%c1f~aqR~39VT}dKdhyMVKPCwa2*apnL^>i zK{_t2qesK#An~t*RC0v;NzB!e*GRd6uu_d3DVN|1tRAD}c0SIo;2vpy0hYr?%LrJM z-HNsN1=u#NR17n-_nEz}*buktx6*Vt2yX7)v|1yh+#~as|XjT9YdOCe&A3 z%#d#iu(hi)3q1-{7tWGh1o6f!T5W-3w2O9HAe0RzHe2pes_#lPnLNn{gls3aP=%_D zmNag*TvyC7)B4$Rf6pxM zuLT?Kv``)`zDuN>g#c$I8oEd>BPi;OMKXdh-;SWUi{<{}u_^RsF=U*sSP7koyWkG&Ni)cNA}jsB>3>5W`Yg z{Z$^}({*eC9C3gf30!8fS;iIM;K6PiL*c9B+JZX`Uxk-f(aBYy>4_w)1~(0&cB_GY znC;c_DQt6^{f1RkjDGx0{$9*QAjse3K;Qe5KHD|N*}{1q_n% zSpYl#4t;T~6bZUv&b+I)-5EtUewWLMnWO0Q?{b+kYes#o0|%l^sLY*W1t?Tb+h$X} zHF5=GAY{W{18I81H2UWS$1a1#EIQ^kh^)meXV z$ii-VlY9siV#H>7ldwYd{gcbYn6$s-N#gn>_0eB)AJL;q1&D47HA2oW*s~&rLf60L zKSXRs^*d#Yc)P4RcPI8FLKU@zD!WN&w(CFg3~~Q1_4Yq<69H=K^84hc;^iGwVm~Bz z#0c3hcNF&1U;E`j;<}FHa{vND9JM?ENqimU9FWHXx{We$-QK%)G(JOaD4uLj+cM-P zC8xA2u=9h#re^pZYhpL9<@kBX9aUT(C6$IYfI%$%hSZCeQEV+ImN35tT>8vi`FT@a0jtLc+16# ziBr4h%7XbF!b9p;Jqomzf}LY(m}_fb3JK z;RSiCc>jy~_=0>wz)87!2@>b2#`NM6rmz)Nyeu2}I=zgQ2Y00_@+zn7i3YwAoI$6q z$n(TKov6=Mh@?R@|Ee6}wYr-@mp@lyyP6+91~E>(a}~lQXjz5pz|mP`ye^jligx2E z7n*oot}5=`Lcd)HfDa<&OOF{fFPd#~C&J`fDue^&{UrHD5Vk`KjmKt~u8x8S6 zkQ#O$(wEReo%#SPQ@kBWD<8>osJl(BCKj_(icM}(;uz;6$&pUnh|(#GR@vkqXkZ?I z82E)!^5nWyk|(ZyrjR_jje0guJ|!-BDt}jUc2CggT1Bc{?WR;)=K>o1RF0+_Ph{U> zZ$H@W`TP0mqg7Aj%HsMgm7dB9!>P=#ujJpvkNYU&kkR;tP8BHb(R0~9Q8vHds}L8iBIAmn5k{Z@|0iR**6atp89;s5R0 zL44*^I7Pmbdt&B)c_;T1*G*aS9?@tp}@o0eUh)!-p{f>t>Awq z^FP-=%T;LX7unyf0LngYRemj=JDAz7(QjYmS}vN;4mTIFy&6cLP#J`-(igdIu`XKm z{Jl7)H`uWpdQe@v+z8?A;B{JtUVV|9iq}3;J-gh*^JkcZ@y#xG(T7Z#lvq-)9S#gPtp~viWXf1z_AgAS2ifNgQzC^Ls)wxL-o00OG+a?WcDS&?05jL7Nw{G! z-UY3FwG`1T`e9>|{G_if(jmiWhblOAwynbTDqKnTG#)qAPwfQl@c{Vg+&93Q&t-gb z#86RcbvPf(1+sWI?yxT8hGoTe%xR6lcSUOKtULknuU1T1576fpQ%3U$KgE?gfYjLHN^1l%$SAIaL+|mqxbn#5 zz1|HrpUC~-VWimS5SZKpR!4uDM?5pJ<9RYDmE&%3E5lyg9!?+i*6aSg0q z3`%KXu)5fwz!K}?L0amD`vG$hKF(bk%n6LU@=kp4g)AQUWK}iWL-7*CtApvfrxGKs z*HKk3r62ah7B8i#_~}pen3qyUKqL}!;)UWt3WXlfZ{Dl{^m%P0@T zt8eMPpE6xYR|k~^OvD^_T2@Y(48>Q;@=61o{`LDPb%W*sG> zlIPtIVC{{O>t=hDf#M>^xU?xaHH~tzoz0**brc^sCasL_;E#^U&ipF)EG4*WGE7QRxn~^hKjG!by;D3%NCDI<;!1%*Oe{#byeE0;ESN zR|UAKTr(*zx_Rc6&?SEv5Z?i(Ki3dzdD<7vOwokoT_lsg^p9@{GsSGAVJQZuO20(J zfbi~K3@xX*9BiF>6hShquJ=%uZzy7r$QVHZ&6TPU%43@=ldx)zG*_D8o5fpTc}}C1 zEtF_6Z#O+?q11=w(9f)>*j}DDEBx%HNsLm)S-$~zU=1xOM&HL^83xkA7^O+6i9v3< zDC_Y0dZXppz-AUx7-FNafk9-8!K%6Rf+AWfGjaHRxFr^kKb2~w{2*?;PxD%VN(`m# zt(2x^3x<8R_sDy5mlJ*%E*H)|w8PfW>s81QtE7Q;{T!>b7Wdwx$Fa&r@k$$7+#0yE zgsQetT8bZA)3`QD#U`uol+c)|u~*)wOh;?kI3I$V`4$dMcDMd)*YGOVa>`coHec%q zSkJwz`8COTEpfL!CNG#=+A1;Fcy(@z$rIP!q=oGPrWSOuy^;cJl^)+IEmW3%&n~9k}YpvVOeWyyex2L@;&F&XZO*H4hsB$4yY$PD8UlM1A7?O$+jC#My!M=L|YHG7Xy0{q1r+I(|h{mMUqN*O8!l5qB52-B_18otg~6XMAXS+o3NGrlnPAxBi`jH)7I+wJsx3-P zVus~|Jv+L#kbmf#=)^atm-t@&t+7*#M5)cH;X^Q1v9?F!z1%^|tuF_}wkx{0^}?$U_w`{yaE3?3p2XT45vYK$Q~FkgbBFmC=?Q z-cB5f(a2IXg7@N0!VBR&9zu-p_nF?DeU&6&w^4l%|I$>-5ROq#)R8NzjdfV(wZ0yGKRY6{SX7+Tmn9|y>194!L5 zAJv+plYD&PH=7YJ!7rMR<|3+?9BvkldeOpFqi`@f z?4n^h-#A033FTEtz#iUxljRPro}*Ms?7-g&1Jn$uK2Vwf;(%XIc;8rX?_$XrAK;5F-+fzHOUcVa%*6ETCWfuRzDj3Gp0qm7}G}J zPH&}rNa-Vd#3Rr_j*0pe0W0|QUA2kF(X0?1l2?HA*DVltW5GQ_`>jgJ05^O%hC3fRKlq1h8+_LUZJA`T9oDQqm@c zf39)PC&-h9D@E^EIsaLtu*&sC4I>=iEO3^3TUdjys)M$s+%qR5(U>#^;7MtL3E73^ zrOS)JQ;~SX@g0E2vT0Vhd<`l5!UFWu3$Pq69LG{m;Y7d$8x{Bg28`ynXK3&Ogbqbp zB|qCGXbiMTNLZ<@OK$4i*K*Z_n`re-6V3Vroh>2d1LTGTozWUz4o2h1k3}r9KFG~` zgNeeY(2I_^Vh_q`yD_Il2)?MZ&BF+QA*pj57&5^qvmLN%vxxIh3mx$2DEU(%k}8;{?XY;0O>6Bar`3Xa9* zwVBXbcphHSkkSd2QZgb9i?iWHwfJCU%0)wp1$n{O!h0kb@}`QqM2>1E953~V_xj;>D24c~`9fQ$w+GuT| z5igi8@OBb;Ll1dFE`<%nYYoAA-6Y(OwuZpf_NF1Z4>Dt{aA?IByfpe5Yxw=W(Xb$s zn}fGUspgnw#sem<8h2?+jndG9+Y%kL*^@qKSXCQ&(TEmexx()Uaf(e#)W)1^g4p1M z1;8b$Z)1H7AZsAJr~wq8whclUAU@pFob2(=@F8>9IwA0+kZTOfG)&))GQJe_^h_!+sWY2BKj@ql+^ZkkzW>R83o#nV8b%)kA>R5V(o2MPJ z@s((KL30;?+y-KV9J4Co_aD^L<-72m0MGJA7ElQI;qV0HSd{S4fnG-LGi%RZnx8GO_M&~<0OmGn}4Lzw?X2fx*nrG%ebA2d25QPSg14fK1*3v(~$!Iy57;SljbBFv2U&*HymowZH zmTySzr@e9Ckm97h0pDH#*_ix9uu&$TwS;rn)f)HXYj!Q9n1|-00#uZnFlt&=#dD{WHqLq%Yr)lFG+TKI?#mmDvk>Zny?FCtxcLz4{jL;@r3@xS`n!l?_jtwRxb(0`8FP50Ci?^;{#ZAbOFyI5cI6#%I6Sat784Zz70!;fGq` zL*G79D4gJ1^$NdL8*gd^1*C+N5DvX+(P4KC)29K-4ru(wzZD7#K%0r*{9#x?rj6Voh?a4odGQ8d!93kxzXOv`djv>qgkp$e!6Yr3)~=&l26RX; zVn{6;*ow+bFAEc|B_gvN9&ta6-@?dv7|zH10w7$B{t(3)P+m1Entn zdjwv2p&C^pBt6Z`DMd#_zLuk4;zQ`sLbY41;mHQ)6c{|2_wcN6=&{ny~b^sB) zA{h3^)lG0o{n>Ihe;Ck%UU}*w$mP1wlSOK8<>guGuoyDjwx@^|gJH|HQSM^3YN^u2 zbwrWrC!CxbW)-arF1I{6F9DObU@R?MqK3+(`8r43?@Ri7iJDyM8DfR#eu?#9_pA|o zc$=y$g)p<<4r;noZBg!74HH}dzQYYTZENZ)P%L}%PcjCY%}c3mqD@QD|1Z_)=2A7= zxA7e2YYVhqBkkwgI2^cfSqVmrW7uf=>sv6Op|+ymsih6RQx@2Z-X38uI*)NgRs!3; zyhx#1%hV*_i0d4Zr$C$PDDoY!j-$w&6#90V+7Y_f8{}x@Fn+^kcoXWjJmBmU%1X#62hpD^ z)c_3q%u01F z7VyeF;A07}qKo7ZqhdE7vzleFu2Kd+aCs^H_N&^#>qRnm!h|cD*^1WeS745|Ccjnc z;7}t>qVfY6yn!(m>UJf2k{w!@bbJ|R1^zj-yd|`Lm0C*Kzl8R!g3h1;yYd7rDWFgh;V*%p#zR7391I^6I@uY494zFLvysIcp%^Z9)Uq zV)2i=)6%tSvRk@4Adg)!0A$S7>GfK5k>N|4w+@1l=i|xqH^|!}XyR|`3P|(=)~nrM z6EcZ^8q$UJYM62=m*fUDK)L2ZVH?zrKCjjQLJCh$)6SOBKx)}N@j2S%HMDGl+PPFb zF2^vHWZF5YW=1X?T^48_Qo$gZ3Pspq1IbfSp3t7ttt$khtjOAkozy~NP*kb9?IR0G-aFGvD93!Wo+!9*mp0x zM1dn4V+7sX2HEXwa@`L3_*XP$yBe%qfgXIj8dp^v#YibA2<%@_2@IR#t#oe7w;jTur<4HTB)0_K}~X9o}B8=${>G8QH+`ign$A z1Hwq2*{YwiX%0nat5v)zz!3}p2BcJC#x{iBfM0_ST)79OWvk_syk)dJ8)~sBv@Kh0 z6vZ^hn*GWJ5nDGqBWh| z0Fx8dPh9)L4T@TAEsfX-{Z15Z-l@hG8-qj*cS3gpX?#xQcBwwfqjnUtOYL1u8-c7Z z>Bn8_0*G+y{-xF`-ll^IO)!35P80u9y@Z>d02{UM{(|ZfbTH_BC(X&_oXZE2B09lKB5<)uYUtqz714|;PY~%ZNbZ9Sj^&#_q=vW(4v;7duwxx0V)t<`lf7mYUSFadgY_t7uwMxY)iLVM8 z?JHUf5L}@3uK`ZVw5iNg@S}YoAZu=U1s)1R_92ghYJ_qpi5eYLJ9-O_cF(4cuK^CJ zD;c)13vX%X$I>4M)e6NA9bjJ;|Da+b{d-Vt%6Q-JN2N zs-b~5V_=n%F(D{kmnV3pCM7}Kk`;9e--`*t?98X>N7YIdUmpQjexT*!o;PvpWty7F zE0z_t??YkOryf-Y;>3tM2DnY7>BrRIGCfZN!0<64d;=UY_5=_8?~%0Un0iD;_GCGI z%r^~b>2bADaEr!;{Z{{u!SY@T0)OdRFTj#R@%1YeJ)v6N!h5(mWiu^+>T}}g+Y_J+ zljA7wgc>C_#PcrI6e@dCt>p3>-s~T97`Ky7s-sIfcXtCXm=daM%oV(7jp+PI9A`(n z(YurCcBOA!+IC89?w#;0Z&6rSfI0bGXOmv@^{vYq4#m@IV#y*gAP%hw_@sikeMMC# z?OF&;I1RIdf%Pf(H0%a~Y0w$9QPkBqeL$ZrvQLE`1l?V`Z~$8jGb5M_R;(Dssc8lIKda0^ai*vw$aF;_Uew-Mp31+>LBIo*EH{}+DbVG-P2h$9e(}? zoWp_rbuF5APED&8ieSk0?$E-}&#*bW@#(h^A$zfuWgB3s{<=~$u}A_21;4Y}xdoJP z9%d^w=*#nJOV59|0?mR}uf5-t`8OsX7?@Aab#(bWwEmIga{-#NhBV}YnpA91eQcV( zwDp48SzKM9hPqEp*kLc3o22xpsRp9Kuo}I& zs)qX?<>*aW=Gf)=^RC!sAzq}r)N^)HT4LN63^@E3!KaDH`E~IWdzl{0g9uj zt>+D>=aeZ`Y0bZCtlMTV6t*-RCzMVJ5?mJEGXLxp^eGpo4 zYIp}|?ci}*aYwD-ozscWEES#&6CuuoH8y;ZwgO_->d^H&Y8^h>?qYc!1yjsj&?oNH zoquq-_%1f%{hcs`0}ZTgrcHMNUEcKMu3DpUCS*ZO@kTSLRUGsH@5d32#7>_kHv7X~ zQYXdT?RJOu;>R}7uzTuLpc(ho2Ij~ga1<2j>yH+bED4?*0$1~;EB9eg z6iv_W!`9;2LGpS4Xz`$W57cg6PqXZkJ?P`C!bOF4DT_8d03s|!UJpTYUk;#F4*|Fa z+t7zFE~xuWEF-T zsK;GZxb(Ll$@}00`bRty z>RDcVIAin>A=o5GYSQrM>e%9g>+0-|Qq%(s9_6pr9}%2`#>Xm-CQx_jY2at3uD}*d(oYkBkx^^* zBX2#>5DZmrTug@|?Zo$-UIQfIb6gZfvgXl*w@JMqCMAqC{T*y&=FygS>W~hD8smIm zR~kEG8MWk}gim99PzLjHcJ^pXA+2#1#L}zEEXY0`*Pe-wE4rpT$#Mu2dbG;h0zHw< z1~O>edsy(ql52swntLixgH8V|w-dKIBEj|Fdj;w!<*w`eJ|f7y!hhs#9yx!37=bIg z@Q)u+B6XR)9y@CSsNd9ZR2W3KDCVs%#WI>?5RG88zuO?1z*^5)5yO?7ziGT8D!^9p z2StP{JL2e=BD@TUF{6ki*m6e|K_(pi77@YTZ}#c?&@^=lCIE55EVmu1FGQ^@BD|6w zuL195t=>E0J@=J1p-u6ct~UZlBIOY#&-QO`XggUx1&=($vBz1}mr2XtPnoz=-*|QS?#% zXlmmd}RL7`#7Z-Jvhtc$1aWPRw`k{*~Hw`q%MYMr=&NdgZ5|)O&T}4UdtPhQLMN6w_g{$ah@Lk|0dMkJOQC~Mvn@wTe zM1PYry(`d-nRLc-D0!IB+<_cwZxWZ3*S=K4T~sK!uNfcNn21w4{q;iIfLoUCq8!GU z%O$u#x7Zu@6_lmoy3#&>W4^cyTn?`LsL|0{JIr_~*G%nLI4RFHrCs1QkOaW7I zxmp0Zln|cE%lA~Fga|5g4jO0H&&Dj z_fKLy*sBD~L)IZ*%l_Jt9zzjkVNp&Dr)_3&PJxrE1*Js;+*CSUS_FY3ep6aR8-Ar4 zWkgeU*j7fYSKf7{NKa8(`L`=2d5U`BFA^{~eNb6u(S=2AFRSi7CD2As5fQQ&Re+*GfHGh_a1}*3cPdhotZs4E1rBng2swL+N`^#Rl$R*RUi<2K zi&$m-V4CDDLc&f%-&ff0t&WBLrcVGa*LwxIQrPcmI_@o61$0FXFz{g+?`o!w1ZC+C z!BISBw7O$>b*W)l5$NNIVoBCwj&Y=qWrVi{MJ(n8KTvvEVODN6Bq}Q!)c>g=1dyZf z?Xw+n^=lv6vLcJswnMlg`eYGO&{qU0>z3OF`HD1lGNt(mm{VQtX}ecW;1-V`4G$1MmmN?~ zmzzNh(%d=;2CeUOH%p8>TqrV7R87JBbUOZN|-=~d1*rGki z6f6=#7XAx&H@lg@3SqVGM!q9`v~!zK;2AU(w8oE|Hmpxn_!2n07ZYM`T~{6MT&{$KZA z7UXZopF&BZ!&8OjFwTv=2rbpNxg{s|`9A+tS0wC10$z%y#OY`13%oKDKbBU8h}v=m zUV)|3oo%;5gs*~_PR7cj8ko}P%A%n;Tp$67Bni-l}ZT1nNvWllUe`zc7Wj;g^J;;Nu;!^B81B<|tj32ae|RuO|i z;eK94B$V#_<@*Bt{B@v;T!=2Ucsfu;%vB!dQID!(ymDfM?Lt-2qA1v%&>A9?`FZ|v zr-?O0glntAh@*vb^`)tFOm*5?LmWUCQ=>#n(8VXBL=6Ol5j8~=1mE>*igtltZ*~+< zv@8uu$LclD`XgvLep%7g32nezQcdw37NV+Nw(+5Fl@JWo9*&=Xj9KTt@^LAfK;QS7a$;pVGd%qJdAXr*8_P|og*CJmfiJz?ew^+Z1iZadUq>J*>y5?kJ6q5u-(;^ZLvN(W@9SRLMO} z1M7q+WUeW{h}r)o{Wi} z=-8b5)YU0LQC< zT2mutAvZzbdvvSa4=zWkYXi{?SHXU6AnF+g(~SnAiIivcFS#9Is}U=%8_N5hX5c)- zyEOk*72ONeRBi|x5yqn_5MZ{YIt@iD<@au6Z73p?V|8dpLowdD+c|y5X&1w(VIvU; zKBRvmF`(ENXdkx=k2MlqA~GKE=WDmaK-EIK?r7H<=Z~p+cE-&~*I0aj=$tU>8ZTNG zxl-_!ev8L}Vxg1q;zHPASdQr!6UaA6AJ}DW3#VB$Sb*Km?qN@3!r}+IkRU?6i{59H zbXmIs6p?5xZk_8mA|8$*zs90xNS*;hFA@hq0{r6U_eLq$$41S$$D_?}gID$~88!AE zt!xaCs7%gHgddyYHxV6xSJIo{0Noi)zcmpFkgGmxBB~YtS6~;`XG~FqswIjM%6T*W zm?#3>PD7xl>x3AuS!^d0aWpF5^(OzO!j}!(n~KKD*k1HiQ{d#|C237l5K=$)f^|25 z80NFh#4z8Qh^xXjB>oAOm(Zx=DD=$s)xY_H2KNWeu$SSbuQ@2hVl<{Xh?yHb=zMeG zS9+?4W8(O1cXiYlPHrtkdsi>y!95d?YF#B7(L(sjX(KqKj(O||TF^oyDev6rY73Ar zDI{BpvTy?w+)}t16iYXXYK3#QJN0TMswnr}Xm%@Xb;t)>iTZH0;FpZEW*8+WgLW%n z8iY$H~I$~xRebX2r=RH3c7Qexb8EJs#M<7ijl0PrH9^*!5( z6`+{5w-W<^Mas7qqm}F7w4}Y5jtkyF9mJ$k=fiky!EEDnWdB}SQ4=oFrVcW8vd4Z;B4JHiOS96iWLIy z`D}N44ahtyBULwigqdCB0lUL+{o);eOy4Won~MKI-1KE0W?Fxm)=7l*IAHw0hkbZa zCODe(=LIxIg3TG zbm#BosB&lFV~#>!mh*r+OMZ5`<9h?BTW1ler1hg&oke%$r&@Hsvj_+uhA_S;%2t`# z9*&}&k%k`Iaq98xW{%I#!QK0MU4&=j2j^U!befa<2NkM~@ncAz5ad`ZRCUj0n-Y*{ z+M6Pr2Z9DK7^^-UOTKmkK3Teenr}?GU2r79ada0@;Go#Miq@XqjyeK!jW1wC!7EmT z#&s1H%@>ppbTYSS$pIlcjW%@^Z2}QK1q%(y`wLC_d^+8xO^E|B#W#9WrEVggH}Z&X zzy_BMw5%I$MI)|9H!-uMVgMpoi33a$8n+?0jD%tP$g^9g8MdTi`<;CBT%$ zL0vz9KIdr<(ZRb~0b~B64!Gni3D~68D*sUiDu0>6aB%fiCt0 znyN=}y@a=C0FvXZ?TdnV2UV|66K`^78r4gD5AC(Nw`dSF9a<1{pN){1+&agAwj9+; zyyKo*IQ766F6c&MdyDGc$KJkYgsd9(Ev6?}%E7^oFbYm@jQ zO%hF({`h!s4y+hiRdSde&vYr2z^K314US2S&k<;x9s ztC2ELv^C}a`m&%!)&y2e6lhz2rG5hiZtNbStbrn>%A8RBP-+Le9Nw!C{zJ1<4Eh=P zE!KJCiyR+GS8)_T=~s1-*yPp`MlB!G7SoeK`0|?MHCWW}cz~PO`Ghkg(F)(0QL}%i z9)p4UQs~RUqOCG3kNz1fLQCw$syGbF9_ut=Ns^z5E^r0e?=w-Y&VboyAC4~4>pN6Y z=UZ4FVHK=washBt`8>;Sj+m^xtK$kFnb%wS?f@PAOoW59djFZ;sn-y34pOuyLqzY0 zUxHYQRwjMiK&Mm$@ZHHGT>FU&3zsZoXfu4LBcdKGGX7pcQ-_NB%3ry(XQ=24v31BW zocgEA)0e{_p_oB`4HLDLzUS%nFi}Byzn20(7xR?sMQHQqA`u(TFkJZ7egFMSdpc-Y{W%izSOZ@Yn5f5R9Vxwux^G4Cf;+9D9x6ZrZcu)Ok3ViakZ> z>*1n{@^>-1Ib2jWTbsPKUo|QmDfVbZsxU%Cu>ZUfq86mXvqpfU_>m5b5bc!V@2T7u zqF>c5a}n3mmQd;!1p1f+_8j+X5@6%j(HODKmEHZoOdH03rtD_`Qf>PZ+V}+y4#YM6 z0tcQOnMUFhUu>gVBSm=N!X-S7^$QEXT8#Csi1lVs6T^#Efxa3EzIPJs94X4M6NHh% z*L^G(>&|4kB^Oo`NmO(cKJN=BiW&vkNa{pdG)k0pi$2Y;1~2sxJRUk~+dWFOR18oF zjutn(euh2-q842+z>b&s5+8VrE49gO3=X8$x_}pR8V5QJ7x;`?gSITWe4*8%#$&`Z z<#HoBGDi3tvgqL$5vZJBOr^$x8vNGQYpj6h0es~+(H<8U`;QYFl>^UhUgL#lF}@r< z8QA^YI_f_e++bt6HCc4Vq*5Fh$)fAWY zg}Z6zOViHh+HODUHeFP7NfNxR5G6NH``k8bx|nG|BqYDDMV3K1CTwf1kboH`(4!gH z<|)_7IZMn|t_9N4EU^GyEvnBH!<01!`eCNHr+k}9b7qOnZcmo6!`92waqw%mmf1Sa z7KnH-)s{a8gLS*M;0;zC)~UNNQJFM$u83A9Otx*DD;DEAOb=Vj`Qm2-d>B1nAXXTa zxnpfhmI_?UdVJE>?K|+orZ|_8Z8%V6=lXFdi;YJ4cYnN z6`~$)47WkAza0v=;+Kdut}4Tcpq=QZLmF6w?| zJGT~?5|@hIe-q`EFET0WH_@-_YN(Ac9q8*zTs_Ud!Em`rNwQpi-q5I+GP6JzfTTM+ z#g!$WIA*KUU%n}3gSb5>OJhwA&bGm6wzA5zzEw|)MH7+C}w zva2?nzG+ltv)H9%-?Ba2EY31m9M~#m8I-3)UAALx%hK`f;(?*EZTAiVmlFLu*bZb1 zwJ31gvE8C#nW@<5ThIp}7RD*JEPUI?MXN%l9FeJLi)ld)2>mr(3O@o$!`;(>tiwH?YhvEJ)(1^?-%hQ!gl4B$9fG|JA)Q%>L{LI8D5G_ z0?fa5CgWb<)aKN3uLvlS)tP~1U_8tR5V9A`Rf#6=1x!?-R{KP%?`E7mY})V1)DlBJ zRBM4i7mV1J($#(7TqZ8a72lM&y@2sp$ESJ`%;UoY^kc4wt3^m>!U~t19-%U5u~J~A zvcE(d+IZw4)~9LeR{enc$VokZMn3yN=$E9H`$c6y?YRA-oagoVD9&_;E;UR?3usU~ zJfAk~7a3rcq7I1hSgZ{PAk>DJxdY;qa&a#G@HgP+XWI8Sgrwt1IS8O?OO*}^pNci1 z>(i~DXItCzw`Ds!n)F2mAJN?WhBY+oplGh-K+Jnk)Gimj8I`t{y-L=!tK{BPiVgctdC-t?p=U8jKNQaWtVGN5E`{(PaE62lmp+ zBch+Ocr6t_D!PUL+t3Zxq0eDkkzNln25b1qM+hNgIh5LpEf!$Lgh(I(YuHVi@%1CR zdQ^DP+M~j`k`Zb4*v}kxE$5>>1)6yD0Od39rLIDywR)v6?-LbWowfvbhi7brBSmZG zC4Kb`y`(QyJSIj#1HR-KmXTe=00mEOLGO-%Eic^yxH~JRXUjLbyyzSYjdF1tv%_+V zJub?6Kk{eseM}ce{?)>KD4J7`i<&-B70_$0mjPTly7cekYLANzSbo!+a*qrDVy}Wx z;xgSk4l!4Ax_UzVRB107P0B6Gf&h-Y=ciM1Lkn+?>O;3ry zvbb(8rWF4AzN~FM4;O!~M^M@ummd%L&6dAqNSc+|jjNJTI0gH3pYO{(iV~j;noqQrXDk zcRD%lh@fr@&ie~_5O4mA`K$>!JQlAst-d6N72EHP+>PXyCn_sB=c!qq2v#-=;bFr%)tr}38| zr#N_xR$oRFzh0xmmqonK9dD+%p`?VN`2%;r9Sq$#m~vLszzr0BMWmOn?uqd%3|5@t zoA{Tf6QjcD985l}XPi`7K2$X$iousBL%V8vvO zX=S>7U4(njuL@2f^Fj;OJ%Q6PkDTd(7`zyJJ&L>`Rz+MzH(P*9d04tS9yCdT`8rZr zS%yGti5V~7nWnMw6Rw>WCKE((;mXMqROeq2pe$WQ-TxI{m8;mx-tF+Y|F7s(HEXK5fIF?*BzZy!pqY$4{@wor9gZ24Xn@o#GNVaz!<{^e zxCz1bDjIN8)NNEZRG)=Z#5c=hL_6v@&(zpksph2G-GY)Q8IvI3PPU_2IKtP8qkIz3 zdi0j2(2(QP_qC)OH$|<$FRYk+Yw$??SSNuuxTXsb<6+Uteo7JS*@2Lu)el8_&HvGhOa3oyFQK9vE}tT?55*8 zogw$b>gKF*anhneOWZjXhf+n=-jtCDp_Yd}BZlgi?U~sGt zc9}dHC4)uGEcmh-Sj7m4fr{Q0RlLU?;t`~H1K&h%S+^8Nv7;ZAn%@;cHSgL-=*eN_ zQ7=SWf?!S9^qbY$(U51(~Yz62;Vh$ z#l36{sldE!7MborNH~8Mh29fBz5}@k2(hZTGV-D5HN9xJS=8sAs2p5IFY-W}woV^| zR#hh_W0FsJH~|OSdn!&F?}^FEmg5w4A3DLw$7$GoQ9Ui?pdD~4W?VOUztSwLC+hAG=~H4mNgm>Yjfb zck2es1`xSuxBOq~Yn~d(uZTl^KyP~Gmb~7 z3petQH{5Gscw1Xb%hRC%ri>3o#i%IGwcEHC8hGpBc4rruSLNCPE6Lg+dW+Xj9|5Zt z`8*O0l-5@2{zz1bpR?)>w%|l;^MqI|b|JucTNz+tnjQH7LNC9@F_bYZ!jKYxjA|b< z9(+wl9^q&Rpr?<-SIT2JM|&(PG#|I0kF7my5b-nG)hhY&_ES>k<5&$WhBL1z@2g#K zS;F&ec50-bd0HH%{m4a#bUE8@#qzu%-G3}rD5G*|?i10_ySNdxlaXCm_YNvy$xg)5 zgD0YN#D${BZ~q^yZ?Tv7J{GM{zkt>`+ur)0aTN7btW#d)(7#VbFYhHqP<#F-t&c|~ zwBEM?^?W9R!npo5ynAkssBN);|-U!4+=V=VFsH-{{qI;p21AfR+w-b6)qN=rC@&=ydnKl@KeAV%l1EY{Y*p*T{kmtGWbO4j+VcuS z>FfzJGw?}nH0!mn!JAf-H{iS_&3hvT`uzLW#c7LoHxP$r-~#&{>MY|CPK~BAZ=u9F z@;l9X3t?>DXxrwuu;WqYm!i=3qO+IxFC2z=Xpm3-7@#NK=AMaJ;|#ErUh-Zf!@v05 z_u$|osb7J}H<;$Pl*0@j^S8?(%6tzBHOSgtlU|?~wY!68#}p5!uFrmB8gGz)DtFy% z)fDMr@cH%`%2nR^Db>_B(!NfS)U$}3i8y)pi^wZVwl^IuD(iVJ9|K5+A^HdycI*Mj z+3ym(K1@MIIhr{gqx3iThU6)I{6MD^AR(NkxbB3A@pRNEd%@;BvY70wd|s7i6qB*8 z{v{pyc0fiYI#*1FrTzR`I&H;QvvlKa6<4Rv9RF#2EgRS&0{3$=5EP>vuqe1--J;We zlVkxnB26GzF*ZwPceH?P2i0^NLqK~rw5Q#KIX9Q6tM?H;rXII*Z1xK7Hc@KameS=IwBF~V7npr_-^nLnIDU1b};-;V~n}syz6!rx8t4_;5ShsBbXYPWDRVC6qCGJ>?;igzocI7GNRT}1F$*l z=RdWAVHiO#QCw^Y*daSR3%1nJY}A|bh-N4|VRHOEiCrX;1LTyWrZJ=D=o8%)!-7%X=7=b$PwyF%f8C}OVq23EZ?mARb!evPA%G0RT5uyZ>7O#PCL7dv$|39y%Txa7SL@=N z0v)M9sn2#pxM~T+Hf{uys4$DG?j_-TI)`R>N%Gl|hgO0NpAKaO*iv3%Z))Hz&2ZS% z-Wve7`2~&kmQ|H$ujprQSsv2rgWfW@{Kc0qbgmL)iASO(BrzigYFK70nLM$uVPz#M zSyuk(<9P`kwJ($q6!H2vVR@c(qpYk|Z0|*sNTvWES*6$t%MB$yiQCd#~WETx1mjyVagQ#BA$WPQqDV&PlTR%MhRNvnbdNkr zL{Cc65q}v08_NJWw^)laC^yKqC_sK;Ff_CkFE0^JBAU!Wa*?^(N#vcE`Z&tD>*E0R zk`p8m=m^m+gJl&~NL7%b%A3d3wt{@a;?Ih5p3l3ZsJKRlyuxu_chT$TxKKew`5Cz7 z&q8D~+$7As?^t6NrI0uCFr%Xr;punh`3?Ro(LZW2t8=^?en11f#5t!XH_6%~>BM z6tm|;rC<1-+W))jjcp*4+w6tj?4D4k;z=hk2S2CaO7chLNozV-Nk+o><6R{=3FO~| z%F+`Go%xl48J{Q9{>pM%@oy1!9DFWtcr0}Zlm1GZ7c>FCxKRCVnEYOu)QV!mWhqo^ zA1*^Nt7+lV)4Z}KkESl;%Cy3%@Sru}a)t8lDz&a6!&y69MS2DXM?t)1Z2&#*5O}=X=V>?pT$=0+K=JMZkk`ZzW z4*VGraz&&Y2seQ5I^CW~Ujgm2?;x3A5T2ilxgCk40~osxNGz1=Q-pd&$}y1xK+oZ| z*eBI?f9t4rZy%}+wpZJ#=;gL5B&x|CRT?+tMIY~J9n#KmPQ-JHW893r(bYzKS8eXo zylS#z>n`@!$FLzPgphSh(baL?*MLB!c%AU8WH0ykC*{7<%YiF|(UJL)eWR|rNA;>> zH4~|Qbs6fj(>}nSpVTUgS^(rf2GQc`GN9(8LP)L-_(eccb{nzQ{(D!WRv=L+hht*|@8XKYZkO4P8F@$ioHZQ^@;oADN1RscWr` zK*oeekxNZkBW*hzM(Lq(@1@R02Btl{?o0lj{we8rE`sM6b`*-6b#{VD)pPrqruM)) ze3YS3fS%-In$=7%Vjkc{}U5goAxlkX0~_p=L;WY*m-05QN6ZQf~$ts`3mx6Q`hc?!YJM=mV# zjlOhV03pq3enA0l*lesL5t{TYU8y5W%c1uC;WwzDj%*eGQzoX%&iA*CgV3eQNgSLw zHA{1Vfh==y2eiggG$7ixx>zA5#Zkk=i`=z)K`;Ud)|Clm5>BBecpI1~vmV?u^%^)H z4OhGCN*`swYjUZ_wC70*ttV?KcWY9gda{zT{1nZs2V|Iin%38oOO&gpsYMLnRy$1# zVq|60YDc4@AQFck8Z`5k<(mKB$80^Qdlp*}2DA zd`+CSF)qnEE??Sqz19=JQ$zdr3Rr832|{DkkH!Dp;3T6WcF#Z6c@E7#0&JSY)B|=y z`24#NN1>e-{Apz%5ap{&^?8dOqq+^Sd9PNdVGRHq-yWwq4P;+-!O=i2!_WL!jcE|)lis->UhEQOf?BM*U9=ft1ddGa45+_>+{_>Q!qsAtXn|0wU<{GH$ z!_l+sDLspm-Jtes(@@qy@bIjL@@pkC4`G_*Y-Pm;THQ$A2GUv(FT;GE;~d7_P0MB0 zF8W|!`#*L;d}hWTk0>u*4rhPU39`G==Mk+b3v?(!j#i#Lw8b};R~2R1S*n;M zt0_-bQ`aOpOUbxLcas3{r_PX9QyFP4aTYT!>HHkBvfk*0bx*+V&a z+BUbDENxKco}$&wvEMe|rc=#jO=aP2a%~~|DC_g-ix#qslABLow~*}&HEow$NSMQq zt3Wqe%G#z@t(Xno9<+;h%H!q~)=J)mUt+IhS+3;Mzj&F`;2d_UJ%5FTnk7qb<>$(_ zfyq)eDEHUXh}N>YlK+@iww7a*^h4y=M)p@)|4W%|hY+KsPiHfoy+7{gjgpy0o zS|Ek(t~RFHzU(YpDayQ7^mkW~+;ymAH`!BJ)f9p2fmphhqjTLP?nB$+y367QbMkbD znGFkF=HOGUMtF+t-9z?-+lRk;$RM2HH+#qggVGwNroAw@HGj~QUb35#_lB*1xXouRjllGFZ;+kKJ8En;zDgoVJX}_!yK`qp&_;GE35mJk&^ctCHI%TiZ|bZQ&G3wz^#b>(l7c%d)*J2dy@4F?9&HY zj{cs)*WOpU=sjX@`oX8rovqCJpcpXB8EE-E24FKmB|HFhu0I_ffH_`FMFz?sW$zpc z9VnYB6FXDtKp6nujRpdiUX`M~17%#1ab^!%{hlps2gzuqcX8@INP2n=nGN(lealB? zy!s*Zo)uM{W)70|BX^bbaC%}Ip6G50b=_lsPWCs2n)lnEJ4Kj6eGlOos}h@NF&-;P z?*{2zmm4fA8Wd_W7?63hBrO~)ligFeVC|!crdDuLX6#XtUJjNO;K9G#XQ1_mmP9-$ zSt;Z!B6}6~c+vi>_jtwr+$kb*7y7*BK}$cA@#Xh$^e~HYFMeRojq98acOLMjy$Ba1 z23U+$sK^j7ZN;eK5E>u2Vm>?qQx@*t*HXcZU7BSFFh+c((m{P_oG*d>)?h zoxRZCB0QqMXE-ZAp0ERQjpNiB@x_J0%U3QT1;kDdRPo({NH-OL=7M!d0Jh zocI!nM)Z+r*w5V@KpMscTZ9j8O=3c5`%qcF$ukr89D%8gd96Q=b;q;uz5X2Qk7rj! z?>Ujnn2YJp$+39$b=IFd!Q9zwq6))gwY2kYdOy+VM@Pq)?%qayy0h&$etHfzTg-kW zfV#@T5yR>a_9EXp5svY2tpO^J;laNm-!UWW^hf)QY}B9aGqOp49*dRF-}jn(w4E6y z{R~k4JpWuqmWe^OwT-Zt>)|0E&IEA!MJ1o6`om>u<>hJWFdWCq4ObW&$|`ANT=d~| z$DBbf$SRKGNMY?TC=zH&K|&uxLcG;?m8*wSu5l^;^68ks&KGj=fKOV6G-PEuvP@IU z@hTf9;~k#OEyl5U(4953LJ!#W1?HLDhc#xPYZ~X^boWC}fq4*;t>HCMoGE#J*HtndxP&pJu)&Ij4OY?9-I1Q5p+}XQ*kzgt1+l$DKjZ_e)Pfhj=|(HUx;Z$S zG}fFrj`)n2>Bzv^{Eb@aF+J@s?AUZCz6ZnGs@IDdhqlnFv1@A&rxf?eF~jj*fU%lp zox|V6Tq6&X|K%FnIiBzl{ZYBV+zNl~K85$;=pJB7gN`fISOP8Kr!0Q-dE(2x`aBKR zd$jY6Io6m!G>6&Byp6gbB`%;m7zn6)?AI)EjqgyNS0~YO=1Jme==P%hKwz%0y(!2x zadKA7Ezs)PH=Ll`6LrXnd0rYRlR3rTUgTd)o;HFLhT0R_g&?6P60A{c(E(rkyoz3O zjY}NeSzR+Z{eUUc1GA<5;X%$LrEmXdy;$P~$`l8y1r@X#p>GPbS-93`pMpzzBh^ur z|LKRALlqkC$L#?IN}x#Oy?j{F^7)2o3_u1$OeS1j6j;NbJJXDj(ktzOGs^EW&3eSp zZjI6Ks>9V)ycd|SA}}u2TBKtMR%w?A=S`6zB=COYS0IW`OQbs{B!nn?CK52-JNz8b#kH=qhv%i z4;~*+b{0CtEWAQ@1xNL{&g{fr_Cl{{2lsevP)WuVS-IBT<0#Jc+)xPC_88%TAP=X_ zY>icWx2fS#i}_o;Tg?^G0j4Q480~{~8kiyjs`W#THVf8G_I}vWwAEP9Oka+vzoCWZ zR^w(2#Oj*Oe`Ed-v^7Q647-6Ma5okY4=M*N#*KJuZUNbET!W`v<39Z5e*;XXjWe5( zPbyH=6fR@HQE488r-z9dEjRT%{e@to$ITOq`2+eA9FUD33$q1hd=t! zp_O%gqbn?iAVqr*ojHR@54-?6V3WUdw2W1TEhWPkxxg@=7LJiY=7&Y?eYCKqv9g-& z0qzy0V`HSZIdTzL#H>WPROyt&5dehMIK{YWtV}le916saZXQ(BYOH|z+zVq|lqssU zrlDU#!aKP$efy=Hp*#to%Hw3+a+?BJbb7~cz--4{va>Wh|52bV3ZTq!GRBmxc<6dx z%t$5eo}gpnWU2UComl6Zj!y>0>I$42>sUa1RM&hj63$B;OAFJGa|cvCcWZ+c8gC%{@t3tfZ?%{tzICwFgSqSLrN9?;!jF3(}iCVNtE zUnGTblEv8FmpV_7`;~1EsQg5^B;bBu{X^n;v2eIsjT;KwdH7$j7v)mgWg}gl2we#- zG*1HU{L@2t-(&ZC6xgx29f`WsiW}Z}jH6XwM9Kb8*_mdwO%x z_U0f`nk;(;HnbNTr={A9_13!Ci*?#LNTAp3Wa>3Vrkj?(Msq-e93nwG;zSRo$Y7<{ zV=A2?194Tdc82V#ob{ju8S-pkiC22peYAvv*F0gpwXi#S*PV8T@CKjRl4ehpeM~c7 zet>~K+K%^R$b`bB7?sHcPqpYdwa{=@@eLy%xa+!}TzsO}A6?8L|?6Zjtp%?P7-U=zs18inYowVK0eq%$ge1 z3ln2C*M6e6Zfg9B7s;esTxp^I(!1$0tZdHh|EH_nTe+)2#iO0|Uid3$r$w48ggxd( zH)WRYYW74(=w^d*K%Top^rYPv*d-N&Xnt)*16Hx zUMF`d*BL^)XULMpS3lGtY?PMwoUY6O)KsMBGvu(=HUBM+nQ0{M{K=FPh~Hl_UKCgw zx!+ld_m6RafTW&0&|9dhRd}v<8>qQn)4TQ3sbrY^A);aaVEQ8qswnt~%7TLNb80nH z)>h`l)7LW@;HJ_+exGokip`Q^mHQc#J`19yXI{2Nv*cF><()GH%#l^oK1BDk8iViZ z-L}^{J=VL8(;DRI-A1R!Y`zV{v6LhSOH$?z2R~##At^O=mZY?va9Nu<_f`3L zj=9A@nHR>EOSBrV^RvbGhMu%5#h6(8>?9Ql2lWK~1P|fL_@G2q7&$P0VlJ)vMwUy< zuor`6gf)Dc{(Rxf*&hoRQldcoXatdM97ihRJ^AA^$7;Vn)IYPQw)mp{nH`e)zJ(wt zM0?%9e(WS9_HFC0pF4>eyF;`mllZuUbUHR9(GurLiF0L}l2ayf;$ExqQog>B6X9fH z?OZ5sI?}$mKqs%Sk(ehdxwJ%fTXbvI(jQR$dD1)W%q?Es){fP!sqyOS3}=0Pb)z`J z8ndY~4%$U31_by69rgp>`CqPaw&STF*c(MZo^_}+nJe`}C9W~zLyaDeC;eokGxMY= zZ855{WAOz^PBl=emkC8#cG_uPrFjUof{`&)C_`3!O>h}FQoH7JJ12- z_{_H&;~Zt+!zm^P&s?;&qbQ%N7}VDx`e*cHDs!6snVG+{VLA_Z6+d?@4pIpX_Wq>7 z1V@AS@XP=5+v((2EVmTn_&{w0@M*4b>n++dUsmy~G@jQe$7;+(9R^!=&!YWtkDM2P zXu4mIA{Iz?y^-Z$W*Gf_61#*J2`X-%O04d;(yJR34!k1G>rYLz6 zY|9BURb}#ZGAxGle`!7iE{0fP|7dsv2Sxe=L?Jv^zuQfinSQxEmS!!MQIXrP@kmnJ zX%93V2&-$SPwGHeiIG$tM@3&4`Pk{6Xxp>Ja-KoCKANmcWg4uGihnCxE4$uPk8fp5 zWmhV#`xZ(h@5MMavWzw8)wiHr_mrSY-^qH;s}{L9-7zz{x!^l|M!OQU_&e!qXiuBJ zgT$l}o%s&>;v3*smqA8*wKat=gXrz>LOS~$6bSu1=xe0ow!@lbP@Hr`@-kUNx#CW4 z%TfGNGDR*&^;OB#Z#l@h--)I#hsM7KZCNhsDy@m0FP9zJZQJ)4(cuM@_PwlytFyN6 zK_*nE^WV!bzvs8095LD8{su7$amxu2Hu7<417g}++U=GU^n>*8y7|A98HrVn#FgD! z+T#C`iwnJu+zJ0B_p1-NJ!shvn2lK4@q;Yq8jHgZw|Lewgw&w?A7qU8>6`y|cr(%U zfZ23qrQE6P_?*7~2{Sh3IUV{5Iwk+%w);Q9vO$@cV|(;7B zm`435+bClm+j4(|1%x{gzrJ(ee)Y}<980$3U%{CuhX&CPt7P>$tHItf(3+T1IuC^h zzv$!J0eAQOvI2wM$$M5S8^Vaf?n^4miN1(4m88JcP?#L)PpwvCJ-&HJGgiy5N_>8d zQDTziZTq%}aac}Ue1?M7fU-DPf!eMC+S<~W=C6?0Fz`O^LWkB!U)Lhv zq8GNIf@TowyGB-mYpsB_(m%2R_|8PjJ06rio*}30!{rfbEqB|8yMTwQQ`>8TY2;ct z!F63Eo2R85;{ys#q}Ix2%D!kyTqm2Vs}LVV`*RU3S_cg!+{vtyeY{?bg7q#(8jS0a zU%WTRX$8;vK-(2ZEq{|CUJGh5X}CAP0T6>-l)^yrK*L4h-{cBkXT&u5h%Etb?MufY zP%vAvg0pP39zcDOXykg?+7!BoEnIQM7D^Ru`&>G{9;Re&RIpwqrajw*3&xD_v^OyQ zgQ29;oxk<>xQ>XY)?PnvPPGLKhQk70jyXK7`3vZ^O|~Ws<{Yz2NrZn^M`%vG*HGdz z-WuU84+|Za@g7f$@MNcHYc<6;VTAe{Um9#!0V!;yZkkydg1P4CAGM3(NQUqUwGkSG zd1rfCD$<}r)T%)M3n!3RP}9^513d~imr8t(ykDS|?t)hI)_Ff2Ok|&Axw_6V?$eAP zlI-K)Az*Dk0Gm${y|uLaj@H}?N6zSMI9k*1v#}K=;_Xg-2nf*o;@mhiX?K8u;}6nc z_c%QZ6XKrO7f!Vy6-M}$v}X1_5?#hLwE-G$l$8>L0DJokNm)${mdEj-uPtX1GUb6( zw|tKCGMgfPm!4_w;%Z--xD_bWS`W%?Qckl?nMYA#3+Q&hYOMj5R;BVenibe zW1c)f98Mp{nE&PMPs9ey-QbkA`!0x|-Y&?bM=sK)_ILr~S_nRBU|NyN8x$8H3ot#V z8O(en^?jbdi+?S-ah6m0>o`vbqR9|tQF>Sj&$JzwBLZ zLr5g@o8TcK5-}n0n?8|Sf)gL~00+ao!uh4}2DvL-KVYXD)A8L-3pUAdk)v~gkwGTi zMuN8TupPx6=9lU4FvoMd3ojoTtH!i?ldMv_tzI%UO{=qoZfufa-Y2vFAD-$2RkFcw zEs^HiU_%3OmksB1E6TG$0lSidHp`z|ogG`qK*El?Ah!`rHgSvQh#lYIelhF9V=l~M z73qDArzH-1FGPW3+_cby%!1S)@WB716}B;oytkl>WmJ2M>;UE4>@BiC>~x=Rkw40* zU)ovG+q7b7K z?6(~04La@b9N7SoDV+DnrD{+rEK?%;(b_%I%jJg@7bjdji#(vY^rPc@S_yFxWBR>yZ1=oOa&l6Nbs#{XVM0cl@#Q?itz7^pp zSDV_Ml~vWq-WW~MMfCMq8R7G|nX6O&OKdtvA^T;Ei%8XMbo#7(QO<_TTH02^sBvB- zX2b>=@^$rrHNij88U=6n=b&f)l1iPI0gY@GUl-sC!_*)qnGny~SgehU)0ou9rq0G6 z;X(T`!db^z62h=+Eeo#xuRc#Cp&w|>$DRj8YoTAy%gdtOF`gyk7MguQhKPEJy4BWU z+I2w&%8X9D-wNP`?9K&Pft1-x>vJ$&ZzQ@_#xB18Nha-+d)GqyX zUeHm-K9+ew8vk0&E~v((uJ9|O;W{e4w7-7tsKlaw6u!04wW(g3qpzWKBR$(bd*H-2 zEabN41u?oo>D~J4A3-d|L*dKS>^;TWUk_EIahK$uCGPEJyge$y;jiw2c9G)pWM98_ zurvd#T>S~{qN!BrNcwL{PPd9Sc^6e=&1{=XL z^*OGD0SMq&2HDnVtr-HA>W;TZg`k?=<$o5aL~Sq2Xpt1JFWhUIds&tjgWBmMIYQZ& zC3`A5e;Ii96&1Y#OXVyYeMK&*Q+9>UsC}a;vvfwy(%hoyK5m+44T77Y2U-`<@t~4* z;)?H-a%@Y0E-+WKt1{HtGXm@-3kpWjq^mHWnsX&K`UP&V8hCRh+L^f}4XDklti2WpV0afw@^+kj)9$r!kA@ z?60fn*nQUl(e5a3oV^Gr&$X2S2CAUp zwP~jcGO(HMs@S%CD8L58rWurJ!(=ApoVGzt8@U~qRtg*|7}A7mvX=G^09CT_UE;K$>lr5K7TL51Ewp z#C3$6)dq+P);37Z#Pvrg6RuK&zrkn}ouEa3Lkz!DgZBRI8sPmc>fn5#ChKH3utV?| z7NnZ#-@jecs!X`?3b)hPp@#Xf=2?;bs<=-#@lt{}>$(594s5ix>I=K`4mO}g^xRp{ z2N$(aZN}o|0ZU3=AzImct+le#soGQ5qsogv>Hbq}!*j{`8Egtc*PppI#MO~S&s-DX zVdTm)*RIYHtw8bN66IfLl=@NMe_dOHr`Y%}EI4z~KXLW2J#yTW8X_7p@iH3d8oo zHP|h1atV`limDf)@~Skt5Spu^Tv}9!wLFcU7P=1i3Wc?5lKBPu_6~NO0h~dDt7+Uz z*i-s_MCV?*!WVW$@_OZ3t;6v)uZ!}DXDBw~od9<9nT>6wwHdZJ-I_|-uK=juXwNIx1i2RI3JZU1sNv-L+I5f1+gJv& z(@*sCYuC={)0^WBK`X2go%xsEglj4`lW>h=*ScilF5$D@rEu;N-ahEk1mtJS3eJ!e z&;C&EUF=yMSQLB20I*DAU;|fqv zAHX>Nyc(bNen80>vA^VFXZ{H0i$C)8>6W+Fi1o;Uo?;=?ft$#u#=cGi>H}wLa`t4c zDUT?pm?_M}^wE2UYP;x#v^vz+J6q}d>RA70Yzb?W!lwSM2q9~9uG4sk;(LeS7> zTpH0W?VYZN(l=l)tdD3CfBZ`S$o9RVfL^_@T)>Z8`4;(j;yTj9x46ePloH;#R(Gk4 zRLn;?8uJcXmIqzv(|54KgUiKtV0C9uXpw7AXf`cHt}|<1DF33!whO`i023`VEZ4U1 z6531ztzefBMQZxe5YfE+nljo6eo*Y5GpA3V9&8-#H2%kQF;-FhAS@`NyjPRjOjLRR zLdT(E3}O0mw{}j&QlgT`L&@J!~US)zk3o@a}(v2!lBg2O^h~NrVVbQ zwxK=!>LwZ*_EIT#5vH7|N{!q_6J^&>8tX0+ou3Va>g^pJbQkq;E$E56@G2h!pO&oo z)BM$I2Q=PPp^T`ioX(^sc=|>x1m&>0hhSUPx|m#YmGvr(FC#(>`)O?%(ZFakpd#&D z=Lt^Lw$kk~VrTV@@Quy~EKmhD2fxTmw|@!?M_#qZXfjec+HDkFU^QOG166%S(H^3H z*<=T1h;TS(*9gKXwTGx|SVt>8#1wGto@MbUO$*D4=5R}WrmV;|d{3RqiI9r2sDMp@ z*~gw0=cXFlh-p_R(8_Y6vS(n#t0MK>y8_hCr+?ODgL;I1E+<;I@Exb^v6ED#kH!m* zHd#mTMi|S{10iqkJM;>8s~zUREqJ((DW!Kn6bLE;F;#I;t(06|R5z|{%9+@`U+O4} z(^#5SUX&Mw^O*7?>gPQAqPz$%Qya#~YL|(c$+G$_-7GJfR7^#l{GV`Hh?xhhH5O`ZFSuY#r3$}7dDRUBX?>=Apo^b*Ys zduW80XlktR8e2rk#9X1BULv}}DJTwc8!Z2loio69%o@CUdy6Eu{l>9Y7O-!3 zzMOCidvH~%;3FE!!`_TSW(8T~Q)3SYPZ-{33i z7=L>HVV3T6-B)xg*A0p2Ye~t!t5EC8qH3L1Cfr7-h`nTSl4XR87Na2ryeJC?@;~)# zq{WrRxpH;?Ev`rJ?NL9P;3wv#Kkuh&{10K0)PTXdehCgf9MsYX^vNt3GqN~bTfUwT z;~+G_0R`;qY<=-+37)T|UNz3!qUCa$t-a^s2p7U9AF|Fs_~;|1W_~O9gW0bq9>y;Y zW7mT@>zBFJg3g+qy74DVbQ7(pw$MN4%JmB*_aJN)sg-}Aud0apA^Gd@flatNX+lr% zU)uXsqqzs(^Pw7yKB?zO-B;ulLPb?Xow!niv;|Zb%eJWI#XdN`)EIV)(>AmM?$ukp zHBigps-8&ZA*cS%7E`*dk5*_cjjSr#2R1_fcJSehG7Z#0dYLdaNh^~E5s^7J)tzou z6+>VrX7U&7Iq0UpcviMI>`QfBcq;C18@ z00c3Cq8e0I0|Lbuk9}#cG!_m0GL|i+enYnc#d*-BowdXXud$b~mBHmZyu6sKZLzjH z1*uW=Ns!2_bonAL!I1&oOTKr)KHJt`{gOgzi%+mU<<`aqG=u!>h+qg~?dxD0N};KB zun>RAIamjcz}eKN^*}yIX~uabLVi7Bsnn{nYW`crU- zsHwbaPMt%9Kempv5D}F=4b;nIZWU8}CJ$$K#VO3pVaDoNKJv+YHE`l;hCz=o0`e7kioMxJEWT&4j>9&DP z2qL)RHSP6^IZmaT*;KFiH7ZU@d6anQt|PC3YqUK=RH(7uo2M;LJ$;So+B6?^2gpkj zt_)^0GnhwsU>aIdeuQ{X4%|ILH71&W!BG|hHCnyk2)2=kR@9vo*jNlz`nIOUjYVyx zVQbpg81&MaE;SZMYyFeLObs?sZsZPLEOCx(j2`ER-Y!DaDYSk=MbM)rVmQL&1V@Th z<<=i!Mcxds=*M)$L?-^H|KsF{clm>iA0q3!Qr5x1Zn`&I>mC>KBiMEEiGgORkjnFukygHbZ;P>%Np!CwCk zi??(QW7i@S&%+m68W*QA0i~-sM{^=H*-@fyoiAfG+B8Hx-xpfB`b8GTfIjA7YB15zulVq^rSnYrYSrjwt?Ii5`m}Y# zmxHW}Q+rcbv{=jmqM}7&`B)&2De}*>hiHaRCtTDqRHeCyP_Fz&U7CxLO-`N1jIxnK zU<)1RzUE50BWqJ~l!NP}ZU zzo@#=dR>|uo}O`fU9&L~HM+hw^eNzK)U}^7QfchYFg|L1s?$?LET%7!;$y|&z*bQJ z0wi#Fuzgr3~Lk>B| ziQZ7Kr^JD>Eu=+pBEomMGpM4~Y4ZyS$0e0`mSJCPE`_A)bR$mGY}6eY^1sz_LEk-W z2O$n=yN$XEcAPr0TAJ9_l;8~X3Qgm|wSy+ai>l=ZL~7GMTwU5ioAz<)bXprPyg5p5 zyr>Rt=W4u|pp@xC$qAwZQuLzuR{Tr}?UqWB5gu5oe2ARd5ffeH)dUG9iyzePtwqfmZBG^O znz+wLo33cS$jg<#vjdFS-bcW+`t6}`lL#=j)@s(=?;&vx4KazYyq7gZbLJz)ta&(| zJqUkVU~8TKlBgWN8-9CW@3cJ)c`yxG`+z1Euk&FT6KraokQXF(9ljo@hfXq>lZRUT ze&Fm@r)hYY{kGHQBvHd{2448zai`;HbSX)+Y@NxuSR&VIKC73{H|9CrOVzV7M;!{& zRW{Km7Mo)G71jKsJ{Rl_0p8;EE|vPX6YU^tZEGhIoN97W#K|#wk$Za)oUY&<{m-9( zM_DJ_0CKRk13p^3T=7#IwYe-;g~$>?TU@U?Qx3231S4iWur3$Y?u z3`T`3xx(5`>+mppS@qh#!o&6ic`V-cnk}@ay$JU#h5iE7VE!JVt<37GUo|px5Id^5 z;37Qh=2%b#AD&tPJ~}ib5LSx&s3#B8?;XIJWsqMogzX<`WU`2LYjsCL1CB64s+TA2 zNrqH=^a%Zt42igs8+mrb?$eDLbrk-sn?FEC>sUiruIB4FHDIKg0;f(4Rs^L!rnUm1 z!0CCZi5ZsY(e=)(PxQl3ms`cDLl*VuDjF$%3G_)< zaS4{&!@7x9F797~=2+cZQBF6sk9fA-L=*2}U0E9IqAMSufPuiQcIirq-9;_e%14%uzp-Y-eD18vos%s#eqtoLF+ zD&Ya@6$Jf2<;nC@KM--KYWjia!I9YTu0r!;vUqEH z%rSpRcv8YJ9T0UT>0^-#*~Wc<2#TszicuD;J=T02{p!uqA!62EXU1sjZERKvCTnt$ zZ3;%YCkDkeH#d-{iquix(zpRoR`^^2dg0x{NDBvuin3RI?Hx*otMtPF=+i!<+9{%^ zl6Z}>Qy}U;pd%@wmf;7=Pr>vKBAQ(^g^0r>DG0;x@JFaD{#u zESlF{;srvMTJa#emMZdkiZ>8f-pg=Z=wG}+)LUYu2h^Xi1^`CO7 z|0y?zHVpyYA5N!+h$=F!vPO)&)jBTp?+_6bw*3NwK0$ELLYT8S%->Y=^Jmd2+5{rb_+fj zm+}7LppMkFM;H#SQ(tEDyp=FB;?X5&Hp;o48o`WFpHRxyI0hXqD%Jd~qD~UCxc`%!wBAgMwT4$= zT98tJ@`@TtKMjY7yO27J5aVD1a%hC`fo%K72+++4+B{N(LThtnr1+#l_4UjIYs#() z_zC6|<3_x~S))X)^gHYD(K^z}&@S?M+5?MI6AvBgZ@B3p5R7;V?(<6F2-?5)F^kpEne+*Zi4{+NIoSZ;kp(o2_)f zt06lCW0tvxR_qB!oU!)D@$v0;hP&!#D3%y`BkfWWG;^`X6F{1*eY6lZb&6ZLVb7jq z_)8sx?7E9ZV3tcs4(82RSJ?`m2e-_NuL0D6M$d;fjuyRemZyvn+k>OafD1II1@VyU zfz86U=dTX*#Hz;+PUK7FT4D=_BDy(7cq)YhsbGwls+_(?; z*#&fO0(kg&R4r8m@GZMkYy-<_N-DVN`n~CPf2lRW@PLr2SN4`o_Yr3fA)x0&&w=rux2;uHw z`ULHzl1aGVfu^JjU*Ezw zZ9v&$QJbw64$?|+^*Vi*E_{@pM;SAH=vF$!{Cn}_lOfvp*3nC4;TjJ%whvat(N`3f zEqrQK#({ZBO%K3aFwnjPL!sxk1NA7S&k_}buJP^Q;wAF6J#&6Z<^lQ)cyH4>;=UTW zck9arHUrgXiMUF&>}9GK{Er3<+(2NZ`{13p1HWQw^bY9L?%sh8^7l>l@Au#?`9I6D z1{KW`4ZVBXzb{0eikrTAh)lDAhF9pb*&@XE=NP>S*ODsiV|?&VgGkVR=nhK;Ip3c9 zR7r>IbinzLHb^lYxp}${#!`z+;ZrHXULcj>ssVhk4wZg1E)yeoj>|$k!bT+(+R0Q9 zZO3=tAMM}&Wl(G7$LQq`U(=^oWQi)i1MRu`m9%2-R@PQMSFbGL20!ydv#?m+(V{Hi z$C*>wr!s%zx@XDwVA99mrhKOtGh_>|N)wywU93@3xgA2wC^Q=?-G>c;l$@Txg8mQNOu3l>CF1%mqpGr=R9RC*(kX z&J{I%=VOO5K`UC~<<=g)%o@>@{N_P{1=Y;!6OMuP=3$t;q(w6Y0@u#-026#(B8nZu_q(-Cq_zvE$AVPg8X11YIKZmD*q>tb;%(I)FSX+B)R?QT(#(A zO1aJ|gS8CFdWAYzJ^96Whl~rLI2%ee7l_e{Z6GaOAUYvVnr(py5Q*y`7Vrg%ja0!3 zsCS~CRwykbj9b(>YZ+WKN^}D_>055q_U*$~F|X;yCkPFnGO999Am7+m&*AKuUo`g? zJ8yBvjoH)j1+JLjN8yRCgMN$<)>#WhT$L_vjIXRCM!u{93>{{2U^-cA_%e&`E`(G} z)M^nx^&O2~BpR2!?}oF(W-}^Jx9Kv|CEB$}oPbG8`eMvEBK9s8mHY&a&*nQ&e{iZV#F zQ9dd~r%6m~+H-0FET1*@8KN1SCEVpYe@8EyslR~U;zv{UM;OoJM_8OSY9O3Km=4`n z)Uq^vIdBvv63fLP<(4=3tq^NFG`NGcgl0!WNv3I4&7J{jj|VR~q^N!P#_W$j{8;ZI zfb+q}cznz}9Aip(s@`f!?kmM$gE=R4CC~+|%=}g2IDB+D-s1GW~!*O8c{P_DcZ= zXyN3vM*P{X%%6<8iROR1m~lJCd`cSzBT?92Iud;kP^zAgllaRzyc}fxy*eJM6a7dX zo;{ENsXgA)t8wTb4z`zJoZm;eLx7r2*HcOA|%>-rB}Z8g@W7O<`UWw-`ppq6csK@FoSI(N=Vl@Idf0VsZqwA{pXrwkqJr0^U`>)p z{fM^$EkIbFx{h9L0HltOBA<<7a=C9t;I^Ls`?EN;7k#x+EW*)8gH2*V;|3S?`up-& zKE9@psjoK0^$w&2>LMdz z-{w5~Mzk_O#A~`u#8jC0D~~v>y}IRhy?wT>RTt!ZvQ1oobKsmo--B~U2+?KRu{T0i zGn5~|-~B}2|DbXAw|)>EOV2rJbWj0-$Q>d@$=yj`><|^8u-dglv~wGG zSTjY<1sm9&j621)vQGwZqpAI{kKmfW>M)#s*$EgOqr#nH1MKI%_)!cke|)Gut?q*} zP2t+v*LteB3v}!PP2C0alauuCE|{Mnq+t#u*e0|gN97FaThHdKZT*%vHmXv>8)GqRI8r!m{u+t!ATKoe2~bt5db`HL*HNt{v?DDnBSZPWY*B5lcHK_!vx4LuFmB3vxqPp zrnWx|3&Igx`dLhfYkBTvk!_}?`+-hYZOE@<@ETUMk55I^>YUIQ37Q%Os?oBXz#8o0 z91dhXB@(L^_`fcSG447RlkwI))h)A7q?XoQ7axI6@nlDOehP^C2}PY2QBa*uIgRb8 z7A-psvzIdT>uKTT=}-Vlk73}xGzP*ufbDlGJPih?HPt%8XGEfM={wqV1_NkH z4Sx|Gl&9M$>lc7|G#P(|0(Llc`c-_KsJ1L9vP}i{^NmNVleM;V*yH|;?_X>BEQod! z25F*QCp==cG&S4-5$yVDL(Ra@nQ-2EN^gG^9Xw(-;-u)J{h-w1WTxI{MWwCRY zwRP0A@~mb;Q^$hPRPcYA+B#5c%7TZzsgXr6AVvg0bWdw4Gm}*-P+;6wKcUlSvGFdY z!n5LI*k<)S2QJ317Anp7PozjLN?Ee~LGVnOlYJcEDG|s5gV_sMY$p2Y0#;xLs`8r{Y*Yim(?HY5F`b{N z^J&R%qA|9!Q@;V__S5#?aU2c)^PHehD80tN?LGPgn@-Qa9ON_R(QY_(4{OgUlFfi zM3MammiiHT^#>M;LllKv6^C$t>hG(fs`wTvu|!MySap3)#cMe7gl=@=pV)2TSl~|) zC~Xz&pKn&6>wkiN>>dzeedsmM`vw@m*AmJrFA!+ zReN#Xt99Pzjnnhi;Jo4qdEOG$k|#9+tYAfgo&2+0Xl1lZ-8#AfrQTLR6`^R3)zn^U zCt2)gKH>;|t6x8UTeO=ofI-3R7fisiZ-FQLp1!>$s+aF`1zR(7WndHhAst$rR?+QS zBD{7}u6GIQwedwiG*p`tKH>xfRo7snRri=$+}7CRF1N)fXaczqZXU`a;}G86Dndp>+yl$YQjY3*0eo>ZlhtFu2BfX`Vd6TEur zIh*34tw$)wD?KE~JL1b~-+Cfj0bKgNU%pF{^?LD8d*4P{_Pug0;qpY6E96Na`zOc5CRTUwPXzV>ql+WL^>>d>A9doYT6MqHdS~4QK12icp#c71vP2&0|4Hg z&OQ*e6S|c_w+A-1&s)nj@8``Azg0&B4uqgJRGYi^($*17gddk|i<0?Asp=tYGd=Rb zeB_byL($xCcQDum^vR!jZU0zHLMYn;KEX>6Y_mRoC^E2yZa>84x0WhDLbr~E=k$1l zozZ|^KNel8jS{HcSWSm|D-DiK@hE}%En3h~Rwn-^!WGdy>pT%P(mI+|;|a5Z8|GtG2h?ag4bsXa9P@RS&ipMZM_zE$CdAEl znsrN7r*2%wP1FGtijUU@6M#qYU>t97gjrO#imLwuVY?%W+x$=~w-jr3&fkSP&Xz_U z4^f9LRbL1PIpGq~KiIRrr0f5P>WIB;c#6&H88v+>CV5XgQM{(ozD56FD!Sg{w2Shd zicIBv2qireDZqm7pW!?zfL#9-ap^aYqha1z(O#h=svoCMz}=YlXpxKG>ZYsqE6!!AtBK@S*(*`yB4PzJktr82$DNo1dWauSIB0 z_jkf!PwaoX@GMg6!Ua6^F8oMCUyB~~l90=eUP)%e>x0qWTULj9jVaEFQMSQvHS9Nf z^cpf@7P-Cww>OYG|^g78zcX(h;IyAGdm`<{8n53y7ZcC3UyEggY1vvg~3_8vaRzj6)#=Eu6)5EHAqTb#Z>Fks~8~xOkYa4>q?B zS7Wub^s$h0lg*C@o4bXpAvwR6mlqAneYc!VUh<;CSDSofkP=viHv7nt%H`MOT~T&r zYubu(o?&iIK}A{Kpv2{p^p!#2bHaV)0Pt7jD{DD_`X@Sim5%z#p-^Mb=l!xzPS9vNw(jDpr-f zov&U&j=yPIRe8kl1-0;(yPEX6j3iH;M3}H?14)DMD4Cn@;LkvdRb=CnXicQxtvG{% ztI2q!?Qe9whOA1TR+IS<>Sk7#9VY`+Xb>f1~e9X)J3#%nQYbNI>TAA){v1t z-qU!0g2Mysf*!|l*->NcZl2=`QjFP4H`)1 zpemc~ggk#0wg`=C*WmoYALN&M{(Lv&KTmCgR&#z+ z9$8A!)Y`In#hvGHI>i?v;957AVPfe8$169~Bsy1H_Nq}6S@YfP(uy_sWjR!2ndYII z#!enxN zu&kzBxgpmBpWXWW!F>TlGM8m`6q>5LM{NJA;+=R&@ zXh2>ykbSYbdNh=&kj8##2%7l~8N#J+g*At;>sfIxGwftMPQuOilgzKw{72LR5mxxSk8P& zx_vi=6OE>_8&ou1o5`w%O*D}oM9Z4V&QPf2H_r8GYOW%VQ4BZ6Raeq~t^kneDQu466W~7E_lPko42^NsOFO zwh8#A{7>wXCKks$@`{yfs;n;)ZB(_Tv>0a7)|T>Xzt+F-dA6fsI1(FqZG7+8+Az7mKG)V7RRikU@o};-l$T$} zN&l*IenguaK8Q*=`X8;$_IRkcn{SH)>_Vu1ysS{x+ZoI>?s~CR8KT^(yQo{doDSvT zZ}D=V()nsm(*!xuptxP4A6m)AK^L|GTvo3hU>`Ix-0cT6b+9%Qn~1td)ToT=Zie}< zT&Rrtk=C{bR={CbYdO&U_P4sJl#ltC8VK848K|__O^ZyjR<)Jiqn0!YU{al$t2rA8mpct)0F2Q(TYUrk9EE`QHD1f@ErAdU#t|iLZRNmDQC& zlD4!3DU79uZP9ETwMml8=X{dAI50UAO~+6n;8`ant356m4Vqy-*o;A~A!cd^Uq|A}$lrN7CL3#_mCF1-kC zQdpTarH;Kj#F88}I^*FmQi z^ZH@J!SLt|^afy~45`-u*z8Y0Mr_mZhe>+IWI!i76gk3j0f&DuR_9hW6TVVdh*KqM z)?U_B9=@Rg?d2rr7h5p6-{?krnV`%YOo1K1IOfuf4zioqo6Q&|;(A#-mwN~Oh%v{r z?4J5$>j0#kLgC4>fwJ*i8k#KqK!@fe%e(%AHlePg#VU>DzwG$R>j=M9nDlp))u2!R zwj=hDI`mgZtd+%rigKR};Y6a=MLuqcIJxoM@e9P|vra z{k^0Qw6?#a4rTov61_n|aIoGRQp`X1=xuL#+}C{-s?KXn$K9Zp5n%GwkhII31Ul|s7cm=YrL3ZPuX~>DLZ24X5iW!e$ayg8``$6gh>(UR* zayKqglhXTvSMMJ}?fc8dKDCws*UX1)9JIl{Vex6@V*0#4w%d4m*F_-nQ)DG2ZadXY!GiRq*(vgx@@^aTA1K?ij$$CVzg~2EpbSxxwo$o3 z;P9NO@gU&*@o%X6AQ`6YSVWdVSPQY<^wS{uiSorXN**lhD2Er)^ucn8^7b~B9fH+x z@iS^NM1I6#+z=V!U*Qt~=e3WrmOCs_&*k4)JH(!4_62&rP_r)&hf_lYk+s?>3VEFc1NvuES)r z3N03)QMZa%)-?csti2FUD5TB9z(DSzOT%PO=Pwr`=`J-ME~~(pxa)8^z}bhBZqtF` zkSso?hj=JE4wCN(Sw&fLkeZE<@rG#17$Iv`sdcbqT6gm~xK8K!ruz}qa)XYHkjIpx zO3wU|vXlW{L>7*czClMm;RBp&wiG6{Y;Ca1s2!k=Rc&7S0jlOo^fa9tB|ULmb#Igm zsPNGS795~YKNk>Siae%!9efl_)kXs}YlCUjXiUM64zyylJlE~~*)k4Y0N@3Hv)x;f zhx*gUY!(EK9=(z zdR%OHHVDEY`*2Y1d%9x-wQvbt94o7P|C@)X-Yg=3D3YY`3QD(b8G*CEgPha#wmC5!hzqfx2 znt+d)3H}DuJL)#Ts>S33vM!E>_+`G05f8ls@&_*!tVu@~r8{FyQieNf^hz=qwxi-N|>DsAdW-Ab;upf+evieuTXL|N3d4^y6KzQ<10iZ6`EFph*D1U?9{IwfW51ux@w zD7@4d%VLG*x&JTxI5Ep+3)MU%k)>uiw9+a9UTLw(T#;uh#X0-&) z@v2GD4uX-NM?lPxgLQ@hwpMB@%9|+tl*y~<-bC3_Nv%V5Cdq?1T6!=^HY>Mj2c#hA zTa2(GiF5IKdQ&0HP#>q0?`}UE-B6A*Ye9fB-0VLM=(l9xHTt zs;pJ+N5zPkZi+E0%N018=d?wkveTf`Meu~F(;&0dq|4L5%a*2sX|hXrO#`fU+^6BM zcFlG;b`7;%X?^qw;1ku*XZq-y;3cd8whuQ>QTlWU<#22~UG`1jEFB9;V{34#}l}6y@Ag^3?XcyWzL-wgNip#*mJi8HA zS37Z;G#@qdAI_g*Mpf<2m&^Vv*jEtKzC!U|e?r8kKM2aCvfG5RyY zq(7sR^{0Dx{pr;oPh;(xTl81IkM(EGVOnzVS9n;QMrtn+8?;CCHayHuh1!ezcJ1M{ zS9|y!(H=EV#~RZeY(wA@&CctfBVP6n_}M#9)82t#?f||=4Aq~}W3@WGro?c|OY}sq z5n7^ODiV>`Pw!C8G`yOfe#Kv7?cmAUBVv~Ji1wJTJ-wD_55LthbUp)0>#c97)GXOT z`J<5HXUW>i+?F(EmaJ)9zO)dNip3gh&Q&c-Y27RcJuT?*ELmSXsmSF1zIwkR)tW7< z8P~%l0^c2c!h2m##hh-lrPZM9E~I;za)Gkr1*K-maB$XJvSbU_fC_ry%Jff`?9*st zbM#oTb%RB*9W=OH8?B|qA&q?`^H~NIHy-Mz-g?pb-jtOsYx+Nu7<>Ig6RNU@w?cJi z88D{@3vHjV*)i5TEDW+`HP`C)Qk8O^WlL#L`Yu>D7wU%l7Me6y_EyXm`hBh(RXOB2 z&*zs)#F|!JaX^hPdRb_@s4cFDuv~;*^uT@($ZdB3E<|qMQpEq@-M_Mb7#FSS4(AAZ8afm(MDijt!tjtx9gdxyWVQF+2)x;JYg92p* z`r8h-ve?x%gXn+>e;EHttIV_>Z^xv<0)B;I?-^@p9gtaQFwSvh7^=9L-8z8178U#P zRuHg#+XGoS-Iz5TO<=>dwZ~ZAo8{oZ7mm7P3JtanV1{vflbch!!iEQJX_i#>^91t^ z?Eie#+Cg1D6+!<{3%Ye9(d?`ij?p0R5^Fw$`EHkJan|@04|I}!l*eY?HhvVF@yg9O z=LrfW<~egMv3aeSU3aiOz%B+RJYyQWmj>mH*sp-e;*k_N)g$d5 zr&u4+nop!p`WuW#Q`?>b(T~k+9bnL=Bb%MOfv3a$l)?{8HQvJyqy&1+dcZFBr0Am^ zP^zs@Xqb}qHy{A*cRhBX=%M))_c5G}jXY$`hOsfOIlfXRX*Sa*-hIT4-o^9}MnAag zFVr2cbk4FfQUD(W%jTJ$Xw+u8ReBr?N_V zZPw_qDJ@KN-(mT?C4u2mZ)80Om|={oyIaWWhBh=;@j9H+4%@zk) z_8n+np%lXhsG?@_e1)?yhGnLU4R=8F{A&5V+?l8VTP$)$zlT(UWeg6c^EJeFKzqPx zW7(YJ#Ahio;@5^1%BQW58g!uxv(C(S%(pV)~OYxjvBUG_qw(4#BTi^u;n+t$%-f;;G_L4cMgu@;kHgc&dwfzaOB)w>D$2 z7z@i7=kC&*f*|uvRq2pmzH1K}q4(6NA#@btLwGVYGw;AbFZ*{P&tGCpJ+c)Ji91Hic)tkxD31cwE;$msTsW*YTRzcp3 z$-GdwLFRV=iucsQK>S7JXU}kKk%ADSIB^xL$$FX_z5)JxM8g$i|wQD0d)WZw+5c5 z8!~9h3fahG*=k_+iD|%Wff|ifY0Pq{4RLXK1-Oqkhskjzbl2r~QrnfXe(fIy@uq*2 z-KMOJ&4_{)#_Hw1SvaIQC4vMSz^Q|$!d0eMv~Hzr-gY3gjp{ONRVGU*<1X%cltfHY zw8QKl@*OHHvU%gRWP?*TqmS(K>AyYybQ{%MC2M$`fw^@4(hs0hG*7mSHr{7J8cs|! zmWr9WCd^`7!+xyRf24B^^O<8P2XiU@GJ`n=>-5TH)v-}IGtE$KD|4q&&V2cck~5X& zTI8q7k#ER%fo!g1enY($NUIVsj~*<*`D@Bnnr4Mwu;EtPYL(%NyMb<5q10XcHML(T zD=Xu_rjZL}&2(PbcCC|-#cTU5Fo5UNs;PJGb9d5Q)l(O^E2&->r%%aRF5X%*qU+x* z0}lXG?A~k^;>|AYxB|0_ysSvDxR(y#6P;ieJlG;@H!n!YLb>^Fi|OVn8K88(NzSWf zy@bcej#k^N)%50@sV-XcX${!p6p-O$V?Z6kbk97-Opv!po=$j zE?Dz2;-nQ#3sWEBGzNWxpSU#k#G`)Gh{mH-nIHsI&1hTA013n?={Nf7bJjJ(0 zTqc&?yhUFy`AbaJsfFsWx76he`AP4LY1IIaIG;2Z6O%CLVX(aXfqRT?_n#SO!X=)? z!RQ_1W2_COiFyy)JEC*ccfiF7u%{*dE_~EC>$w46EMA>9rG=2;dsm<6G^s^KaZ;z8 z2W`nbn#=)G9n@*iG9YjMxni2u47)va3Qj*jAi7#i`k3A3e=Y^>Bn`lTIt3(Bv3z|Pk*kH zzCQ8uF%242W`h)%GDr9rY?JYeJl4zbPPO#8Y*}cFFCi3q?(mY_?DYgnzNv+LbD{MM zD3a`_;sv&0Oiha&`e~Hd)|KY2$7#%cy0>1|aYb&e)1FjugAA%GwR^=0E;=s7xTG$` z2*S?y3M=5cqcIYV{lQqmXygW2U5+OVWyL%=G?`1c)i+NUfVO%^%pnF&L$rWPri9EbRh2bb|*{qqu zRM`STvT_*3Z@~e;YlH>cf+N2(v}TL+Rsx67?k%#4XKd$K+?7i*A1kJK>SwFz0luU& z3zB5rnhQ)Ymd)fxVqQWF9?&|KP4M79{`@Btivj;3tQ_YztIMeiAcr|McAevMuW7aBEVY1NAUrWFAOdM%Cm`cUP9Cv`7OI)%6 zp^w5I<;7J-Nsubo#^|P+9$yz~mNF)bB^O@|s^M^w;g-3RhjCX~2v8ZX1S|sp*^Frw zF=@~6%N*xs+y!Q7S}69mc^v8iGWH7WE(ciquYQ>aDv|Atjt@o}99A_x$!disx$wq( zhRj=Kt#m7D(HI&oSs%HKIo&+XX9w3rT%u@%B}xy=WwF1EKI-f3^-*J}XVHM3xTgaW zGxu?VgE{ji{-*X|9^;9+=(WzV{J@>w$C4kUaV9<5DTEE~pwh9(r!~G_xDEI@oT%mq8M(T@7&Tq=DAuHY;#53*Q*$e2Z+Eh40dQxQ`{^ z+5Em-aREwyNyV*WR_2v=$S_bdZ#sLJi4v_ygIRnnPzSxF?_IFFk<2zYFN&A>;e<$M_W^7Ks zpf1v=FVyJGW_TDgS3pmz1-i0!!*1Ti=eT2&>b4ln3NILTZ&w*K6aWLCm(i}85^MO= zRvlkst?_>PXE@(VG{CuU0xC>Eg?Y62dz{I915k1m08!Z0e7_PfM)gjuz#b>T@We)5 zH)i!l=Z(9RsOo8V;lwYy9bRKIT2wb??ciUT@1QGqiMBN>iYO?pe&hUek0U9{-Ix^! z9ZOU#oE_r*eHZ$acA#3@WwZL@@fijyE?UTUb2|)9sh(e18iHkSnCz}6EGQ4I>mSAJnLO@eH zm5Zti@`xAMGe+JvX0Ap@%;#cZ;mBd*YI8skX)swGB^VdOB``5xeGJpoTE+wCP3ebj zIhrpXdgq*Z&tMHNFgyiSG#So8wPP?v<{7i@GXQqMtn+DXfnz9Sq4P*EnSU`IdK{H{ zP>*z$f9`!ZaY5vNb<+(!gN`gJ#F$kZKjY1X2oK|rF5qTmdcFr!9L!NdYbd!!P({x-h{26vK!Tco7>R1olu3K#6u?a)X zr!xOCa4+G+6-{X#&AF>)w*a+2^bQs`+`#YR6Kl?cQ_jrShKjkFH_K$^*5jWAnfJiV2vU(HX{L;s?>U-Sw_r=^b^snwAGlb$m8|6O$EU)|CMNdo@96j)NiIu%yE6hoiuQsM~1)n&ZYYu^H(~hB2!(y2-l-NT3Zz;h@+VXx|}fV%mDtosJ{hWM{qd z2PnRmRlfj!`MEmqmvIASxd8@+`3i;~$-^HX%JD0>4<<&NG00{D-o!^fGiJU*{}TyfQ=;u+b~mL@)P~%Hj_85T;sBb^yTP{_SdnxE)3O0gpkoS}Rcu|cCza$YWlWzl z2lM$MvKnVU41LJ!o%Ww6;z(KE)_i|+}IWdCoy(?UZBn@w0b z2|muY8q{Golw>#!En+;umV7r$@Zl@_40wESAV7{wpZBp4ZH3&ihRHm`$JPZq+5ug9e4c^quLcubgcUOy8C{?9zx=5r7T;1Cs(R;eUk@cVoT z8XFMGo7?Q2sLS>_10vWC(%yGK*Qf--?fCV#lCRD2$}Qx7PAB%@>~Z%53fwEJMzqes z)`^_~>+&{2U1eymi1ll}p(#NIa0bkl6~` z5KNFm{z>f}Oo8n+&Tvnvx5v|)y|Qurif2#(n7|nbDCfeLJ>dWQh+2wMHE#;3U72x4 zU{B_?SD&E)`(%UChf=`+KkG!R_Q~WLpZth>{@)a9Es*Q1ncLI?I5XL|<<6xt`=xi) z&00E;1t%A)=Yr)OuW`>AfD$~bTPSWn)N;R{qAB}fpO^WJw(ghhl=x_RwO_7N7DdyS zKOuco6rKACrkPz&kjnumI#hbWG#OXoTO=D3tlvP7r3FO%?D&c z^&4|wy_uk${LSsp(h-)yDWqw5jIJHbBI7~Xxy*`RS!9E&L};Y@%%O1yWu!8@GktSV zwpV6vr#A;>)k^2`^gQb3Y>WpI0l*Ft=;ZpAB61;qUuep`u7G%=vZAs*lB~JVH10S? zTXSVZh2C(cihwlldkKf5YU8H#B3Fj^G(HA(&^4xXi}h2aZ6Jnf?DrIXNOn?^j?$-x zWN6vy(=ZXo+94|kHdOaz(}hE_t5PbG>K=wI>B3;@e^^$lvg(cwoEcbOY|Rpzm!RvN ztPy)g2|CxhoR|0IBpymC)NaMzW1Fasv*_o;vQ1#@C^Rzx8EkNvrU6CUj1GYR!D!um z`E$S#YI;OgZCo%CFYgW`?>Z2X5*A(c&0-ZkwD!Gt0|Ct2fNU1SymlonKyy+4>~G3AimOzXw&3wJ+41xMxoqw783qB^>`VfG3N>|7U7n$kp2R4mxQf`WoB3W~i~ z6gxIhVgm)#b%QPH(Z|FdHPP60?P9|gdyBE4G3s5>pi#lj_doZ7Nxt`epWhRgJ9qAs zGiT16IW@BTcxF%Hvxt+3$R^&j6SVR|c^c7PRhr{AcOMUY{VE0$e0>mPhg!0a zzkNj3M4g%q=0_Z4EIb&!nUgNyjTu#N4N+e%!@h`Oz2A1ezGP+iFTmPG;<5miomCtl zCb+KWRpjec#2j5z*3eXF2A_gsR~d&zXxo(AAuA@pCPsHUMwe^YTc%l`9|?zG6sWkPk)zcm^~CtYCUmBS$!(Psiv5Ul#0Rp zs+{BTW(H&6Ai4Gh;r6(fRKZj9>1=FU5HV~0rDycsK5R}MnN>j_Yq}Dv`#mD9Ni9R> zTGWeR<$gvIg`Ls6+x~9I7)w3R=&PqnKXZmXrmL*k1?}SzscHIPe}Epq#UMUojOiu> z_N45}4NgSlvZLtpqwn z$Nz?YklRkDRQZWb8nkTdtb)dI46y;L&#GgTu)z1kG@dHIwx;=K^_5%=Aw0?__!{Kh z8H2>dc%CC=pVhld?@Ljwze-nu@a@3Tb9%p2(6FoqdO)XHF{o8ZGq4p=-BrsJ6ZWB& z4-09TO!5Cp5zfp#hL6jAd!}6x#VOGrV}OTww$Z0?HN-q4Ok*nKW%6`^%IZ3MqrOTC z6H-gQ+KI0sN?~F{nu_-0j>&v(0-c=tQrQP;||kO*-DeOk{U5} zV7jkO=3g@zutCk9Lsib}Yk6dBfDRXCjWPUBAO0tWH5vgMX!v=+XvQO8AR>kHvAE|N zPJA|l{W_3q{~3t2yLvE$V~q-xWnkqPG1R?*-D&Lxl3I-SB~~J_@h`2ZfCr=3GI;6o zB(2ZXM$#}Fn|4{L*ocv)4>_tcZqBn}WdM{yRyQ6;326!|!t5tOXcv*yf%mkO{-DLN zze=Z{N#nhJF*{;TaKs$ss$;9+T-4X~ILOgDm=*zo zJV79aD!P6}X~AV&0w05{Y=S6~@lO-lwyViZ28^HY7&6$lfbq3^1eLj@_j8C}%Vr98 z>(^4fOR$ZcO3N?lo21@u$vl0Gzb{e{FED0x#N`1=DROM>ZJ=`NXp>ypm_7C{A9?&5j!TZYz{xUBXQ&?IA0E*Z12?G30hp{g!9gn)<1N4} zL8m2<2TtA4v92ixgsTKDE;Z4P!6J{sk4oauVge{~oS`}rVJcbo|JjDeE@FEl;tU31 z3(f?lR2YX>-fH^(vfi&ZqCoJtY8_n-djxk)x{`LLK$WaVOXlyK4{-|<2@*P;~YcAZ1kDdw6`JC4TI#n^SrV=+W3oU zQ}soCAqFsH9Knk0tL=v~Fsr3xq^PTU_X+(3<}WwR)m=W-l~pc{$!t=Kl6pFS>kH@8-=B2aV~^ zfNdS$S&^6z_fG(k3G5{Wu4(c$eJDKDT3^#wbMJSMw5PZacBnLI7K5YCfn68lLsYKV-){q4XvGN@pXOe z_MCv^U#&u>+oc%Tfy`6+Drdvk>P*#&!(L+FV4xwtFk0v0OC#z-g9o`LFV4y^a=M|f z-O~H|f50eetD`BHZg8J|bmxZNt8|0r;EfN{mm7NbfThif>44F?rJE*ZRetSkvF{txp5OFCs+_~t|CfqCz7eS8G+&#XsLHlUjX{j;IxeHI+xlwK99K%<-%H16 z{%!rNz-kB#sNTO}$of&8I%Hps-Xdn9mL^(_XPc{JQ`qnNanedXZU0?gIlSfx04EKE zL^~XcS2R~C&*k}yx7wkR)yj`M|Fl$(tmJ-EV7`EC@OGz`Qn@?&OlhwpExQAH7D0#Z z=snB%bFDUhy^W?eTIpiw_%eqH798MU<$vluU_UOiWKi)8halO|4YeoU+;%R=fB^_ zCAh;OGUV$09oH<<#&K*BkK-43_T}a3Yo|Us3~9{51uBLyl3wHIT?_Vu9BDpM(WXE1 z{DLB^~xp~ZS~r?gaey&;2joss6DLRCc@vyNut89bb-X6106AxYR}u#=3+vbBwY z_zJHfxN8Ps7LJI9x9j0#bKP5^bir{cDbREYHn+H2<+<`I(bflg-(D^IsF(~r=U-ZU zU+bq|HM(YQ<7qT^$L9O%s5e?=TAyVbj{lD19%;*;nT@bbKIv5a-O1wbvc6#v;@`a~ z@S)z%Ho&dk2lxt3( zA0cMX$&!M+FskyWKD}Qf6j&7yn*{(quL&gRC2OKO^(lXjc~=x!YA_Nk>rPr-KoE}K_a!dZ_$~;`#<`_VB*IHJ z{jtGxDkA-bJ|gWin3hZU(%jB7QunshD1Z0h0w{uUm(OO)vW0k+)e#3rJD>`D!YXu% z&Z=-F&j%SUpXl8xf5vN|j_H!=Skn>q6K;oR;KIEc-J{2NcZ`OHJpmKKgUUfwbqE-b zQVyd)50Sc;I4RwshelO>(*E>T_Uyyw8);I5QS%o4m*YQ%Xl~^TyQx4Jai`zpK~KfS zTlW?=6|IEn41PMtB}5n!?=vdv@)Hb$;CE)5lR&zsdQV$iDc@7&r;zpjR)RpRwzneD z>OZTf8kBpgL8}2-)l5WbKAP7Y-q!3dVjrQ)v6fXo2?y@}-|CnBKk9p_9fsRvMcTk1 zf%ZPtmu)a051}K9eL@jb2={g7!y--bzL+N{YM=^2YaR-*pEc%yUSjw`{t#UMX^5N? z?{1xqw|p*@hsZc>N>5%zLk8;&w3e;UsGg#qE2Wj8BZ@v;YF=ikRqyM$;5)WSG-P^W z7b-`WYnFU!yy>->)C@JGmkRZ>>TCHnMmVH|XhY&n+*QIpnV9}nc!vK9kZs<{?vaT$ zTlMvw`i*~wF$O*W>;sQ0apUPPtKR6k6saJXfE1siDz%k%P|PzpNoUQXhtKpb(i2;H z_YBsnIkx1Uhu;mh6q<+NLRI=u?>zmgT6-60hJzfiLV3JY8|eUBJe+|kJlh<0#zS=0 zbVsGy6RP$c?)fo2=r9qw5 zX%(Ac^Q_nq5NU*OH>QTK^rQUOrRzDbdB86G!s6%Z-w}p>eeIFf-D{!xrYC;s)GPQ1 z+BBgrui!!+`yvC`xeC~=NDH(HujPlwQ|SHQdQZ2ITz2Z?IK@em zn7KU-S(8%Fn}S}$#_QHbn)DiC;~g96hu8WrX>Dh^`&u6%<&PtuH?ZQe*+}i*=<5bH z4{@}CdsB^U&Nd&+4~Bln6vgu`)-nG@v^fgN-krkUHKGk~;LSB@1KoN9P}ql1!5e+d zn8ev^l=?Qpbe&f~T^q{MhRSL@W%4)L+OWUJ(KH_XZ+CgnoI2f*VMT#v2{lH>wE;2` z{6E|Y|M~JM-&ZX%hU1y9wRWSY(vG*FnYfbRg~^eY#{{qMmFEN%7;6& zyHH=-?_vh;k>s9=PW>*qwW3T^%~ivWF6I{6{!X^<;MwN0&Qj-{eu7T=`4z2yug@~{ zZu$joYbTTUF)vVd4TXQur%1MOmIEL3=XDKgrZMQSZ0C6c-rx<`WtKLup8OC3M+XLK z3?9^zM_F=%_J7j1Xf_HCo6)8W|2gR0Z1;1jwlRkAN4GPz7F_t@&^WCH4vBs=oQGQR z1~vGsuUh3?3rCwP3N$$H5k=N`?161;R+rMaU^p1TQ#1rWv9kqD`wUOd@2Ar7&-$*? zk2}fZi#}C4=|cbe0>jhY&B*daPZhtcz-pQg`KNK~uke7WLiVdXSwX{!^jDAT5GNVJmt#x1!kyvmgt2i6PI*p6?(>b)6januQao%Emy)s;juX+Z)d zN+ML6pgvciLz1W_wQXW~ED1ZEX)#NBl0350@^lm)dP|BruaU~i!4&Q&+@!assi&jZ7Px7ghEcqoAyRTuu1x~(i9dKm z%S#Hk##3Fr@Rq*hSmN}ey-sTHO{;}y>sMx&15_um@%cyD$^g-SgN!EFK7S1407tMp zZdr&kRz9&|rC{ffKyPKS zTRNXWo6Cw(wJub0v`LSR!wO6bw@wE;7U6I;sViugUFQUNrZ5MSf@R=>CJ7X25G{S5 z;1l&lmEspeP@uXZaIMh6w80=|NU=kxx|8s6_Qy+y%Z7|W7y!Qy8e-|?B+_+`1{eqM z$vf0UPs@pxb!Lyi`k8%sSD)eK+cj2OzVrOBw2!uYJfZ0LPfEd2>ftOrJaSW;NjlX5EvPpRW!`dmTul3YenPZu#l`e~%)l#6iCN%s@zva1M} z?#7X`8+M(PK{0OFy1%8rNqUNVZo>GaG^G>~eildrqzD_xpN;KIG6 z?K5emyKtA5&ZK?rK#++u={I+@6f=_~4>46b0$G3ucHsC2bjU+QNM=JQpq+@R4Fg|~0Opt3eBC*bKu;-wNdOapBorm58LLYpg!iqdQg zovtWuN&OOObtUm7;C?k`_7C~{GW^#}=ivhjm#KdoQmKz(o=zt`MGfh07s~e(5mL|_ zs^<-1I0Z=4H`r9h+iwbFJ712SO z^qihn5yPtv=%EpWBtTHzv7AB1Ny+S|LH`#9?69^p(O*=NcKt#t{6W1N+R<%)VU*4f zqbdQy=s0kqdN?Q!&nP)S_(_jrXnBC>UgmD{yCP+_l?nsI7-`l}8dg;dm8K=pm8#-| zG-n(wtp*` z>_@0%^`e1+qOw%G3uOd~fWGy$Z;r+yo<(D}-CG2s6{E&S{R|cglAEmLP}Y8#6u=MS zE5HWsBy1#XZe?#C+Xq^0J%8Bq>6;>y0&>unaKSRGrF3<%OecMLN~>!KAKzCU%i6@6 zlj}0Ze#2n$?4iMIF(1%HtthvKaFOcngKPYo8hT zv&pSK7(L(KuwQE2ux@%z59JTt3Wp z&0~3l$&Hk8oz;~HQ+l*eSE2#5g3-uh`V+8r#?g!^!fp7<(dhf{bx(WG&sw(#UK*MLLla6UKU<8bGK=o8&_h%_O6P|IdK zeYK!@bUd`Huo_13$JMl}o|r2c?oo^SqON~LvAz;O(^Pt6*LCP7V%Xb;O6%Cu&9du=_` z1TQg7G@9NA-*LNJexS7tL`x~!dR>p&J7?6tE- z(v(JGlr-cvSsRI(-l4bOz=1v|V#X7+*CHaTAL4%8feA04F`l=nUI@VYs~shV;K(lQ zL9;_dBWeC`bTmY`N^ZZ?tq@@@=V0du7>@FN_79hp9QC?2ATx=}b=%ibaj5ZZbrMV}m zOH<)5{fWdeO~q=dY=%Z7$v{up2;18fQa2F$Zp=C@Ya2zy3twvSZ{ zN7SRFX2Q>FFXBOzIPE9lrRra#-fEQ1*J)QXbn(6~bqy1vz5Z&BhyZ*w3gF$~2}>|; zvAMdV>QZi)s42BvOrp7HEOoz5ZJLV#(w@uoQ*)78Z%!D0irVLRQhQrzpQ-{K z$J6mB@s0D9GfV(GhweWC-V@h?tiLF>wQ%>Q??06YN+LAz6kDno%`6aHF`Uv{iy=~j z-Sn)rXjA^_*`9r)9dV}(b%!rB_y`T^_9)-S$F<%Z19;V;J9sb7mf_E{Gm-vJCy=m>h! z0VMHsO>&D93DTIFlo|(aFmovK%!^;j#QQ=kw=j`LcNFerLJXi6;}P7yqww}AT~j^j z0vT-088?H2HL$6Xv=Az#BPM@*20ia62Jtx`*9nu3{f-`X64mQ%sLqp4ZlK(*!yhHr zSF$THoRe$tsp_AKBLdefFZFQdgV_%;M>~tgeVXDsbvxhW9*3(R8!~x0l^C@FL*@=V zXs$6ogX7c0B_*C=VPi&>RRs{n)8S57Y8F87?FkvS=p0k8-+*j#UHVS!#0{Lme4$)De;h9=+55KH*fzSKLAU zARDrdps=o@Th;vs-XKnqTQv??1;HnCD{6F;h*}!hc-)FV?e8k8N)UWJ>?&NNhaBYX zh)V(ZHTJq*{S+i3YwQ4S0YcfakkGUDv%7LP7k#24=aF!VI33}RlLUh>h9U-3T3F=( z3hyR-LPv9_KHN>XyIlgq&Fz40T*O?o$}Q*9^KQZv z)-(W%1|ctd((oH6Wk^lNRQ!dN`&BDy>Bd;97427xf{Th=JpE~BcTpF~A0Bnb>2=LS zm3j!@ZZ}pr*z8v}uo*I(+?nFI?7GWSY`EeMz&vvzXM2R`TCIc9EA9?9YDH!CTn2I> z+gBcfijd)b62T4t?~UrE zXvnyOZq-PPMK0lf#cRX3r@35*aZ$WoLV~(S=iw9ucpCOkAPbsuZME+W<7_Uo)4s)c zlwX~3EzM>GB+BfSz55mYLUwh^lbIPU#!rE72*|{Vta{@s57{Am(Xu^ z+cVou9D~MEI+e?I|K0+4}kYWe% zSsu+CV6FFoqo%LHjcu?kxBAfJDOVGBOQtLv67Q7U|a)xAid|u?z%a<1S7M)$+ z`d|R~Ms;n&-2|D(m5#gVb8peca}*k7nm3lW!iuWez8J}ez;tIC&_}og-NNOe82NLe zRj6_b?kpFAt68M!X|zc}q7NHvZKdyRTGL1PmfsAMDX{u%Qmk$CiavC`5Afm011jnx z8kAr400^fB>2LpxNL!ZVyM#(uo8QLL z#DOBPOrujcHhNy?^(asK@S!xhFQ@f+RY0O}eExB}|;32rQySmZXA;PUp z$6zc`_C=aEM0ixZ0ZU8f_4i=v9I^-0#P2t}@4JPL4H4Cyoo#{aZ0F(uIRiH3afv?R zJE_eia!U|>q}xAHa)KDFD^I^C;M9M)k-Ue3-~1ttdJYwh!n;BmsZu6{x5niJlGZT` z7=kW6**^*434cXjfkT;|Rq)@>wNaSjP(sdX)1{%JVnX>%Z*bGG%dP;ihg~CF!qv0x zFt3(UQClrEQKXzNtuZCN@Sq0Dn+&HqYYd)LB|UuSs_U>n&#OwxaGUfC;gP11xCuUm z94({*br>cZv{=&}2*Lix+1PDGE^W)>F+FT1NdeA@V7{tT#puju_KJKy~Xi7A3Nn z|2_SPBI}cn#ECr7Q zUwxwsMUNEqTz-Na0;7RtFaSFRQlTQ3eonMtq^MNet{fl;Ug>W@P-)<%t)}3qyOq*b zvj}grsH4dVbbF+z<0|A@OXPO zbEu5OEuQyfIqt8$q;+A-T`=dPY#BmpM~T`M?XCclb6_SDiPd6red^UmiS(qN5aUWIvIB)p5N_3%8ML)5%?mr_BX@!OH4m0!bn(?yy;@)CN7E(%bBk8estF*o-&Lc7 z6U0EtW;S^ziLM=Q<4CoBQ_OgnU259{K3P+3U{0Lm9~ub;A&9r*BkrVqS*^$8{1E&> z3*W~MsnPM^3i;MmN_p0gP9~wdGYjZRlK8dbm(m)BL%V6C)RMIZe&+_9-fIn9z(dv) z`;sfv@IJh?wcxsJuN`R$g<{1PTtBN-R(wyTCW_0_@(*-lBA~I-L{5{$?;bPXBfQET z>ly6#m&SDAZ)5!pXrWBGM5R)259@S^f>J~~zZ-t7IU zGc*mPGT|b?JWk^mA~E~)3-s|D^fde-HJmJ}I*mhU6liMrkcLajBVWtN$>OQ5?BpFE zzV`K(Hw~C7zDU!@(|~EXee@eoY5d!KJgw$m@9~t)zhB1D1OB}~Zs~N9FI~7tucqTR z7vxEPsUlGdx<`vrA-hSfM3+)Ud+$1x-W93YV%P$*9)jhmIcqdK$tq{4X&SBsFjDD} zCcLXAjKOpx4S{E@XN!*!?KXe$G%uQ#FLq}|`aVr`b*%{sh7DM72pa*sqUjU}bKwgr zGeh{N-b3N*mWE!DAMN=k=A&SjKIOm*#OU<}_C_{tnhN_34v&$KI8yohfIYmMf8g&7 zy;|AhpLRl-i~0!i0b}3gcn@cJ|1Ysw)9quk2Is&Sy5ZyJ_BMGnzAg`fR#wo4E6q%y zEi=S`DlebIfH3{EeQe`T$(wL*%4+zxY6_aK+{7E4`1$Xs&P-9SQyxwt+$SJ8QO$A= zU?Dkv`gIg59pE1Gb?Lr(G3>{yuU(hu-Pj{$A0t{`IodT-gh=&t^n4~nRpk$oN4lul zXdkkxH->xUHFd@%5a2^PtKrcD>g1z%^06ZLj$%e-jB$M-O->gwSe_a(haY>+Z@DrOH;55QFQDuEAFbHYWTiX~i8Ut2r-C0=t z%2b}Zn#GvP?l8SU6vWmx)<-xWw9U^F!4$Q!QoRE`HiIBtcBZo5iYm3Izmy>Y1qTkx z6(~wImCA;KLU4SLA~G?r_q90n59&0KBC3vM)x%R|+g!@c z65Ay?gBH%iSvE;nZp{U=}j zex0ueom?n7mua{Jyn1#s@?He})pthAltm&Is=?B9ZZYUe=hF0XG44*k{bH%QMCeLM z0i~$=GO^S5#v>UqTPKAwgHwsIz~&iafg#g_A0FMHkITSIhc+hHF^mG$hR*G&urFsG;kM;j# z@W@-NLgYMtl$~`bXqAZdFj?y|Qwjat0u_Z}qQz=3F_sps647mL+{L7M#vCSBd-dgy zubsl=3?D0Z5t`=f0zXAbbk?L{NA1y`_QlkVi2fx~rGsI#ZnbDDt(rvnt8t}lF^M{? z!Py<;LOa($%aQauHD3$9YtaMhvlf^!@K>6)7NV5pb!g98@wfD2A^o%t*f#1JU0o-- zN&baYV?C(OiV+mQUObTY@1&?7#U9D|8h!dv7%K?j&_W9#U4-zD&H&%O4Gg#K)DCk>B|N&R+@gD#%@GkT^G|&8zEx3GJq~@ zgjO$bJ2lz_Q;X!L2rnguOXvF2^-VyZ)OJ*~3H7G*vsC#>tkp@?66o~LVr0Z*Ny{a` z@oZqz$qHPfIaKM~S3PpT{VVQ5s}YVGG3L!&gB?Rv-chO9hbC-h7GN%YzgfgNEigj= zfDLEe$d{(S?dj8I5oT}7Y2~IZo@FEICfGTxIG^nz;pn z|Ie4`)fT7}ns%YizhG7~FVLZ1fVI6Y(4W7EALNf$K#Q~N=0pRdLTKJrkofwg>EKqJ zi!qg8(vEBrC8U;{-IPdGw~1QK4;xY66QOIc9e+mrbWr`d_$kQ>GQtP+N6i#vB{YC5 zD_<&-oY-$nIh;ldw_!gb=JxSzVx~`Ez!%s6ma|DJoj$UHE-45k(W&=|Vs@lvM~dH$ z>v-g7n!6ne+8T@K`gVwVcXp#@JFq%F)o9EPH0C{=R__3HFF%d)cEE6^^DwHkQ+PL< z0GW&F1aQSOxFBts6JV1cZdjb7tN;e(M7h}D-JPU~hP@}!KFUcBNJJ0J2R+1Thh@et5vP;#hS0U$qPw(ch$U!`FzBR?l_+el80kGM0uTv>3b%wR8>g#a zsXGmO(v5QVigvDMN4_YiN$ZOlnS7;9JXNzmncvxwI$Oj-$vDXJ#KH}i8A65oK>o`c zY07@lUvl=MyZdqQxHlo!1L7CSBf)a&fGDk#*7Tzb2Vq;XIfT*=0YS6N($+)brF3K} ztv)O&NbUn@?_uy)Z3<}P5g0Vh>`l*)fLD4uh8&KHdD4;wwEQSQyj4%xM=_GM<>>iQ zfY#7}e6qzs_eGAtgWbIO&6CH1Rfk@AOrX-NKK-2yVcqz zadcqO6<-lfaj>87VCc!awLBUF!|s%~ZojQhF#-E3b@*Q+2ARvZ;~lg#V_H&F;MPEt zC`LrBi9z#LD^LnXrtjcFc;5kkbGwHeXy-98TdI;mO^=Il()LNT^*9t3>91(y3E)NG zKH7UiG?ZRhEH6%o+B&K7Uh+C6!mH-O0fnVmMkq0Xqwqe(UQ!$&oVO0fUwl_n^vx*! z6i#M4KXS+se@Sn5)B7Ai?BZ_nJ&mQvHPEHgxJZZmNl#B>iM)1MDxZP+*tsb-yqYjC z1Hi#qV(vn%&WgcOluSRJ6+NVpdMb4ehnz74-Er1KY>${f)D07eKg;O>`ERhT`N$lM zypZQa?7$9ca2^B>^6Sy( zA@*pzgZ7*UC^~JU=jUNAg1GG)e--U37D845k+iiJ@V}V5LOV{%m}+FWAVOUN5PK}| zKK628TB?(j6p8^N$7`PpqL%9;1OUjpg969guY0S4l6^rSr*4J=IbK3R zt9DfL61Hghc9!0k#2cOT`K+bm6%nA5Tp>@qDuSyH4ZvQq!X)#bH0r1T^GUbi@@Hg z*VcBbx&y`&ETR0i8C|_D600;rItNW5(u0)%J%D3_{l_pYBTX-2aOuc9Me#Ryhn=#_ z!>>;IaSiRiDRxOOS5x9GFxk6OI$3glOYqPf96(Jtb`VLp@LOl~cOfES?DX%zvR ztG54!O#<}fk*s{fPKm(Z+P2a9^`h*1B3*JgOi}m6V`=A63d%)??f#(7xuQzN+J69< zG>QZ%b6q9pAOHk9f8-!7$i)C_AEoWNP|Kx$;UK_x6BYbI`TGbx&jmt#^N<1_;K2BF zfI2-8W4&uY4xcuyyiIXHRdZCFF+J2K2}a=vx6+y(JP;Kf#;bU0x9$OzdMH{n=yeGF znKQMsGR0Wr;;;e(O6Tikv8T25>HfkJbmWFon$X0D!n?w|0&E%01m4DkV2oLIH=EEV zw3!;!TRTq-8EL>1K2r=C1A#JWVf~haiG`0O9*V=%?ng<9*5UERT4)nOSHnZ$4eQU)qh9 zJrc(%R&m1hCB&^yQ|DrN#<$cia)>6n0!+|YWP^RaCY~^jI_Xf>K)D)O0yor7~x!Bdh-~(NWDGe z`9$oLwwmek6Vb=bH?OcLZ?(n%M4Kl;Etu-AOzC53^;ERhN%eb^S;1bpHj+kKvFEyv zq^DL8-5+{V3p%fjI7h@4p`u_}_{ZQ1r*Ox8KJiqmTL9!B;50?U7?CC&d!xYn$egwzEE zv(BJ$IAo$gCpBJKF7`$;P8&+)@toNVXhQyPR4=D`940bQsam~8K!=q=r>cVm!iEi zWek1y5@75+h7P_I7p3nukogtp>{@Ty@=DZlo*M(wY071e9g!cZDC@>i-Ye0l?)OmuB@J_-hK@%8*O%!c}gX=D|P%^RCBoBPSrC_Yeh5u7Omwp zJRSv_v2w_PuK$g3EGkQ%{s!%6d6+z3Vph2%iw8Ol%4CfC@b=v(}_*P1}U-(tQ z?F%}|_s$PYj>mXW{%f&FI$w#>-{97>2`PZyh)vR$A1UswXy66~NZd=0|E@ASySEjRjg- z5ju*m_m|ff7FjvJ0v^=U^C$|K{bpe$t8vuAim|l5Ky@b*3Cxh(}DL$M3+!9GOXV-wQWG<{IpfnQ-4=#=w09b$c&HI+;<}cqE9z zl)9;ZDAU%^mG{^V1J}@t_gIaHH6(ukqwKVXntuT6(Rv0g`yd(xc;nR9wi>&FVN_Wv z8*mbvxkTysF^yh-fSx^PC_z9(j9aD`~P7n+TYa!FT1#u7mYqdKr^d%I^JWTJi~Vvk#!0Pr#VWAISO%z(2H+oIk_ncVcTY zeinh1?jkr9GD#%omqzl58v| zNAL>v#ST&BI$y#mTas%@{g+X`BnL_jmyt&)xu?`NoRUi6c{_BbrR3^TCehhaa!n~^ zDHW8Gt4ga|khiVe9|_dsO3RgKxvgAQ`f(}!WGe?t&i&}Ft?XCUJCeInqiZQUo0G7U zqrHd1q>NJsah4qaaW`Or7RuWT79dZRcFk#mogCoaWg^aaP*8WZ&c))By6QyQZYO(4 z=}YK5em#aQ!IrwFRmsa{FOdPP3Fx?lCsL8zN@GOTmhk8+I;pPbT!lj)DxViq$I^gb zY%(n@jk$X#Q+8=NF2J+V7qD*eb#W~{#l)`3SD6loe7hcGcoDeNY@zc)23Bl}l; z{T&~g`3e%7Lrn94*PWfSlu93HLK%RkzALRLBhPNyu9mv3@?bWtCRzp2-IxQ;3<0a{ zuI6JGet$^f?YF9?T91F!ddiF(>T551O9Lm+G<$iQ^s*Jzc96SC%UaPa2f3a!xD_36 zkSm6qfsG+Xm)zHwJ_SjGRX0kYH=4}xavB1vOtyDV4LyC$orY+2>= z0D36P6{PN2R4B{!EBT$|o>dRIy|MA1wV+0PV)nG9sIqb+$2Hxxp`F!HW?8wmwESDz zQ&t`$1?s4(L5^%b9(F~nw|2_Q1Ypf}jYiARcaL<(og+pWGC}ROx)Rf0J=}e>lCe$l zOYCw=pQKF&d5NpRto2a_za>=g<6P?OBv+Ac&ZQJ5In$}bT+}IH(ybA5NiHX6JEofW z%UorWiEfpXtJK~*0+%2h(@mJQcsy3Sj>-IRrjMpkv%$mB0U&fr)ocoMmdCrf@;3#^ ziAr>F{Tci=h;}&3%D@wZ#(FzxNI{fx4 zy2^v4dI^-~Dp!`8rqeoCkil2q(gjy}Ql+ugRILV3eyfu@j7cN4VdSS%e>dPvtC_UI zP4<)mp3r_bIb3=)gFd>+e$vXS-}6 zhH-;=CjcYZ^o?Q9!wkgP3#h=CNf|YQX1Zf#L%PvMcVN`519Zz>p5*vthBp0z8Pvl= zj+6XN^s|SY=IB>kUU3FBs3_MS*nSXWSh6o)b~z=x^35=9oz->g(?!L!lqlU}mhlv} z%xb`wEVjclz69badfe@_>sL}|V|-UnV|*)5sIH91{wNil)$F8__l{0flvAa|ffQLu zZc;gMsMdM_bPYB=KR zgWM2HOf``4>a5nVE!C`(VHOufW{v#?sPlXq9rpw!t2O|hHFB`W7KC+yLw<$2aLPZA zRr-WyH2QcuHTIGlNU2q6jF)^x8ugZ1ddowkr~vxOTdrK*FF+H<)P+0rOBVc&^QC*< zax+7`3CoLfV>N@S>QoB!k@p%_&iPm2z$x^?M{X+l`%n#E`ApfXFve%t!Nx(kIB;oY zd5~D@#YmG2+CN|*C03Td^Gxr}^F=s=3S`uMDEgyVdV?*Y+d^J`z?-3^slOlAx$OYT z@RO6IE-CcEPi`!Eq)@{ua+O|xwnwz{>KW?5_%|B^WGB{d)$(suzau=$zZTbHTM2$Y zwfOx@Jo9%Cihp@$^ZQZlEjz2oVWq?iHx<({=xe>{V^uk&riTtD`|310ATT0aYQW^x zF5&V3>-RP#@9WUYYVt7Y<~Xtsl*0`T(*6an!tvBSP;Oh=#}yL7sCm{TSD^+8Rf3tOf(BO~O#!t*bZ(8JNwwv4-@UOK{5T4+Y9jNn zvj)TAp#93p7F4m0?B(UMjyu!LHVqjec!j80nt;#o4@;Li@+O^2+z1|}nl~pI=49Xr zm9P<(a=~&Zon#$GL+Z&3q)8!ESWkW{4fsNT)t4vf%2*N_$U*RvHqhdR@;C>}7POIN zH+GAqY$F+Bg;8$g93lrvTT4-Rh+Idi)tttK$gd?O$dV8$zt>4GYFGv~0p}xK?q`|a zOkSgt7B;8K&1Kgrdm^=YSa}}H>T0-f7Y{M1hP_mIw9wk!>oQ*~0vON(1e*;^;M21+uM4(3njOfXGtBq(C5}zgnIk}nHbq1z)-H$0A&Xv@GuH^-~|=7l505S zVe$TH@m^;d*G7(RwFsrmQF9POCA0V;n;%lt2l!YjiN$~QfGk|YKcmrHrYH^w{uHMH zeQqPiIF`aIe*V~rIvZtNT07AkqwHFwkZQvVK=-%eg1$a@(q zsjsrVz1F}c{snZERce7|#`0ZzIv69@c8W*YKXC2Zp5DjEeY^`}wNbe%@*sQ+rVYT+ z?v>U%u{0r8Zc}9u>R>y%^N7&AuQEd`@Kp=2c;jN}UaTDH*teQJHdVgz`UKT%FOQV= zrqi^5xX)W~ew{u^=3@}`3vs4M^eg}u!j82W2|A86U< z5!LAkdQ|m3^}w(A0TtAj%85V7+)=LNbMv0YX!*kaHKQ>kO@N&{@WN&Rn!~opQT7Xo-f_opObeH`N+wmec zYib!-z!xd&_E|P}mtAz?F6a{vz+Rczl78(W&lb!5N`{mlLH&CIX>p>Q>?!~1`W)8d z)=p@+nE7Br9(aN_^pXSJriT|6MI437#m4#&CnN4An5}6rJ?;hCCjUg`ddvHy^h7$} zTMh~w=A%Nl2=FR~*$I@Sg~f3>4DOO#*t~z65Bc-~!C8$`$oi_s^8)0?m>T-vuV_>2 zu|+ORe5hw1@XFBiP3r^R=hGfq+Xo$9-a{Ar$icOK*aKiNcw3&f4Xrh4;3%bOa}C!5 zt?fB?z-e25-T@eE%Rv;>R}Sx!=FPqRdz};25;PKVv^?r6N5Zs~*^6K62v&Nk3%Iek zcoi2zs;kn2MLSj=_`9VT6UuhYtVlu<@c4lwK=~W_uV?+Nd9p$`ROKh zVOGP1H|#+i$9^orhKN)xW7M8*HUk;JUy;@(2#v4xe!Lld+Ybm`w1tlLlcNHL4FJBG z8VHznm@&m_u9p%WgF`mirnzRE;yM+6!tDIgCYj zwuA-h??n0iaqb+2@_2y!oulI;4IXR5>Cgb#tDm(FMtyN4%MV}#`c+o*D@;!qV+Mz_ zF^9E@ibs*WNgFPAWs;B&&N0LQBge^jm9T(WV&r{r`Erk6KGm${CXJ+!fpVb#w2Hh+ zU&WV+c#LlR+>r4Z3#4T#K0lVy2g;ewe|q2*fK?*tyzW622g!l$eztj6l(**}X4FM@ z+Cd8|irs^ev>ky7faSZRJO~A6WY*3BjAutqalPQ|;5&Q_`BK&(+zdwSu)G;0e}P_a z3%waEXG(9j(Uc)_LZyc_)Cur>5Y?02o#D%kpoB^%N0{(~v;{RJzXV(e@*7b91UW>? z`Ps58K`ziqTW->VVUQkdDr4C&Ox8ge8B9M7m#1}FcETQkI)@lCHbZ!dG4;W7m@T#w ztPi!40cwrGh71#)ImuC$%Vf34(=eao;o|wqp8_zffS_u2{ZCNJ2rwPLl%``NWK*T% zFaVkpM9-U(C3kIHLvKOUV~(4xE9eJ z18Q@)07U#MM)~4fOT;MotWFxgibNvr2;S>yVxrtgsvARF6Xhr`Qz;h5YJtFCGtq~n z*_W}YKxx0$;xtCSsq;%1h$B*~lPR+}S4D`dh8s%TvsR-`(L1sqCvTC?tf0N)@;>xPDyM%|+8TZnFWc)vtE=90-X-~1YeT_@BI7!|im8nW?lI3w_ z2VZ02swD+@cY$(}!H(a$V0oI1>zTCXF7-_T$NX%$Wp@fM?$c#t`9?OC6G2cD9!&-x z4EM2Y<#SEyI9Ya;?8ejZ$?_BF-e*h4DRKp!G;}Ksohnao`Fnv5re#S;ya5%G=^4i` zyL6iJr^+jlzJA^`h+?}wp#9V2m#)`-E+|Sc9rEWWK?z1f;u&0Y$4sW9)8&TJoOx6* zUA`#U!*wuKJ}g;FQD&O_gVc5_`OmjW9s~hb?$yEIL+x|Bb_wAOb|b(jkpiCdie9 zm#WF@bvx0egp zeL$PP8&S+Gd4+W2Fj;5Gouq*WDQq@&SZ_VW&z9qApXC@de25nl_!yOWfgh7H-}D-d zH|JQ|NiEdWnD-9S!`X5`)xFS{moS0q`{WDJ=0x^v%xYNAqH#-q+@_#8a+Gcbjh`d8 zmBv=4BXhueuDVVJlRQtVvxZigWY6-iuE7d>W69MWV^1^EMU#9|n*4$m&&9cQ{|#l& zm8-a)y^1*6&`e=kp^eWZJ8Bl;ouAXkx!80Iu9CM|o+iEehJG;1ZqmCewAYMNu)%Zs z-7M!zk1o^sZ^1J3s7p`2m8+EQxf4JwONK0Yt9$+>HA1&NBHRUEJpzde&eVM6_9eQJ zCC9nW#@pbl{O;`6cM~pA(|Ph#>BdCbKTmEg{c@3X^X2cQF$%4kFSl+nsjLoO41mAs zm>RpL4X8Jpyn)Ucm2>|q;2@DI$5aalWR<_Iq z43AF@3~I#_+O^!LYLfOlZ@GIWTVQL0*e22fO>q6Pr z@bnc5&A63w;qR{~W1*bt`qOztuIFj}Ytl>3lgA?YTj^RJZCoVxlg7`a`6RoO&v$aD zw;fC`@c{(oktVC@c!Xg|_7NwHn-A{B=jb!ZZRzNDa+FICr1?YKKPZ8q;KH!k<1>;x z7PIVV0(Dp{*A}@BIvhbEQ1I*tB-3KKrt`Zq7~=s=$;4NuGm9x_vD`;Df~qXRg{I&k z^;ja`liVIs$Wnkj_c^65g{bhzbUL_Ho*+GWN_9!@E4`VP?_dLRHoD4%L{bL)Z+)aztnXm z?f*f}mg*m+DJ$g!>HHCTv=UrLBQF}Z3go=cV7j_W4zKg!7FNCs-y5t@n?&qmQo+F9 z3A1W-<&g902s3Luw$XF>652iw@GZH6X(G57Ol|a%<!6KWzn>h}qumGBsP=lfc7<^F530zhG%(wWV7W!gU-xP3dO1?s zG{&-bz3eDS&-c>t4Y>3SZ%#ut%7bdzjZ)38O|h(aX88@I;f(A`pCb0z&0$syhazH= zJXJjC%|^Mdlyccpb(361C(TDJp`Wmjb(T_Z{*{N*?4KZ;dE1n3|0Iv{2N^dy7k{45t%tEFc5Zh)SjDrEbrrAOQ8{1!P)dS#&4U*vY>8mR2~RR2&lLXh&~S^DW0*-M&kpfkV7 zH5)}6WShKUB?MIM0LlN3da8H5hJ6=uPaK@Pl+j-8&uDf~_V`lut#W_YF0VA}8$N8p zkqnT9whwwBd8Aw~`tH{E;HaZQAx%1aM34Dlz@T4sl@oYj`dz~Tj(p3@xD92P*U|;r zyyAa@jZUC8JzMhFChw9S{6ZJE0fN&nk?(dnMp}KC61U3%o*ut&x&yZK@@AriH3{Wp zeF%}Y?J8~C4pRQ>KsvKsuH7=CTeOyRCD!z7S2dKyjOQG?i~Xp=jpj*C<_v!u@OvB$ z6gh{mxJGjbvzEg+brSf?-PB}#@jU2}^XA&p}QN$uo>b9A+NFu&6mx!tsC{({?kD(T5#!U@8WjU>KW&7@ek8%?y?d ze~u4`fSos6A<82BZcyCZaCFuKj4ZeSy0=yxQ4$&*4?UvhVH}Idq{iyUqffUQfI5gD z_=hc5i$KoIVao6QaNRO{`X315SI|V7?TU_rbnCNezPBf{Lh zfjXJ}eCR0)VX&GIksj-8`?VkNzV#aS@-(oQ3g+F`7vXI0p{|Xw`fo8=LB}ErqMW7V z+tKOM>f)eDwn@GS9u+|tcgsNtDBya|w|W%Vc;d1vg56O5U#KptjY4#U~BKfgo;7pQ1&?S$u8Q=W>95oTV?L;h)K zA;C230e)f-SYX(zLh{)oSE})`c;%9?bu#?Z@VX#;fRiDki5u$A80;Tf^d%u;MtrlP zFEnfq^y)9G(VRVU4ez+rLQtO5gwSo}&nz`;JN_+Jur)T7;-n z6h-!(EE8ilvWB9<e^ZWe0 zUaE7>z2Db&jof9$u zCyRmN6Qgiyn`~?ot5r5r-7Ttb_D*ajs}(T$fI`l`$t-2LUk++8Hsxe-)*A+Z~Z;cuVMj>~VYMoJs%ULmZB$tIJQe0_#3qxi_!1M6dp1NeZA60ogZl>4} z-dLVs4Bxc?t&5LETE1C-*W<;5mY?N#=F=;Wyg_Q0Gbj4EBt*S@0fjHtp6AazxY##F1f3#H{;QC4YKTRi@V!e}^ zr@6_zM|63sn%roOFP8ch&VhHL)|%Mym4K^J-nc++P8o>-F=H^Nn2~biSVEf2+eclu zLAGdSqD9-(aPJ;XxMk)OgO;$6lz(!%v)r8GHxb)%d~t+2R7 zp86n}8Z*#&z-8w|D(OcK)KocUw=}HWd z1Ln}W?P|Ek)B5PaobX}53HfOAV1lE}|DE1!S0gK*Wb0u8W=73-s38b9#%%@YFykHnlzG$9TTF0GShO z;YWWr{K&4EVch7)XJhbv^){Z%FfR97i6^FsJ$M4h0<**KKHh|wCfMVpf9W1?WFGd> zE5yozzmRn{K^B|^Z8!s7@3#d-OZNc0JSlRQ>g$|}-A3%;BoI~pguyJ1q7l2GBV6?( z<1TfA(jk%zyVW{|0IItiYQaYhsMl_s4|!77ZndV@mk_i|W1anF{v`Yb$>3*h1^?hV zC-b6d<8HNM?KKzlX|=D;%Mh6Y1ovhnio&L=Z^&n#>f&*y5tgM0sp3y)8OCmkv9-gD zYdL5}=EYN|J+NA@{EV{qsG+`|k;p$eSLXc%;7P)LHXb!^VpN>f?zeM1o!kS*t9k3m zuos5jYT;B5zndpxczUO%v~a!~KBJBfvU+uMi!<;fN-$haS_(IR=Sp#tWGzTE!QuN1I|7~r3y85E=5O}&x=-6JhNv$>KFz$lX|1n$fTAyvt zzk>h&W;;EUi59|DpiLGYLa@ha@4W;dmTN!3YsE@|x-gl1jIzAsdWLwLbu@pU8tD3C zxOI(A>T86xVFkBv9G%#QeU1B+9`bL$PpRsD)hp5l6G?!u&J)w`0M5lq#hKcKfJE5> zx3j#NhRD2`%hpw=@ipx6Vddo4t^ zz__Bplfbs&Yz*vpkx;s)2O^VHrtt^Vx~)&*XeiFKsSD@^rz4-&7|;4O;POP-d%%|- zgPw4)<~z(iP;R`%dU@}!+eto8k{AKs($xcMZP$7*d&ij)rzV?LFtLm?mSUUcS0?9! zDk-aW(7J=_LB#_dA5!c3EQW}Vq+5=u2&hoQQWHqPY&X@E?TGL0S*1ht%v=2v0KgfaBvunLnHQ9Z{S0{No8zH~2+D;4$SeO@~yR zVwrP~HTVP;11yK{Gk4rOG%5F}A-U-VIdky?h*lTy;~$}7=T8usAWATWFXhkI>G2WO z)om~+k+}ybJ0O+gFSwO!UF3aK-KKoAnl2rM1>!efYW_R?F|J-@!`eZR9M&;k6t2f` zwC$x>59q&uS1i$sB;y`!4PJ$wERC<_W*X-$7r}W8xAFI|OE=QnYgImGK^B6pE}I}l zyOy+#Hvg_hWMc>zkYy-RB>&?L!TlLl2pWTdnt zb9=H%crSDT?fyfpY1m2^|4?ficF?OoV6yaTLtcNX?G4#9>Q8vM zE<++(F1{ZD@MBHQ+na130i@?$q96ZMyBbcB;h5UOsV0_(r^5RMB!EAdJ#{<=Tk%uM zI0ie?)p@l3nCj+s28o6eFjjb}?#5+ItT;HeUF<`;a!mCPDlEk!>mU@DlbWDd)_-^g z;KS7wtX0Z=-dg| zAO@Kz@TBV5EFQ)}@P?2anZE!8#MIf5g;mZnq7$vc2>=R~T0KyX4VyZpf@#I$SIRvJ zvrTSYT76QD!sM@>RBQEGFc%yJ@;vGT_R%1d2W<-8>S0U(u6;(7QEOs1 z`%~?&XyRq&VZh?Sd3@$|2hHm+I4~ALQ(0Q|Ba5$^R+)K?l&NzxhE)i{tJ5swer+>8B%5TMiI{=_3L-2HHaU}r*o+s+ zgZ3j5zg=>L*-UwjY4(;?NE2U9h%GlCQ?*m7OBMTyHVA_;J)+wx3OS|51l2}^It68S zDNOdKe)i>|X2*?w%?Fu|AorlsprMvowEPqnaDhGTKBZQvciuYH3`7}>!gZ2V^@J;Mk@tayfu;Mg&L<}{AjLgtTda&v31=t^>S*`u;D zq*|NP-pjaSmWH-15Aenqek}L4W9~I?C~@GbjIejHb;c8z8fG{Z)@PY#hV-bTXrVXi zY4!4H=s7i_wigf}=a#q3iz;Uj7(Mh8Y=vFQm$dDiIyor>ZGl|Cn4YH#R8YyILC0PK zfOsnYrLlndydb@OJc7aC3irkF)h!L{a*5vl%x?0YG^ecdYIx}7T+G^VQ6=%-$L#ob9KZS+b1g`Xk zE%g|ARMMa}X<$P0IPVlJT-5r4+Q|7M9$fBT=cJ}bGt)RDm)-d5WV`@($N$Wv-!G^h zvf>?JZ_e}~&|D$EZKLNGV089hMcppqSmEt9nsHIBk!=UJYduy1;_}qHVjU0!?N~SK z5?lj9@YXe*>NgcKs6K$9Sc?baYgsn=f+hUpv}hWMRe?}wY>E@h&546@uU3dw#%mD9 zQ~U8W+!8SN+kckA(fuIguFTP)7ZZ%s{*qc-9Scz_$<)pskqp!YlyeE*c{Vd}@~FYlIm%H06G;$xtNMCsa>L^@0+jL4h#*RMTI@EG^83Y-K)kYHFNMqf4hc; zUr|>z+rNUjK6$7e-RMVzrLrbcQWlFDcPZ)dennO4EyBDk-7$#n`>b za`imQG}O@)8;Ngd2<} zjIZ@>wXx`o<$>JY24j4Z<#W9^E2?2EP{2;IPL_Wi8v|u5^npb!riO3T+BEvQY8Oxo zwV|J_L`lOI5K&gM-s>H5-f`eAt1jk_%-H zsDyxnG?{-A#yWm`mEX$ztJlfl21KZq0Ke2hN0@Tz!$&-?(|_8t?{lUKRiQj-HaJ%r z)P^;vs;TG_iUiA^%O zF+uag)IuL5=8Ky$KLbT{nsU;W7G72B1f{xIRT`)2j2gP_bdjGUv}Y}1hxHAV9L@pY zs15E)H?FE7p{=rjAIw-5_tm+mwrT)QOD<+s)9b@F&GdFwCl;<5Paiy|gljm|c(H}X zTvJ^ePqf2$UqjOzhCk%y3b|S&M{RPyxaKV)4Wd@=jd!{GKov7!c0965 zGgrq^Hc}Jw>BI}I5#A*a(wBesg-fU536M85r96X39BJ|_qEpkule{lgmr3v%bAk0vTUt$7G(1Zz*a`I z{L{c-iz7Ukk^$aPXw$}G;BUN!+hXyE1)A4ecW!9#DZIAS6Oi&vuvt&^&;1*S?g6@* zY)VCR*1xOZmG2@8r%3=_Fka&x6~S4cTeJKZ9*)Ai&<7a!pS4}4fC#V9H<=qYWo4~ekjZo$dVOK6b4LStJmEr(+BY>anijRyl0y7f) zddPyb^o-osAYx^$$1v{6 z=kHxjG7YuYrHKp7ZsCq$ybNjB(jF^HBQ@10ICK1~GE5iCq5rdNg&7X8m}W6wWUzuM z68}wBQ+)1gYNM&XJ(t1PM;5?Z6WHNQhM_6sl@t!U(S^ffzwCckrEk&oObBS8NM$sHr z2CU>3Ct5n|`mvZ6l)x`1poA(uQnP!n0sOtUJs;^%s&hU|=VLtMjXGTMR2`EH2eo$J z;WCokY$cl9>{ZOqGW9g;Vt^6w6L=6@D1>Vx3*FjsgvfgYXdAJJc0W>U)Y`ZYrH3K% z19sV;W z1GQzqwV$n?q+kzr5%`>Bl2)a{s!b#fI>5v+slsfU{y=qeb)3UElm&U|$%_l7HVGBl zB*{6>_O$MS8q=TwT*(t~qQ%rwzq{TPtI2l3pYej1AWFN_21>W@X{zxM!@Oln^B$@- zJO+-mvVVVo%=1>dZ;n;F+S-|RJ;Ws|kNI@@p;{-qA_}6pm1vGx+a1{YlRyqliOc7o^Xt*Zh+1LI{aWduM! zkhP0Ji>yXctNEU*T4EoSmFcniEcHvM>tnTX_6oF=dqc_H*Tm8smDu371iHU0fX67!3xIUuw`5#tPF5{xYE6MyLG~%h+toa#8kf66+`{A(9vKTZ;ZgxvB$M=kzan(ASL=%-$%koF+M^w=Ai~lFj`75#X9VojVW3F#7ZZbT6_PC z23w7I&{^f?STFXQ@1T(Tb6E15BaPy7)w|=bx|MH-&cL));br3-rJ_N>k-zPBaczrXR2r77hEC2Q;>)^6?t)-EeoN) zW-LfGCBxK;%w`{XKjp)-xN`mIPNFRMxF3i)ZUSp(H`0dZa4gzN4yCx49Arzer64iu zhR}@Hs%OkJ7!dfjC(gMl0Q;Md@|W|vg3~Y)Of-&y1lGEtB>^vV>0lss=U;-eC7aef z!)1f|L+Hdac+QSHLSJ#?>)+DeQnh*G?HT2qTjwec$smDlsa9nctBcbYraCNASS_ka zruNk61&sfyo;SQTIH2WE9TkA$+5;GbEKgq0m6xiQZ#5+1woKW{3uBcU{)=f=KT6eJ zg3>x4rKTvK-R2i|%QA6R

    1;Fs9;5dHi@b6WeJRx06eSJ#fS%;YIFnDD7U-7S3^2K!1fpEq1JBE1@%f*)uXXIag`PWK|%u*zE$MbH0+g!|Y) zHQ&I6dEj+g^hS+_0rkWi)wRk=9x!J>K0;64r~!@_XMzD*kB4|%@f7%0ty61D`ae3U zoRzUlVBccut@A{im9P)q7LCnh2FHd;vFjqEMosgq3={T<%u9C*@ueWsTuBF;u!j& zyMXMn0s}iSj5%7#9_mnryI{}y(hp_07=ErV9V}D7ay&5BPS_RYJalcXmh_E5~6wC!=!SrH8tbsEi3gr~~`+%sk8=Qto+ zxr_pL!}()HO**Cs*T{liR>J0}O~Xz@49;|5TQ#(2?T_WSnq$h31^s}^hd{0fO=Aj$ z67RH)JSvD(rG0f8RzYl3ruQUoTY;odTWE-_7^xiYL1%1*QEAbG2H1&#%K7eez)no* z(zkngUwi^k^bUa3S@$PCQpl{EVX-+%p7oi0i3~T$~|xSb1i&MHbusnbXNq3 zTS&^ju%fuF)agc9m4t^!#co^xXIr2-rBOP~vC46Mqv@AQqL%xRO%O26c0KTmMKXkU zhD=ea4b7t4l|-TPvI~80FIp?L9G9Ua;l16 zN~d4wQdP0CdJ(ig3t|g^-eNIIwcQhFo`aaxAd253{QCR%{&?n050(yk*&M8$Ufyv6 zwNyoIrCJ8{RmF1UP$l|X6`hn09jJp4aAF-p^M!D8ecm4Jr9o|s+oGf4IJODcBAvDn zpD2CSQDZ3r6*-9dOW~)i{fzRZ2vJr$P=OSoN@gP6m7DOvvo^t;OYE>P*jd(*dtBW1VLm!HD5`A2Y`T?q0mbe|n{D^(E&1#mJesdB{m5@Su z=p?+A;6ieA77?DiaBmtI@~Ahk_G3kh7?Okbp;NsEY_kR1^Bj zMKn>)KBKcPB0+xDyOK>Ilz#wmu{QX7YET2??fi^-*AQ!!Nrww6x{8`ggQ*D&jJQ|> z^g+`hfEcO|wtlL?Yn{%gL-dRWuurT{ZQVtZ^22IcRUQtIO=`YJbC(sobL zO8L4am3a!k;A0v)MpguEe=*cki{BibNyrsvVj&cgxr0Ecgv^wOlaZb%q^gL1%Mm( zWzQbah|l1yAJS_(R$9pxdV#+sV(dfC*IszhL?2PR)*O7~TwFLykGIV@6c3sO-&2-( zrf1X7D4`r5NymLeUH=|P^@$+2NAyOyb*5-e+%{WpaLSFA_i3HHsFtsAQ?#!s(pO9~ z1Qcxa6?G~o2b$3Nx}vV~Rg)$40M64MQfNKEev>9Nq@HLOd^fWEo&pR83}ejf&fp!! z5l~atXJKC`!Uq6YaBaF;Pk1P+BI#{C;pd)(a)6r<_$9Efd`@}w!I9LgK8m%8r0(@a zf8}-rZK*E;tNYw3-|w2R(4u{xJM_H1SgOoVqWS(JR!L2w6aJ#RM`n2WkaSrL>}O?p z!@a{PK0wrU3P*weqdfn%kg@_qSxw)te}BNhbGWA2?u*Z9Q3H^cqmAiQ12Ii$*O)p7 zf?8K-OkW0y0A=WBbTCi^yR8Y;Cp1*QkpecVUrEtE4<(0&BDBg$XPp~s1rgMyp~!N& z5W7j5-LtBA+gl5v52ZwiiB3Iy|Use^M3Kb zI-^OD=7>Jk>GQ^7m1;o{U;WnA3+>7!iVYJ!O5o=-C=87rI8STCgok&J=SbLXj#!nC zQ5nys7_Bb<>_hwrV{7}IZiYcRh(Aw(;Q-y4m#9y;7_8hcroG_;icLJ-4HqV-`u^nx z`VF|th3(L037QjuF+ZK04n}(@LUc9krrME^GCEzLPa{Qg;I+#3HhC8_;hx#X zmP7p<#&eQPIILqbRwB8I)u&o(Id@4D(M~z>38gj>-zYmT(c>n7??*8tqQuAby4$ls zmgTcC91k&F%MAE`_9@<8-zR0z9J&|<326T#YS2{pD{cL#OH(nx*)@Z&{rz)$^@Vn; zG976u<|_%4saG?|W%b6=oMs}}eHMYpU4!YJB^+4s?-YIxAlHujTH$H4FKNw0fHe7n z*u8=BfSZC^a1wbphcvR5xubA4(*1BR?yuU}O>>%F)(-96@!Xn07>|`%|fMasGnapbb z3xE~I=yEQb`n3QMoI6XiT7anxu1-f=hy|`c6k!w1Eq>E~MJ&Lt6tkLNL}OcuP0EB! z@{bXN)X$1Ofaa_sS{ft1a2{5hd+LgFDRa5Bt4*cWv7)WwP@6uF6)gj%g1uU@;LgJ< zI+`EcFcN+k$Pe3~R`NsFR`e=Xj8VdB(eOCo;aZ~>KKkF~Mbi1r6=oPd{b@xUSmQbm zdK@R5l%*b2u@!`+@8c+{6~sm9LGxP)7pIpsF)DM!5AP~5V1op7H&8(`_ zs`f|8J06nqu-lXuFNQ1Y-05+=n62c6(Ub(NyuCXuNf33E8*a2cLDY&l;8u<+xo`9) zHNP?|$C7=+EdSWv?)>4@46cwcrAv4a%4gkWurE3#vJLz7T8R`F$@M)e~}VE!bXe) z7F%uZ`{t;;Im=rN9M%g)cr}zlTMHlmw(koKEibedg>*bY6DU|1&-3zgr75jN`;=2P z%15~HhLvuFag*@%(QD{sx$$)2`F2)ZdZ zclNQYgqH-9iPSJMq>06D^B)0BR;_<-y?=)z;$+igd(H6ztxtpKaHSU&rHSti6=`Be zv03RKM2$L$;J}!w|A6&}1#f_tIordabi*+6;1#+tt6^R=rxOI9+xzHnCo$7do!WI4 zjo_h_)ft+}l;ievybJi}dV6}*1?<`_m?FDEOfsLM z0bNDB(@VrOw}i313@OI$Vf?e#QbAXdu6$%9_ioTEDpaB`yNQ}^1Mrdc5SIz~!|HDf z&1&p0`m>v89biNvNve`pvrHLYQ4_v>C%_MR!rx^9SSxWGTvCmrgiNL6XUIn77&-QJ6$m zy93ys45sKFB3Nl`MLCUP z47L4d^p#OnJ9PKoqt8d+V62bbz%U+tE$6U05aN#%S{Yk0+h;x-O6H!TPR;uWCjf0n zajS%cF&tG72doECv%N+~dkW9WHxZY`QUR+?pEa>{qsqNRcIBJLSa5PNe?_15g7EnB zuLXs@#McJpcw6e<2TDNK_=3rO#14bQoiAXDF`h-)px-I3A2#=uH?8dl&@vRz@BBRc z9fkFWoN?hT?e7oV+p?M}ri=Q@=(p4;UBoL5-cn||xa%2K;bQ1}J;{>_>TRx!c&N_TLBxB^wBDqjDWX=zR`2U$P5wT-z=dN0TLdeYMj|Qj3=`K)w%9fM2yeK%?g2(fg?OR znjt*vjPj`jmh~E+v8|ntqA_#C)r;6&{kGL%tdl}jhd`hmSW3}DAiMOlp`0P2mfOlT zPp~dHk~Ti93;&@Q+&(j2(7vcj8;4*~>pIf;A;POd0%Aw}Jw!B97O$fwL!r-yJ*VMA zv1&I9ka|+2)<}GY<1ceJ#H+Me-RI(7T+wo9 zfJ4~1_jBHEN4a>TJbFUwhhYy^In#q-ARR4e%y5AJ>Z(M;K|4me(zW5DUlns02U)qJ zeYcB}N8o+c$Fy(+3|*tsXx9h`CdlGbXQcR1IaWeNBZara@*VGir4{mtj)Vzk2%?IO z0#mv6lKPH@gxwS$3c7#sa9v+^68NP)WaT$Ck|RlsStj z@)I#hd3cw8{)AQTyL9{$aNX5+>BT3)yRu7L2S|iq3AAT~sEyQvBHphSLONJB@F7C( zefzCA4YDb0jUS;Whp`og*P@p#eLGHQNSabGFH_hWlnX?Q#*2^|bHFJq3qcqFLggOk z$X-Gh#*0JB-)-nW6Tsm840K@vmgB2uOC}0mWt#)}O%z`#7jDu1i6YqEc$`TpD!rbF ztxq#k@FXxm?^`r|k_b{B-=uYuL}YDuT*B_zPj^xn3(+&hi3U;a)Z#*gKTFe;gt9)8rXW6AzJnJ ztOQ<#sBF;I_VAB$c=-*!;pXQ)6dPGq(dI+cM|{4j7sLmXwak7L&pJ%qrU;+Pw>IkJ zEbuzzOo3WpV^3dA5%p^|d5OEwdo6!rf8l@ZoopIspL+zFVu?1bDP5ZaoX{3h#Vkli zQP(LW3yU`JXZkct46B-0z|s^9+?oR!rh?jKwW2yxf!nnYzK8QGPmxd%+Th!zbbKm! zR_ayiI8BhpM$j7UW4UMmi!mR_utD(4VyZA5!bQJgik%Kvi7BT3(;<}j6f>{+=Su&o zmSmnT>IB@s@_*ltXla!SWL`Viw_rrZsS=z|s_m!q)5UnDr46NJi)3Zoe)=+740T?1 z`DNKw7^^VfyXYPga+@0Dngg5l@%>bm10bDviR#Y~jcdd^qa(A+h+yCgdw=r+$%{04 z1~~G_=X7F*n5cBQNNs0g!RF)rOn_Bypy^D}!}*sB=mnhshgm>IFa4dUY^M0WdiRo7 zx=eBhEwVhf`bR3r6|o85okt3(c8;db4mchv?5BTyq0P6x1$Fk;`S}%q7n`Z>>?)U3 z{$-3Gbe@{$0a*7((Xc#`>%QTf-Xhm!bCx;c?M@xWD^bOKF-7^whi2wOX?3be+w(D% zVP`3P7I1udBz-;$eEjD#^l%m^PM)Bev%!|GMNsN&k>_5u4kCddq=MXaSRW>a%PX_- zG~JyoTKJAX&D-OI=yl$B-5cF1KUT8o3liT)&#Zi4J0;HnZ287S;d4b}=Zv}#*h^c7#Ab$JEgXR=8ynMWXrFmwE(pB^5hFJu- zEjW%v@8ak752*8YO*u|}^FYPZ@@dpO;bEvlbLYYGap)MGohLjMdPFbgiFCI_~SiY5R~8J`=wy53W+R z&w;EjoT~|UVkoHI4^c!TZs7Qu;ylf139?cyV0P9BCN)&k6y4> ze-t1O*Q^u#!qN5K#q`rcm{XQcrZWr08O6qx)-M9Cj+;&Q7Ks?;^QzQvv6xuhSdBNG z^$^&7A%huRXwzcUi+N4Oi^UOT(Pa8ziSVd?=a$vA=zX~%&UAJOhV1i--YyX{l$Mn# z2gV;K2ZWknc> z{{MmO^Jo-(^&hdxH+d@@?tn~DamGYj-bw_W0Eb9`&77TCw1BNN{#%%Bu75>;e2exc zZJ~PK0bDw5DMcLC8_B}MO{=bu44HT#~j2f>NLAa`) zz8ZMe{w3wChLonfq8+P2=`Xybo2$hs#rXwoTZ48BH`3KLSjMd{$ZjoUc*7BEGlfHF z!CK*Ou%)eQg}3`4|56OQ3l22_p#GLdAT|s`DgN|iEePhyQu6#ktW^5lqTN4;yUMS* z^wW<}76)e2{U0IfnSLRspTqzqX*x~#3H$x_XIk|W@cFx+>D5o7kxS;!j7&~&G1N)^ zzVV81SWuP!9T+#-AiZCWQn+7xWy zR^o9&_qwgzf0{@{j!b6G&!lIs-#+2HWWa75Lv zFQ$g;MQno*y|E8NTDJ&8`V==Pb-SXzXQ3zACDMKaEm@DLzVxIs>xD(RypHy4fVu3K z<8*n0nCupb$RljDKn%a#@6WXlYOxCuRRy+tJNPF43_|DI3R(QXaS*n0^e<>_LmX}R z1qWdHd&u&OIID~}TCn$5vDl#GzoniV#ct(zI(cjoH$gmlDTh2iW-YiVYjbz%s z8N7dKGF2?V`{C6otN{Cari6MFh(>)k^>|XIYXpe-Q~`Db1s4G3C@JQk>%Hvxdaulz zT$5E?xGC}p6rTZqQoWEGs?f~>QNPBuKk;#p zPN$+!Uk~M@mXOaD;p|dy@I{#(B07oPL4b05wNsU;?H2Ix@qg0fEg*=E_tTp#;)Jqm z4jtbrhA8!#Qq(rl#cAjmCXm+HuyOrBJigvUUvCqOm6v-ca=Qqs)^oJg^zkdRMYG+~ zPYN=(i!}x%Z4-I!1owYdKws>HSbX_N!HJz>Ga?e+!F_U&cKfSza2If4=C8;sD3Th! zyv?(NpIsqtc4KzXefDa98Q9wa^nP2e{_-Gi{=5T}z8mmeP>p8q7WvA_E+qDdfi>@k zq6K!&g%9{6E^bxDv{RupcaI2j{Tkn~E*Gu61fvA*)KTj1L3e&O!nizt=YAlwYl+tshL zS|EqLe)E#rZ4sUne?U}ImhPr*2e2Ft!F2L~m{h|zj%`kSaS(yPc-FAmYbvE56dRPF zH&pGAaH`?<26`a;2cb_wS%MU>N4xd9ywM(qgo84tkTMR5o=Q+5?Kvb?RDYN89IKV( zhFCkXyigA_Xv|@#(LcAO!o!%;z`b8|+$AolY?lq@VtGEH{G zSwpNgW&l0>6Ee^D-%^ibVx04UbNc#NeM=ytmTLVkQSmVt*8Htsc=}_oY>?PPu_qcj zIgUYPpP-oI;xn)N$mRkGg|D0C??#kd++TzEEem3uF*2{KRB{}cJNgwhDiWH7Ma>bp0YQZ^;a@zXbDO+6-Jb6aH@XW>*4(~mqaiw;Vo92$KYnB3U#`INk5)W>#m4l%18Ccy;ua* z=mxKRwgLKYg#ZE+V--p%pgzT5)WeU`Z^eMbmY3;Ku^1i}`ZWfpj|@;WvwY+Yr*Q)n ztkKi>>?w1E(PhJ>s?dJzR$iicSA}n_6uk_i*gi`yb`dp&`z1gU^wtKBra!KVL!L8& zVDM=AC=)ljYWLLtJ}2`Q0Rq6p5`*ZMYcRBi2hquEqN^C6#fPeW*i3GBtszBR7hY~j zco&Cd-p+RZ7n?YhWPhD@O*H^lhlN0W6`z!v*rJYUHEzudzGyv0Q&g~#KTISCi-&33+l z@D*zskEmsE11;=^lBk2i=9J21+SwA&)g=l%pViDPJNJ5T3*_lc%LKGf6xoIodTW4(WxKu>PN^fV)gg6@ds zHE-ft4622&LWKKPg}utxpwox5p(1wzufWi-J8PGHES6&A=> zXU5TC3-qR$D_XNnRV%IiAYnbkE7^E;v+*<`sR_S>v0;91L4}_pJ1{D+7zRfvo4TmJ4VoT z6mVZ`Ex;GY6O51bJ>(%xA3@%af&UpJ3Zfn}9s03=#ytU*JM2YgodEpp7q}V2@X+ z@=I}C$(&0UUV?ZBcBcxjz+!q2E{K06h8vWJ1L^127}sxkbn!I~(IWTK%h%Ak`wXO3 zf5Q-TYXEKiTQsk`206$9FAbT5AylBf4wbxM4t^=-x;6JyMNWeOvEh`APYiUDV^P$Z_4@zZ{Sl^SyyX zylor$Q^{LV&toFE19sF(q{>Mwre~{->Q5o>upaUKsrNh3`#Sw8>m87DQXy@A2hY_R z{R(QAiAsjRNjUvu9|`Yd+>l}K7u(o4Tn5K)9G66lSx^y!P2-r4yW$sjkRi%}8JlLv z?+mUJ9Qh!$13a~&L7PjBdlN&;G=o32P^6dQpF{l=8KAiICZi%3bKpns3es7zuTPN` zWU!K+O&JyB5aoDJI$l90JLUDn++iz0Si|fZUGO3#_^wgQxej6a834 zo>XKeWmlE%HElcT#bPm@C??r+%i-pJNBXs@98i1mIBPTb4%*D){ZOReI0|vV9;SAr zjt;WB+p{#r@Xk#6!N#qo&|>XM8trzFW~D=#zU~S#V~kQ|4aNQwnx)EL!v}ZJ@vIg{ zBDBNp>HRzac&A0YpV)5^ENf4*(Jl5kd(v7>pb zIM&Kor3!+ORg*2N4{OJ0`;Vde?hlkuUHU2E?Pyqa`MvUKTdM9P>o*+KmX|TbuOZeE zJH`ud^&4o55C3l9=-R4OYpSCgO>>f=%Dd_Gvy-f&SQgM}CmHV6c`nD+fk!x+f|uBl zOc>LSY34@c<1BkAkDt&qXSrNi7)%~6vYB$W8FhD&1FD&WfLKThU4n}~SiJE+794Sr zj)uzZ;9!U6K0WDr4LL}u-<#UFqSNp>G{sepR(?yQd#=*#;)i6L$Q_oRbSNps^#6l?8<4{nnWwc%4mOgKv0xqu$mlr`K>BRo*Dse6(h z{pT^OqA_X|H03izhOQR}O+{-Fr(@_il;>Bt=et{5R-a+n)(?9!6!RT~Z>*Cz>WA~j zN=baZ0Gij*T3Fk^V(Ir3%I4)FwApZ|^7^I?x`xD?deND1WgY%zb%&dEB*W zn*E_f#yo4Y=wc0uTU$@$#;^Q`(re2GzSYqfLWQ^io`+f+JQ(X`b12rI>!Mtz1p28q z=yLZMI$K+g%(k-@Vv*pM_G3JH#0&tM=}a@q-G#KU7@f!H#?L1@0kBS7tBDV&z#h&Y z4kAi4Tf7C)|4|OBf-n#nav}E)EPlP^(MALV?rnJvfx;5AXU6Pym#|;GSYd_-c z|8?vR_=@bjWT;yPmxuig-SUcA^dV_!EvdbiOi+gPphaFXkZ(Ke@dD0&+k#$u$@Yq0 zCu-|0{gr0fl<6(&DZV+h+*{UHK3+}-yk!SPi>4YrvZ2x|ni70u-*C6Iiq>dnaR`2v zSq1v5yBD88Kh}2^TW|^o(t2=M^A6qdNc;F}I_)DfmH00T+WE>rgRIw#F&l8e#^~hN zlwU^%c(v~WT*CE8Z-@bLJ>q)m3v?Gv^Q7av>CZYc$*WBz9WT98bYUZjlW)MMi-{nx zVD3~3_mlBTL=T$mCw-MwvuK5%3{pN>M}PRqz4Zbd0Pb@#{j6u9X7zPdJkJJ-8iArW z@Br|CgyZkJ(y!7joHuIyzog>2vW4QEL!R{{u31c`ruD#`-$c?k_2gK^7)dVm<(g_2 zD}TTd7VpL^qhs~4((%*j@A}fqy}H6ir_9=b+DF)21j?$OH0Y%^d^m;qOP>no7M0Vr z(f+bZy!3EP$L~RQV>sRQmmY3}n*T3^&IqU40n)8uJv5^2jnX|%^afzvw*t79!WFH4a2yH# zaw-i7kkQU%Vb&du`oOi`_M%?`VD~u` zgexI?qUjUWI)qXO6!r~A7FPsYXJlY|`~jVz*!sy`(-gUDjG}FvOmiCo^rtMKjSXcd zrQ6439|Sg7;!80>806vklo2FD>uWXswZCQBl7%qw0!lGJebHUc;=7i!kP3s)*ycv0 z1<7!y*fDGlclNV%FL&bf>Pn4*rDsToMmW(Q2d@Hl%z6T-w>abOvhM$?{q>*c2w;at zwr7EM-`0Ndp=rU=RXG<=OM>NTB{Y~uHj=HB2T? zSPbn8`?0;c9!uN-vDIW=XE>Ufy4uGf_LF{?!<8CvbItG}8Al@JEQ)d6>>`4yvmC3h zo%Zc~`XW@ucK`VjDZ2ycN*Fe?+c2^Zmp$E@2Vjs6e)MRmmD3PH@|j!3XPB+G7a@DJ@oUEhuYIr>K!3# z`qk%`-|}VL^6CeX@KUZ`wN0tCEJAiszRseO2!IHDw(TQje`S-2K8}QLuql&_ zkuuG-^B7P|Hp(L=d@)BM<}-};ne-?U`hmzL?K7HsY0WFCR`+GA9}`jID6J^Bvmac7FJT7DdS)oF0zEF)EloZjP`(RjdVlOC6hH z6zjUt*rpJG7k49LQ}C6kIrM8&2=46%lVdY^LrFeOSuLbzeYCYCjt6?7JfPwoHX%RN ztqXe8eGEa{KZlw%$Ecsh)3D}pwqjD~X>+I=TLw{$Xc?{i;6q)aA^m##P);;3x>pXJ zik6XvlT@_@sLxn$3Th!!lzliTY9W2)VB{x+7jwS*41w*}pADeD=kkW-9Yt6Z&3g)wrv z@~AhpjFrQc|FohXW1*w%Yfiv}>09yv!W}3&(OgBCF}~Ah<>+ zy$1S1FoX=M-wJyf6GAbqq^Gkhx;~WX&lWR`AQt>{1$MiY?3BG0xghk0wqYV{z}E)r_fUM#nKp!4 z#behqX>z=*n^Fiz2y7UiPkHmnHu$`YO)8WroKoapOhOhenNXyin*#~~xE<4-j|o1c z-ZDgCb=fG%Bj10Y?#4q%uiBl$5&&k+qo{uZIQ^kW`ZPfX8+_sRE(5AB-N7dt;mFJ$}{YT!q#-Ux$1Mrz$s@JQC*lzGJfLDiil9B0T+hA&)D4Rt0 zuU%?2M`D5<;NZk<-8=ZYEcaz4#Gb+8@rx?=te!KY@NA7Hj13a4f{P1t?S1eDN zehcvu3lV6`#`3dHElW^6j+1$UgEz}3zcx@xA5El;Ho&}ZJJT0!q*rzw4_s>zT-@X` ze_~aLuUDa`AY3cYxFU}jTFbrp`Y8*-zV61burDiafX}bVV@`r-dRoiQVAk<4({T(o zt0qyV1@OyYyfh}JG0iQ}3TmRShFr{S7g(hNw77hVN|I5^eSi8SNyer;3`2j1I7FHa z+rd1rGFlC!zB3-+#e9d?+6zRDvp$yKF*X0et|MZ5B>j1a- z>+El5dda<+a@XLO=ATR7w}UdA+n=hY$Pt0#dsypzsFQN7l8v4s@xLlIoLTTqiu}V+ z`=KwqH_;OWn_~3g8o(Q>djx7>xG>&cdNio#$#;KnCSh5x-=~cQ>=Y*$ak!^7uf_ru z%mZjXyUp~lgRHHrG9#Y9bTOz^zGk9x2Nxf;vagV) zQ~sq~Xim1B$DVHOE-FKF3QRyQa+9#W@X@?&Mj zZQ9ujV{ve$C%xo8rQjYF^oH5y=zg;81ItJkZ={x#W0cj-Iud`^qpwEUoAZ zDf8JN+SXSl8rCi8C%;y9-lA3gz`|pGp|XBZ-J^e|#{I!1cV-t1=r6k)3^xn5rpq*g zGRTpt4g}xz*+4-90gsz+Q;&f%QR%t=j!8Aai^E}Wim8$wiw7_VJZY2&CV|Uh7pj2b-p3JZ2o`_J9(aA|QHqc& z5c2J|7i2qJeyNy?Y1MGKT}eAj{YJn)vKxBHZr2K0O=eXwD{q*3xWL(q)B7$3(wGC0RV9OW~-SnZ|2MBurbQhXwUBXU`d>s(CDrvm*)Y(ro#uGAy$oFGu2fy`71SGvp4X4QzBX z^<vI1N3RJNyYz9w@=-ymF@Xd47zyuNT*Wam+35sv@PC99l2ddr5 zd|nnSH=ow^)H1F0XSC*1kg3q)G|epIly@~~w;9!T9HS>@^q1g3HRoYGvyM{IJULfs zyOB=KlM`zikUBZexQ7`=J;cjl^^sK_ZP{D;Xudq44E&uME|9$|Y^w5{u3eH&v|<5T z?Z1+aFOXN1sEaOHpsW@ZJ{%5T`#s-wa` z!0lYApur;PYf#eHTTx)!>+(|nMu7u%GcTlb$?VT5O} z1ouI$Jr$lK$0aaSSC6KKOJr{CzQ1CNaCde+n7;u|NGZmTAYmmk6P#&Je=GrUTD6Hr zlJxWVvBL8*J;3$*VZYzny%Xst!VY};qjj9OU;K}8K2|7osSHQP!iZp+yRB7Xvpx=;F9(*ZRC^P@2PnSche+NJK#ipj^zML0?IubNc5MZQ>5*^4Wr7 zWh{mJmV6Du&~7u0`&u@s->nBY(aGrsEa3C^%&7Syof&!Hmrg6Rx50GcYuT%Emc@>_ zRCP0juLSGypn)r41iSGK{k{_R{MuFN@k+V6X3Y{iZcVQWnydYPY<&e-R>}82?-djj zxO0^bNf8wk5KK^z5KQduZc(rm6%3ZeSXYm0#~Q1yt(b@fc6Yb;6$1>g`F+lPLEZ2F zzt6M2+?ly^&zw1PYR;UoI?RUDbM^O6w0)(#+P-49585tJleE7*GXWS3XqKoC{-mL+ zz(M=XqU=?2Z`~B~Sq+gsZv!n}El-g$_37pRW;ynIZ3xNCCPg_ZC)qa=uGMOIyp)TTR|4< zvGvpPE-hJ)$sOB|uC9kl@v%C!{YOrhYzL9N0oLNDQ53mBo+mw7Ot&^*_4TIoeH&$5 zK^WbdYWypokY;sVuvs22^%zbQH)EqIx-sMe8=VtaiUpm2$Rk!S?Vy*N(c4QSa^C_! z?c#Mba*MpG8qND)AQj%cgy<<+v$^+wtXb}+NPc~OK@nSF{a3h4d$)oicz|1Ng*Nc? z9Hnf7NU(iL*SE=?<;xS;NO@_%@Pw_@U^{$vGj0=YhiUrtPr9^SZd2*$*`hD&TP*^1 zq595ajX&kM{u(DcErw*$pA@@8_UhUel^RXM=Fn&C#~yOTuO-cP@;lcJe4z5rnj`v) zCyUubxu3<^`r7CMAJG)EMf2#&4shY$+LQ54tlvrVD0Zi8ZQrjLIsDCuNCao-K6V~W z+9})F*Z5g|TpzljxY}hNZ9%m(e<7XR33VpvH0A7+%hx#iM=`2Xj_D`gHH1-ZMj;#_ zdbc|mky~+x`sNF{`nf85Q~h1&!{QI>u}ij2Z2Pm122fec{5e zx>4A;T!B;OdRrcL5=Me~*0C$8SU_Hc73f;r8R8cX6zdnKVIJ zv>cg>C0%3?u%dErJw4bfyOd3vi`%}yL#0iIQ8~{gWuKgAbKoV*>qtNF0&u~ET5P?q ze@Sci$(40Y=;A)iSfE5X`{Z%T-W1lbi#u1N*U_l`a$U2H&jGoOlxRfqLGbqFzfrY=p!fF@4Lk@L+_okyJScm(Mb-f`&FZ3K z-7;X5#zf2FN8_tlsBZ<`IVd-k9EVbs4A`O%%hQkys7v@-UdF*G;lJ0)_2M3racy_k<&DKO*;a+L`>z!t065lRqeEQ8EP{h1N6i3H3M% z?cbZ`AH_f&C(zNOP&Y3+(5s^$2BT?Yc}(u>TFdjBfgvV+G{FSP$tO6~3i}wD5xaQkg7#xyBT#l?BFQ7edps3YsFt?PLUsLC1GJ*J~+?HSp%OMYxom-=nU5UbKSI2UZLF*hh;>(fx8 zF;V@z$;E3n?nhZ7%9sz-A79*R2ukEiY;80iM;>P}ilH|s_AK<|eGMr2to*xf6Dj9F zrGuJNt8*CKgE2Jgob2xUHNLou^K*(nG;?fm+3rd7aI{>WUY~q5DgVLe@(K^9jKN;6_F z4Zb4Jloq;C{uL;W(g+%S74`FXP|8(M)zBKW^(qEnzK1Sdg*{yt~!)LZ(=DJOEm7L{Ds;uH47GbE{&-^++;(y(_Pg_SdD=_hdg^3SGgE6zxJK?*l07 zx)gI??t?AGE%)KfZQGwd-iI@{a)0uCAbX15y*?l?`bk0#BBfGI?#-q44`h$Xyks4; zE{&%fCL`Wfn~c82Uj<&m@VDyyn)P0s_qwls>-nKDE9p4kWv-|;J58Anz@}$4pxg(t zwM9jlNBt%SX(F6tD*F(WYTK9EJw#B=p+2`A@-LCUznJ zXE2~%@1)pgayv(pE=8U%z(1v{2CM;&&i~MnXPBlH$LRGl*|$=MDBj>Jwm8&35Spxy z)Y4t>QppxY#IW}!MLfr(SL{qPp2PJNdJO61p)MCH*;PDI6|#B z@_LIXu?Z>E^DUe`>(^1%Td1_E_8n%bk43uudjz&fW4tNq z10;sMH?8>qh3R@Co&SI-H=aW!^W`un>+#6z`s32dS=f`tAhkWQPJdIce7QmS(Ir?d zILa|CuF_ zBWR?(dukku%RvkagPA6R_~)S3bR3%M%^-;Qh@4%@UHvOQP>>eXptv)ru5HmKXA5=> z`15})WW5bE?#f%}*d8@(3mhFpiwoq@@}Z^>(-9Z^GkI4Sq3>=V<>uyb6Aa6zKpioP zCVZ5am(6QZ8k-%OlPxASFiQ=yA>U8(I_biAy7mdWYjqnc^H~nJnAw=8EWat@Y39|X zPM_ucQu7*th8K*a_Fv>KW$(nG9?ITi43C3uO5LXHFS4(He8+j|K^4Br9*J=Y@NvK_snjHu(KNgUe?6O1;d-mNf&;KGMTWM%4aD*w zXsA>N#9_Q|wX+~2Mb1<}C4T9`+t8{gQaL1!wtbTw0#oXiG}?n*CJk{`+`&?XY?qW(Rl--;|fF3n`7*iRJFYn`A7r=sl6lQ&hOot1x zkfH?P41AE(t?c}2B2U_MmE3iripS~*22@=*1Vf1hkAkx#4WUzbd)!D(ubwo7hUy*KLTNNO#ivGpG`RuWE$&BHOc zmV*Iy541r-?GB(^4R-a;Tp$9;@fxCJy=Ox6^`;4}n3#gb10f)$lMV1AN95}70NkRG zwxD5HB0OKiE~Cqt$mdX8@oy@7=L*!eT!BN7fTyhfB3YFX)q+w=!S$YvLudHUAKQ%T zm|qHb+fcnuu#>aH?YIRBT-7Y1F(pK};#O7L@l76pm;=D{W(b`rA?&5+qv?4G;Vxb7 zN@a}2e%pK}1M3LooziHnmo)1*OS)?;s!1#Ak)?^KD!F#0dM3iYwn;VKh(E4v7W9Ca zf?}v%ER7|Y)*S&0&(-5+01R9h$q}e*lJW>{Zf^43oaUH_jurv$Id^t8D_qaJP=SeX zldQUuLrD=(Z4Pvcm~3ND4FGK6y;jem1WR|_KfopKs>dbw(2>5E5>s>&X|kyZ(lw;rrlPv^t^?(miYTvSTo{PeapE*so^T`YO*(rBH1K62{aXgp8RJfO%ZO{zKhtTKxfm>Z zm_T1c21(xS$X9(2k-vpVmaZ?QbPM61Xtm)hRxQu!XP)x3pj|HPgzXa_g}*1_?-2Ie z#@E8rG_9sL4*T!Mkb+igk4}lsn8)v-5H6{>do<1DcN9Z%@(M9zkS_$pLOnA@OVc56 zfR$w|7%PIs^W#gIvmF^4L_;lwm!!U>1(xDZsX+?)$ihzAR)eBs;VCt8p}{hco!g3L z$(Z01)#;fmhDrS_sGSfs-0wTHCReD=NMsWH&j{v(aSw(@r32D~e9p36H>NMj>w|SRcTOL$|W8 z0jCft)!Sie+^{8R$l?r=K}vLMxM|$%g|*anHPx~g?(L=`X#PLv&M&sjM@DTeKnu<5 z4mUB<_lK%w=mfb3z&@CjRo)3Wndqmn9+vU~-|olp_nLv0)|R%}iwaU!INh)pIO-EY zAMHhi?TQGba(N9YhfEb28yFuzRO2qx%0UF`*3e7`5iYHaptBC5k(p~19*~K76&wH% zj%JsgG&%Vh3)&Gb7*+QFN9*jHF6VqG$WLBN2qb5q>zueMBv>itidQ zJgfODIa^9imS!N%|FpY}Dpr%=N5D$s_S`52Co7uZk_B(IN<(_=Bs^-aV#8TuQ9iBm z`7X#K+E^kut_Amj-o+Demha7y>|q9n#lSzJ6i|q>s26cDA6n*aCsE4@*K3VK(-;W) zQtBd(0>eeijLY6A%?~y6lao8*F9YA(SA*?hL;_5a3fA}<8FvMz`f z`bf2INtMb&aP_D_P0New&UfHAZFlAGu%y&OUT?f_&- z73%4ZIa{}c*13yLQlmUF_7MKI{S?SK=-a?&FoIN}|Bduhx38ck9->g%){dHbigVK3 zQRG}f1WBisQ0oeiJ(HKwqza;r6w#LURS=OJeW~*Ta4@%gy~J=yZcEF(#59;?6)FlB zsee30RTO8Wj*ZC5Tg;V4_oH>*=sqAg;P@>;b?PZ5~o1`K@4&SZ|7iuEY;7NCiw{G zn8PKsZ!HSP8ueg}E43XoSY)(I3z}`OQFwof=ewq*Byen)B#-j7Q}I=Kd4LX zxQ3qiU}AblQfXgNPx6eUM!q6cdK5vw`vRx6*3fQWQNipV#2Di3jt%Gunwh;o1R5U8 zHJ~b0#VE5-H(qMi?OM@>s*oWQp3SCD9>GE1~i<#kISNgd;Xo!c;R8U=fEj6<&@Sa?iJ_mvbws)k#K>{iA zozhPSi8!5EtgH>?Q!R?DDJn_z9BFt>5nQSR%t-Zg71~h~%)$2tDYb-a%y^zzDA>>| zEb>E*OC*%SnvYLufb{o_-`DDk5p2S;{uUnwV~X`&&PbmY<>&$p9u?O*>Ek%s*)XYfEVSZ_HE2j}h>u6m_-bRmzTcq>wZ%lY zE#*G*&7s|OqigV*MR1SFmG?}axCsg~llz{A))7upgFEzl9Z|RPE7UQovVES^ZSmr}P7(bIWw2gZ}(7E=st$>IVn_s|La?UzIMLPWUt#v9uFCm#j%Xm@jH zPRRLPHFsuw8O_shU!7KsV(KxA>p?^6VY2%s(!zT9pyfcytOuEP-I%V|6E&rhZ%Nb_ zbI>hhds=`3nA0u?jq$lrc)hIuY{&3%z@v63F($P%C-b&b%h2}v zqNZY9kE;(Cv-8$h=yQD$EtS4P5uu`i^vs`ThKc~GXLC9bDi$;x*9jQ2!U{FyJA*6m zjfVV7$Ox`KsM$zC`6$xlNRt$EPjwG!nxvY08kD_rJgwFe{S}6#XX-%L!bC6WofFk< zAXZ6R#?t);!oB>CDAAQ8Gf(;BfG=Ib-O1xUg+DHxe@cIS>TNk=6#Pa?t!&8oU~`WqCbl#fX5~=+z(v;~{_Fa+qmILd}c>+q;i!Px_sJ`sXb|fP3r< z&HhCFA@B6WhC)J=*$7IC7New*HuNPLba#Fsxx|QZ($PA!I7UpBhJ7cOM&O5|K2fbk zkX!>5if;tc7;Z)xjj$j-FQE60#BIr<8(nM+L~m8-bz_)~iE!XHf%4sTAkAqaE=WFK zsAp4X$WL&tq^Z~wFs_+Fbh~O7Q|-_MH&%3^8ukG@8LOFwk`8JbV*EHDMIDEW$(o4{ zx~gyBUW~?RJX521OZHvBMhNy)Pa=&8TMT>y0qzLVcwLryv^kZDg{6=-n^wk(+EPmk zx)UqHbyX}Iw?K1qj;i| ze03DpS=^J-no^4{&>2b^(ZVjGdWnmL`E;&}xK-l)_k7yemFMnz`uVO5cj`AP*If)M z_4_mE`Y|RntvhCDa0lwy1B*ENGcD)=g>}qZ+TBBRD%}|On}s2>X3A&s9gdkE_=N&{ zVx|JV(BPipsxG}&Bn`s|d zzQ%io0u|t+oatT7Tb%COU-Z^VU#w}~0P(NO0c*&vq+_mnh|)rwDbvgi$PYwLBMW~d zbsGpp?ywb|9Vq5YFKnszAn|YM5?Q=h@2eihE#eHUJ80c1BT+O z*{|vPP;@g>P|0DUnq$A$Sb)yjEr@^*%N9pX8}p!=y{6btuR93<^Q}R}?i|xH?QnDp0*Cj&K#xd5R&=yV|S^ zO&*T5yXqx<9WGi~--Y00h5FJ?;7Dz!~O@vs%NF#)e-J*OK9!dY7PoC>fF z=ilQwKyBjL8K}@=H=buCGL{>mm_hBVows|TS+;ET1w5z0qrl0mky~sOm`2CObZivX zYyNsN9SuSr{*0=Qh8L~PGm04vsP>*D>TLZ`m~;8(E86M2**vTZkLlc45u(g}jDDX&tI?NOk_&QKLQdmE z*V0SR7`V;2=af7S+S$OxbZnehQ?B|Wo`y&WAsavkS)n^a6UJkhqfZcx2Sd*)K_|wG z^3{@eniz5%tL9pqDYUna9imfbFs}ylg;ygxE7VPg)Bw@pECI+y=3kavYaSt*|mM3trkxlGferY zr8Qz4hCZOK6Ga_XZ#5t6podnz+Y^p?K8qqs?;qqOopot-3(NrUduyhKs0Zb6mI>y1d;3@L7^)O(=CMPO7`1o!jegrU|#t-ixBz-9(&xnT7iJkGtlJqSR$na`O zc9WsoKWsr=CX1@(W(DX_OD(+a4bfz=Ao2HHV{{VquKaT12M~hTH;mv}ZxL>71cO$GP` zM~XXs_<)v96^>R*k&kL_oHBip#Muay|y1SC8xfQvcV^KZ>Bbvy!t3stw2(JF;Dbi;TLxcoYPJ2iM1m7OLU zh#PJiqKbS-FNRX@X>cdJI7r8)iRNZ&bC^CX%2|@rbZ82pd#K)YQArm`{ilm4<@*6B zKLoW+(;C#-U+K_v@lIN_GJWR^VWR8*_zFu&cpmp+0GJL=V>a6&zcA@rnb8hV^XVIq z(#v>*mY(}p)z2a>!vx8=U6Qd%`C18RnrSAMmS~+8G!j)jK?wQNcE8kD`^YUtgd{HG zuVE|mJ&4%g8w2Do4w@L{%qYIhHO=DnS!mMnfJP(jG>hpa@Z9_7^Dea4xBmIOgr6gR zK2PUoR;{)7Q%mKCb~jC!lGV^dM|V@i6zTP{^zOe2?B2GxKxwIBq_pH>y7aqfq?6`2 zQ?oSDL^{%rmZXWk9*fT7Owi=S@>+g^_Pl zY5!cvL@#SH{R8b+SWwkJpbL+?O1=LOsmP9>`v>GtHAD!^gMYe0ZhED8!U?e%Hq`J> z=nkGIY22S;Qn{q zAVSKwvqC^fNtKI z59y3%G9F%VfoV8AR2@gltN^qsMh+GQ>|!Aby@wT7aXiGL+}Kn2S%Ur0XYyc`m} z=}GFbT>NF#;5xta>t&3t&Sbd)+Fh&tl)6H6DEn1+Jv zM7vbO4e}|zm<^1pJ8M+mA5!c}=n--IXvj)XkB1|bStagBYwnPKl{hHnccb;Ip;&$| zNe@R&{wXlu)U#vt~le$jSaUQn|$cG6QZ6qguz`jrFPVLfR#!KNjs=r=zv?+lm z$+zWc%+8r-g5=()i0E1m&HBtvy0jk4;IExXSSpBAILy&8?!hGna&8 z3s!ap;4@O&9;E&oMSywvCB^j8ez$?f?`)$Z8$~yeg!?8j(A;Nnaf80Q3=LjvrJb9g zf!*3qPtZbYwv}T4WsGj6DgO%G)+N(|e?@<(-pK`#=4I_6FOD(+}HGJEoB zD!qmN+zfp(@d};aEFz?o&1Ag=9iF{RQ?`f%Y3;xCaf_&Ko<_xQW^XgR+4x^-wN>~! zJN>H>y_KN>XR7&;b|-EgE!_$YXyYb&w-qRoE>V+hfcijhny^hgZB(Un0iXR%UIc9T z-`29=vWRhIPSE@XTd7C}!M1Z5SOr{I`85hL$F+<&;c`5mf95@fd3m&PyKt~4&9a65 z&+lmWc0skxQgipwz3s3KD=j6H9q{eE^q~ej;HWsdfd=h>{_PP1LOi z4eN|ELO{~aEkR57io%Lw3_D=Jxnh}~|JVhEXCM5k1~*ztHfLzKt(JL2NB2P-#XY81 z`@pXDZ>MtmLFT<4(xCm&-gZ8s4f}yy+g0>@zo;+Os7KxhL`}1A37YHc+79Y}0IZ-9 zA_xzNiWTzi8=Mf(F7K;X9vdENv9g#v2JDJU>pfp^P@It7dNZASh&oPw>?@DOP4`%+qQ2t-Ch%G_si?f6d zhw%2$vTXQrYCoc<*`jH+f%7#wM6RlR(1Z%L>ye<{LwrZ8%~1Crbe(X@SPS5ovj(D>`u zwBj6WgAGsU{W%d?qr{zeh2U}v@m|x^(YVDvKLMWdLbcOutgn=;m{jd500C{&zZm0VeLE-^uu*s9Cee@8Ath zkQj<{DH`s<BAQQLCKKZ@;1nXxgZ!q|0!WT7n+iui-E{L7Uj!=5pbOp%tXp$6CCGgqfm)^#k* z`cLW2b+O0l1JrehuXxWQ$Mj+Ku@&vVfqmbKwdwf{QO!JmXz@aDB67beYTJb+gUh%* z;bmf-jLjQ;3mh8LpAV*yH%0rhx})zo2wvMYVu6%*obKL)hw!Zl1>XWO9!#RRTcWm? z`;q^)D|;L(om1M|Y2*iDKw6Llx^N53DYh}az6E_G@F8`)E!OLPqY`&S2g$W3b-g3H zN%tqyp*y0lRC66wyo(80xrn;lh5PGyBBkF2zIG*&{w_8K>}pZ z)OlW%dQVi>l}|r(kFB|~3+d&3u=lCU$@~E}*m?}3E)PH?787ai0|<|26KD@VA9+D9 zA3#?>w}AW}ia|EI2}~$*SSroYrXKh)nRpwSvqf~NR(-+x&m}E*1lN3*@wD<0yY9!4 z{bLa&O&mi#9>d@KU@T=k2Bq#8OF576ozAnU>=USSWqc|833%G|f%N=|cr0BSO=q40 zli%i&?iqyF`Z=`VnP_UacN9}j8*SUtTU%sNP4LyS^yL}U?lGgt>p9{)BTTBDu%TI?R^eyFF*AmY;^AT2 zS#-r{fhu-WhF-LC8PuA?grLzueTzigoSZxo6ruSn3e;u0$nOQTwd$>@@eAPW*+p9a z0=T&N8{K^&W=a0IKQ2euRkB5dZ2OM-4-6>uFtw#Y$9w_i&Y^fiin?>%Nt<)97iTeo z@^YZ}Z`eVeFGW||aTh@$z0}BQuf`;>G{W9qfx6~z`s*d;XZ;AudMRA2DE(_;POGAO zl`#6(YUJPa>80>(QR66e3$qk&}bL%4|cgUy1T=4*(8-03T!i8p#^h zFP~ASlJ9F#w|cFGCPq!M-P+4|S+p*<@IiK@DHKa6Q6`OYG@nZe9DsiM+zHH?Jxmz4e*tmMh1^g3_g;+9HGr9ruvixb;vdameQI{-+-k@{TyOkf?Vb00({ zSvUR7*eJsW9{{N6Y)UYEJxJGX&i)*YqpO2XlSdx5B^nI|W#L>PBAamu4|2mHj2g;? zP#>#IJ5OcaLx(>2h5X+ma%TD$>i=GJw66RGkfpW3)(gOjoWtasy@am6#~Ob5nWPU; zvtJ#fun*u&OK{852dEL55}o@X9IyeT{{U6e;~1667kzY26qgS<^;$BuRP%w6?dAQl?o1;|i6SkU@kJ6$~!p-)`q@M(kVhs7umkt~_ zLYF>?-=%uJsQYJd^2a@C|7W}uJ(|3}Ag=MnDBglaSOmQGDTm{25aHH@LjU z1^(j3H|X&fhy<5W)ch;9CL0@3xo^T3V-EW!DwoK^4&=~pfV9UVO5@)Ki)hm~G1|)h zG9Ye+9EzA-#1=BdC8_3jQP<%Vjz?=N)`)A_)CB(7d#up!-!VUpThY<)FkYI!Cb>{F zcDw`^q~1x3-)PDXf*a_IJ5~2?qJ%<`Z}z$&uP5tU<>tpLZA&e{lR9MB{ELdWS!94# z)1(|pI;D%54pmTet_`LBI;FhhD0r_h^EdP_wL@)fm=M=9piBRul{%%0l)0bI>69SJ zeh!&PN}%-k5Y?3wf6oWF#H%<6NQ3@}x|E$!+Upq15q0x=njuPI z!)oq9s%or+du)VFg3+wk>yRfBnaWHj*Yc33Ewe|Y$?i}-;;_$>{xnu9ncoX%MT3+7 zCJdsJ#)_+SbTs7{E7ckY;IKX~?EilCnCgIXI1PXO>h%LfxbsEs%;I-6@EL*ndDO>5 zad)f`tF~JeXLf!+^yb%=HxPh@~3Uo=S5{DK(`&+v#K} zrHb`OY#xSn3hT_FR;dYd(5d?L3YnQIezkT~g%QLrr$lDzgE#|#fyJqdxFS0;7mNVe z)C?7j6fmJ|)i;IWOqGgK>#DTKROwxP=t~W@_4;`2rWnJBYmfZFjB#O2n;S(5RCpDs zU3QYcnNl8DjWq*SFRr8^W{Qig5n@>NFIbPn;sGSu_!h6E)n-axWB@8%T4@wAWfCly#IRdu%HWvRG0U1xU$1LykyANcK;4;G+d9@Ap=;ot8O5pX)LK@2>n>)0Cx1Kd zo+cW3nwdP%jHRSn23zb}{YBJcs~%Ktz}j1XIv^`G%~yJ`wa#{6{q9sKWAthMv_}2+yBd*0%){txgT;`|WFeGV6;8VscRT>EBOTBj z{c>)c)&^FzL6l|s(QBbNTdnkCjZ~A!tZ!hxw`?I7MRAsf`%yjqZ83Co(D!?W{?QK^veTKt%Gh+7%BtcLxFfM!m$r&3q6JClHUQ z5gVwZl`=xgTu0}ul)BR6sZ_>V>Fi`Uko&6;2OyddFY}F(tUe;vb4aNhsaom=U?A_V{C5Gny3`(?7K5^1cTdecz zfkd{DX&&3s9qkkcom8^})wEZ_D(`Ds5}NN|_PrPM4TCPi$yn7{V}L3!)2i}r!6-`$ z+VqK5*(*(@rOA|MuZ)pAl4+2G(pq}8hYmX^U8JE%eCw#h26djoO1gp03NJC~1XV)t zFlY?ax}`Oko8C~m->$gyuhz82Q5o*E4kDg;a96ECo80KM1YC>6)R}gK{GAjV`vk2; zuHMJc0<{L3bf)f3;Gu`(X`++jQ0FOjqj>!=U9z=t0i^7UhucH- zF$Tx;!i#`b?KYJsR^uW51|FhrT1_L$E1psof=tURJ{?SfZ2bi+&_irGssnbsW8Gh$ zz)QARaLqf9>h4_K2-Uoc=gMvBAu7S}R`sH{Y_K8^F}G6Pc963RSZCbt6yl<|+MS@H>BS%B zgRo<~BYII=0Ac!A{Kb5QOUrU;T`o1{(xi;77#;S&IwHzRTdAydHx8j4u25fIA?JoG zOU9{G+D&nCUH|~~v1fmMZ#jZbc-8L@rf@f9SYl~3K}ugl$(GgQF1AUpwXY7wv2vcj zmptrlc+g63-qPSwpG{f_Edimb&UPK-z@A@P<0yktd-50JcL$ z=cXwS{7;6p(ZW>JFQ@38r!vE)0Huk8C;Uy2O8NkX?+c=WFm*QT*pAqE_`-7qKa4C z*9r68jK$R5OK~oH{uyo{{FMEJj_OaK*B zD=HJDL1U(FYq3FotE&^P3+u{?bZAeYmj z)>z-(LhmXmkmXDr7ois&Ddy4p?1#G9QcUBV^U%7gud)X1cMD~-rbnHFH3{`l*%^c?HKwd9C$j| zGui;$y!y1!PjN5Xt-Klhr&b>kag;CxU8!Hw@B1m$bZv&7e`h!nT|}mD)H6A65z{kK zL99dk>ae6CR=R{G>I@XZ-AOn_fjp$H=wYP|q9NG#*(lYVk2^&!DspeCIYX&e07li@ zfj02(#QKyMpx8-C_o+;EXyb8$LaHmXq`X&jwz^_p{!HiMEs;$NxeuOCLxzU}b%RXC zfneaUX~r2U;NKV|4h(`$bhSR63{t|S+{0v9L-CfUKL@ox#4N$h zbYDF|ku{X&4maxlP#zH?r-g{)!mn)g!EM@HL#a@{dRc^7^4U<0rh_#hmvNZuZcSyLWFAK&YALl7!%ARR-mr+)R>syv%JH!5>2p}k#(y!XlkBk3 z7GJW^+AJLNm~;&H{HZ^EphtPJb#nm}95#lq%2J1njrL|D3qA7l@NsEO*V)e;j}^o} zVTN=Un=!te9buCv4Kqq8Wy)O~l*qrfGQN^)0}wmU?Q`|105FpecxE#kVK}QE$bTf% z<~sdzx>{SQShjmj1jeQopX7Yb9umtsN+oH27}c%=!?R;pdU745hE96qMhEIbDf664 zx9Vb2YqTNLV8z3%k%i_bYE+Q|gOwPaOp}74j&94MyTMAeptY@v$-}EUCNTAYr@*RG z?Yq81EHMI`!jhu=bdf1t?RZYHy^5m=LrPLuh+<{juH^edn%myYmRw~EW8EG~2vKkg zn=360fzFrQiuQ%T-4xC)gt+d9MMIqqEKyIn|jq#s#d&xfnnIG z!N61srMpmFTao!*Q6UgHy)*5pr?gCLaPBS2ojg&M3$!sUy5s@3y>>jo)bg7vv^N=U z)QvR86q;cQ!?L4lX~#U7N_l1mc)$mq>f;I9(wnatnRWIX_&j7E_9}2VWnMjI-iT?# z9b9}_dxWPqqJbkQr9P&?VLa`uuXHe9zyeMSHtXX-_MwWu#ne+pxx3$}?MhI)P$jth zUc`LLyRAemD^oeSvpZns9Q=r$1qm6O(Y8?N&~vNP*-*u&_GR#YWSF~zB%$H;!%{~A z5)1EAh+mN6J@DtTH^xT6x_G;SEF*!zrdj+Z0f00UGgAr(Q>vOR3&y;r`98grJ|Ik) zu9Jp@QCVj-5t9GhS;o(XP3sVPehl{Ci;$d1Dj#=F3NJqn! z26pX2c@A(q4c>Q6{=jSdT)nuIoFhPLNjhpAp&-e!7o|n;`U|0dBfyic+fjCe(#)); zz`9Cvrp8o0Qt_5-s!?<#JP}*Y(eg+zaV-46c(kll=f!P{3xY?blfKWW|UG%Ck-4&#?dG!S(T!rq19aQrAg6> zmr#uvh>+t(jHjSQr)g)j(x%MVlgRHnvte(wQ4(3jD517<5lan*`_PLiv6$q;KhvNX z#aFuWlorKcfSwBNi%}{_X;0~4j1pj<;>+kU_MAMXk5K~B_-iDWtxo+!K8=(h*T%cQ zaIn&}g`mqHozCpiR}J_CmHxzA%B!c?SKNN&EpOdww9I#h@tOSL@#_AjtZf!U^6DcU zZlu^%?sfbP%!89n(wqlKW=1&f5;g@+q{8}*Qv*-)%5je1SR&js(~(LvR`y5_6*|}$ zrrKVGo;HRS-@P1JHo*wYx=~OQ#iL%J%~#MxF9amuO!N|7PH85R7G-Mf6liP|0ioy3 zD&Q&p2j|j!haq|qy5K3ytKTF}zTzuwYYJokuuONGD)r>$h(G_qE&{!% zax+Nu&lRY5GsU}XX2vg=1Bcq0OUs&pdM)iJvl(1qGs5Y5Go_tWPmo`8C0aVxiN-Zo zTuW~Ggm8jaw4%9UYqku3i(p=xEk03RbH!0b(4OntAm^4K=kY`I%G|93#Fp_K!h`g9bjn%yj&`S4FS)4Mcg?#6JSJT zQ2Q2`+N$Siatp=Asm2!0Z14zzj8|)sOH~V#@aaz5TPT56qe8(Zv7gGMW;7Pza3&Kf z)8`h-eCgF@n%fdfblyhV-x4aow5?>;O7VAm_5qmswh?LyEShQ67?hyXT&CYhZCWXw zJ}dA5Sonv*M;Z(@vn3F#{+b1ad>D!KV3zUAyT+m|j>sfqnDdkT(RX8cGw}DC49cQ~K0K zc~R?{17=VjWs|8Qg+h>H12eGR%%aTu!C7pNr@U^_s!|rt>j7~4x5h>-!A9-hl4Cpg z<~*ILPCK}Bj_;zBb}-luU#EZDDgJf7OOPUbT8kwQiXd)c0V2P47w^RTMTt6ZqJS~hD_8AmNyFPKU8PAo=|X#@Qk{9F zzd~2Ju@?s*kQf7Qu)>Vq_)|?aW^Pl&A?~HLk5^;r7X!fpdi)Ej-a)A-y!ebP7=(6$ z!}srcG_ZpbReckK7&*AP*ZdNGy4n7Y2)67hi zq02(+j&79PQE_)#yZy(SWs{20iL7)fBjeRzWKZp=RFenU6tiGpcC)&m6BuvR?c~}? z@oXGz`jsP>G~xzc5a`IXtc97W!BSDo5oAa`l%ihsE-ur21I3h;a#WQin%xQf^n*@& zDdnc2LEWPF?xFZ+bOz|8OAor(NePkG1d`|s5f^Ajl{-Vt`4&VyIxE46)k^c+6mx6c zbI=39f!;*hh%(TFz7X^uI zrGz*#9<^F`>su&mS{XTYfeukJh-!6FyvkU%V0S>FYE$?D*J~)HOw~ zie}%*ud6ad^3S2=U7@@!v8E$k757qQU<;|OR!~k?#n&nM`v(ozOor&~CkEAl-zl&g z7RQ3K)V>?|t+y|Y>!x_gKBbD0fSD_NOk27EW4#>dbvLDsl>C?~cURmjrj*Pt%sH!R zl%qbTx9_f$g$~=C2KRvPHu5z6(*v3TOu4%~l%Y~s4mItmIEp7FiaTaHuknz^^i*1x zI$;H92U*bNo=TwkS}$YxYrjDEsk@EJ^@5Zr>p)F=0e}XN==WYQTVH*mZM~GL(!p}{ zu$SU5b+ja_-pWEru0Wf6V=9k3(9_;ZedinCU(l4IBT^fCYe(1~W;hp-MN!VZ* z4*UoUS-VTAF{`TJ|4~njjWGTFBho@S4Dhn0)`#I%#lpSDcwZwv^>YFJ-AAb*UAjwm z`Y6HWk_+HM{1FBOLMzdZs`OQQNtOjPr!O;wkCfXNyNCP7QT2W>%AS9q^nO6m4&0&J zPl{$ObHWg5_587n!+^rXMi%w^zvUR_9`kQTJ+ z0f-N-;M9iDuB;FQr22lQ76Y){(kv-%fZ}K)(3m}zH@+~GO^w{>0Cq)G95_kg2k@ryz?liY>VfQr6kO$EiLnWaR5% zbFL^(^uBs9j~)(!@-`!nYzHenF?8%+YMUtDM{q zzdV6F+)cq0FjVPQ?~B0ZsJuJMG`iQkIru0~3o%A1wHt$7n>zNdUVN~$T@41=CfC7;5FDMzL0GMNrndX|a; z`KoE9C~mmoB7L=_KZYwcEr#8MaK&6+lw8`;YD&)ZB?3) zpm-(TH^U61S?|6Ajg5JRff#O@1BZL~S(9fBl{SgP7^(x$K`Ck0Gx-%>BMjC0|MvxL z`Dibs;sp*2{n2_HT5BEe3;EH?@HzfGyDK~JH_)%!n_s9BHT`j*%H&LxnbG92{fxSi zGDay!6GkburL&7EeUwtU{QhU!BKJ$t8}P_RIy#C&%Kcm7?;4vQ}srG24VO=L~ z8}I4oe^P6UAjt^Lbrz8pQL<2TK&qdfYGd7Z5dM&#=y_b4_K#K^gR%^@>n{C*iS3Xn z;4*MJ-A@}{sD>B*G62Bt5lLmnfS>hxN_EF5K5_|ux2R{;yQtqXhJFh!{?cy&ChC`d zXM)fFx?KB5P}Ue_hve~u#*bC1xx9VM90muYd2LVo_TR>R!WjsAdNfvXbf0aaQNY>@ zzW|a7%?+60L8va@$Yq=oS+*8>D3l^+kEpYJ1z8?V?%){iJjcE@LC1-&3SH|O`qKntR%jSL+&;Dv!r7eNw~*&V z$Vat4MNI_L&-{ZXO$6`$>Py=vf(hJrr~6#q?mgK~QW|%tY*0oxF8gyvfPvhAa}WLy zCJX_P8sFXl&#oa$r~V1=xw1mU^B&eR2B}Xp&wI-KfuGgJpA1OY@r?FQQnu+bX-Faj z@umgzPa@=DY-Ku^2$r< z?|HuxyznHjr(e!0I(AbKl~t(rTZVX4CCFnq{B3N9`<})o{|Md^LgHW_OeGsvJe9L= z(VHn)O4U-yWhzkA>M(Vhs?@7Ez7DIgT3%fEqd>KjLsox80!xUCyFYZ@?;k01s7RCxKT=0D>QRZLd=O9fVjmFRMVx+N>FvhN`% zp%?csKHjK)xS}f=Us~mZS$cqNV$D~7=@=Vf1?q&H_ZV7AzBaT#V7*94OS%eRsDS0HC^dw=X~Q!p?*@v&(8n(7oFRVp^7t<+2%`U zy(!eM;(yl7q9Zeurrrmqet}Ry!UDcY7$bpTawvx#V-&e^k(Q5CEme+c&Qz-S#De-` z(gq*1%L##7aJ?>}lIEXKS8;$5A{Ia{wir2P*VTt+&4j-z=mH1#(e>v6IjsNxINm);h16VAv~NmDREVM|6-AMqlRdI; zhj5VPWJ_*4Py2SP$8zi;`%?B}--%;s60+~~eLUyBEwA_Q^ZTdnYv!73uDPz~zFkc- zw3MM+BEd4uG z_6+TV7?DW*5HFpk>~R(P<7yjRLzOxBTEZ8jEIRCpaLr-D(|tJW1`ePo8}%>p)5~6U z%Kq$H9bJLh=oj}(zYb}iiwk#SBZ7(}wR0-fY^&EW;;OLI>SY&LCfDla(NcLU@|h;5 zNt18TnrX6|+-5pnr5}vi_E4{j)Y$2Cb(-ABy$s4-8Pd07zy!iqBU_eh8pmc1hb1Uw~Wt@dquM>Vj(=%Zk*30`7vFd@v+1ymI_>xc`O!5BloqkQ=uE-y3oi%5wxzDmXW zO|mIwhFm%H-WOQxP^$a8xjj15%;l+tNka1P_H5stuo(1?sk4Pz|CM3mU$W8P`!21Y z0V`)pBwe2Ywa)($eVHLg$^9yD03dS1c>68X=a!T>6JnrC1)4ci?&=?B`5IC4F@Sd; z4q))qMEtnS+G-*yIb!b1zL^>!ak?kD&4Q(>hbJ|hCA(WT&%+(P*{R($a26bR9-gG< z+aEn>=Pap2$|N+El_7wAH4W3xy^ZFPrX)>|d?ICR;*{!zzG%~x6 z7oPbUm9IB*feUd@t4hDRiXJQiUh0GSpTSdfye3)Bmk&wT9xy@%Ti-4)Y{?nM#e-MK zdV%ci*ZCHM0hRz$z|(`U{r^v#Ox!>n7eG``)zQfXa z`7DH1h}uaF7Rs%qEq~w~Ij8`8qUrcT*{j^8YVba1XjS(b$La^RW#q^kOvMXj$69sn zfi@0V3n+fIg=vgd_N@u3ga#cd4E?o6gWZFl_p3%z;v%`6t{nAPBu7g@gK5(ud0~JZ z`y{myI3~;|iqUQ?Cd**4{tMQfrG+>cI!@r4+J=TMmgAjf-Ngi~$D6Vd5T#81`7wzV z_36%HNHpy)le9#>FD z9KXye>`B<0I2{>l6_;66ZMu(|u8>3RZQr~x(30=vzxI{4!s1TP=?>FZs~aM9nWpYgc1+ za>~(()p7-!75hKqgTlOE%mARCUPPZ)L*5>~hFsUk0aDW}YPtpz@1GZF)Ee2<-0=a1 zcxFc{aIws;)!*Nka+0p&wp22UKCF>l%5+)?@Ym+za*{mO%H>Oq&&F$jj*GLX{#rS* zOojijR~mULwx#K7v2@p=X|I*%NY3|Z>N-%DM+&W92i0JkLbule^k*ydc^!z*gUcEb z^6Nuh>*ck&!*pi7T*qMo5*p#Xt*5gd{|y#_ID8S3{?)Q&$^CDpeeW;b z@PM7!Mi>8vz&PUxmEC~->amS#ZIGKtlb+F}4RUoaDT|$f`Kse~7K1f!b~J!I{fK+E zySDsh*YD8X4Va$GHj+1Dgx*K5%`_PL`y0D3?Hp8sd$dsZt%c%}g|A6bVN!CG= zCG!!0&sG&Rn=WpaeIq5ljfJ!?c!LNy&E=+z7aTg9`B=U|V10^0UA^gVMLi^~&^~`Mt+LVA~eChhvY8%>BVtIJW0`WX^c6 zN0^3At!F|_x57|WVtiOS!QPMLZiEtoY_PEe6B~+)Y8Hynu)AX&f2SdRjDIps^MA@QP6$;k!jTPX*=Mi6 z*M)(q3a@>UTDsshqQr_h2nQKhMe42Tz}IoddgA$CLIi+;^klp2E{?zfzeEQyGYHbLpQZWo0(+xlnHJ4Ee;j?*a z?nZjQ3#N+jbrh5ZGS;;mwa|zN~ z&;3nXcFSk%4z(^S_6FIhhk^~dqlISxYwd^8%smjVsJ~>CqIYJiu<;PN!=JaAe@O^YkvN?d|=^R6K4kspx?0QEuKT)9>LVKPK4oD^)y*w+4Tub_eCw6{_g@i}(sPD6>%^^9h+`SY3zwcW0 znVuYyy&YXM`5oFSVcZ^*c+q&V?Eaxjhh-m+uss~4fbqb$GshZ&rwwNf{2t?6zZ&3VI}v%W>Eu_hOpB)lYv@^l^EN z{mCUvvVn;j7eh>4Heg6SN^}dIrN4+iAD0{Y4covl$kva(69H8E;0yfEP+-Y*2`jkl zhtmf)Pous$AdSVN=${|1Kr8LT#7eOhnooC}V% zWj$@q1>5;|9_8iA)sr0w8sRc6p3=hoA$UZab#TM!&CUk!g*`T^cDmy3KH7)Q z$3IOGR!5Y4kH|}V_H7lw6plF{oC;Ou++jBlOvHe3BPsO+XtDog=-eKNVJx_i01fj@ z0&P73{BUVZK_?+P_$Oo~okYfvm5AMSFv8)O!Ef7$JT8qMb*N+hqRMdtuPW9QJ_bMiH5QUqoFE4$dtz##)2 zBHMHHcx0!7--PKe84TuO*V+T>6i!f)NoOWd%(Dci)z3W>X#G*yJ6{}NFtKxsWO1)G%ei@d=6_e@fWqD=Dj$sI0_)raS zvH`z<0G5mSL*mcjO3$8L@(;hPX5yZ95r7kc_MgM(+7)b6gD>>qitOXk2KNmB3G;5e zSE9NP=O<|RsY?#0h?R#o-6~2V@P|Cgv9dlJ3dU90`tah;@AKXx^I-*`RV^ats z`T?)`8iR?}sespk>i&1HimeaCSVD#AI*j74$)_c|N91rF#%U9zk6ecVSf5TFH)M~} zE0>#^q{sT})Wac^a6_&v9t0W2hXZZQrSx^fFJb>=c3dXs5_&z+4c{GF_*d zAXmTDq+0jnO?+_WJwy`k{zx_NLmxkzLcQy<=RP?0 zu9NiPKB9@s1yRUm&Uz4fU;cI`9 zslJ!umXkGF*j!If|C8OzZ8`kL0Q823<6ufvr=B3s2l89XR`7uW1JAu9_lH=AW0h&d zLs0+m+i-{=cCTSHfVCwW zM9dj>ClJ^WSRmBe3*m`HmI*&#IB#rKca}Ncs{==JVz$BJ%w%@?cyd({!4f%y`l%2> z|D8Nxl_Mq z*pHXpX#X?Fs9OeLzrU;16`75H8!+#=oW?<}&mp>e=s-)KLmSIarrhVUyTi`@Z=s57 zikGnzcU|qF{_~1}#B)24N0B_$bNUK~OdL3u6PIyRl~=>8bClTuQ~)h%H?IZ#TO>Q^ zY^k6~u4M0r?%xkS(oC4h?a5c?+#$ag0Ff>&DB*=%rJN`7A5&)hm~0Baw|_sH@j|{J z_1QqlFXh2WDa(F}@hNQFz#hZkqm4HL2i&leDI7(Iv4V?QvO>(Y4TF#^p(P09tGoUN z(4-#=(NvZEpQu!j){KH)$x8jr4lq;o>w!t>d;&q zpYajcRJ$2(9-q#l;-JEbufRRdpQHn?uq|PI=+!GE5f7|Dm0!#MO8+&dFR$fBb(^#R z-#@(0@CCk@k~_ajA3Sjaw0+Ay9D&;23rzaZ5RZh+lGhLr348tLTSR`vrl;AUsFOwvwZo*;B+kSGxy*@i)@h<#Zy*!o8yHhhv<1!6 z2j6H(F>htRpt*)->sFZD%(b9(nb5;=zbmd6r1Eb*npm`*Y}VRT6U*KA7m%zTHRqS*PP{?>yf{QiTHtT z_@laXr*R*E#aD;Wx(~2o)N4t(ALRCq&s*YK(~re!9*1AHUN?-wKgyw&6`KQK^ue8) z)0mHP#d=wTd5f(l#A#s0`3@W^k;QMgjhuyoNC=Nc>E~x!*azHZO5@m#9)6S?SzbkW z5yo8GjB0&Cly8=ynb?e`eUhtN_CaJh?%Fn^Q=jC?L5|4T;Y>+vI#>X{N+WgO# z>#9YaSv`Pu@zMZyD*?iIbax6Wfv{ep@2QK- z7!ZO?ycHAZ>ldK%=+5N+6_7crBgKCOwcjjg##b1eW7bl^R}jqEI8x&qvK}{gqQq~& zj+?*J_;2!6sq1HIUkqy0dKIXCt_u+UzOo=KmIL20Yn&UF{9 zY@!F5ny|DUnQ;iqxFBxs1mQ1LXfk)Zs4lghF;^9CWnz$15tDHPw_i6QMJF0a$xSIq zCxWCGeQ26aI9PUw*EXSlEN#&VPpeN0K>)P867}Cm%F_vZpPdLoWj>CMaT%~Z*bV1L zuu&Q|rlEnAbMH^ClJJb^rrl$*^Qxbb?7UZp83rw!gkdhnlrSk=q%kMREEofS^j7r; zu#gm}hVnJ=VVNw`?LH`eBSzac%7L`x}i0Y#Y# zZ>i;bRGSdaeov806$Z21S8#75;rmO^umx_(&^1A$n8k<$qAjLkiqw2Jg_RKY&L?6J zMr%FikQQ&RnM9)T2#3`-#%YZuL~Y5h5p66Xyrfm}bg_h}BBk{totbcu&cuI0wNP&r*^5S42!BhZm$pN0 z_30lA;h>ahVA!FsIYtNZ>;`npLbypIV(E*8s4TVWW>}h4F%)ens#*@gzGEUdLw%&B zXfFK=7HKJbrMao}(NZ)J9a=C#{)_~>vyGaS5>+La7BsGuh?Hu#pkt*(n6$V#Nu@;- zDZV*1FO5C-Zccxc7NOFUX0)R;UVE$*-7k%=*gGK0wv4dUxzA0aj!c(C0QtYEwP(KVd9n0APol@)fvF?H@KTla^qnKgX?!68irKo`iJR@ji{|utN{5# zAD%jfXU|^c?tf97Eb2O$r308Nfs|=H88EP~4%Q4rc;7KvDT@`Q_8}96+bh~rf)EvK z<{H|O{0mgnijRj8_qutnNNaYXpETpdRJo3C~@@2xsJ445kAtRGjviBE>i0Qq$;9Ix!0ecgG}UUswJFS zI`%08=gA7-F<6|qW0$vxRyw@KUVDfP4=h778 zC>Qz~S7>+JUsuR+A9+ySeCi?L0wKa9|%OculFB(hMsJLY> z%1dp1$=*Q(S-u{pz3pKrHFprv(v)DDkIQui8!p!fMPb6cpRx~Ep3sLc#Z}FY%+@p1 zOEuYygxc-`VAU|~3eJqq9PXPjcf`6Of*o@R*@ z!<;vABfpseNS5(LliNdiJ^aA5kv^=t8orZsE~1WP@|xr|gg zuZj~w-=rRi%XDL8$$j;_Sf8jXlv8GCaiXx|gAi|U1?a%H15&E4K1&N+L_*cQ9SzIJ z>E3EVH^WrsapO#)VJZxg25j=%LAI_UQ2H>68n}u|R$)#*!tT5Frcthdh@mcY#8nKH zhqh$uTkzfGV)mBe+(eXg=nYMC6O(EeUNbe>)Ot^5s)&O>L}xujgl(R~>+f_0Z<>t5daKkV4^NRUtqZ0# zoi`HGrlQ!lV`4&M-t zqy8h8cKV7|WrcPP_1i`Us^xOYzLJ=xdrWI9iJ{Uzy~)iFn{^FGDf@}zQesVVtt_gR zei07Btu0ASYExObN?FHfSY;6*t$sm!DuclN?o78Ui>}h$vlQVkg3Z^S<&`>4|JD%B zG~XZc!GN>$kH4sCQ%k$UQZK(h^eDac7lRy1qGWEY9`$-P*%kFF;Zto>#B;H0k`S{+F6-ZTh=yA&_-Q&_7kSs9wtK=KWu?=v6)FA zY5D33Te1oeanjX8)HXou5H{~20$jsh1K3$Vgt+Azh|L~3g<1rPwvxvb+7u{yNNsOZ zxgb%s{JK(rjY}GpMgM#QRefENl7hr^r$1q%C|Ck*JRT9Z5m0vFk))(=*5j42Is8itppXQF+6Wd}x z(~q_NxmC#XhmFc=h%a40M{_SGCY4P|i4r~~>qF&Imrz8MsNwYC^v_pWPxu`&nPzh> zQu9n`dX)IB{P`-TCIxN)Z+63iP55>cvoQj5X0Hc z>N{7OjO)_5eY7Q7L|eu7)3gX)?eKo2ixCa%gZHtMik(l)?(xY$|JrKN73vftoTU2K zX;chE-U`=gQH-c7&Gx5TF(RV!(#obdQRSKSgaYgj;)|wnJL74=P2MhjuqPj!qb+EN z3pHpUqHJ53e=bgs^3@rv^^p)Y#>LT+2EgWqE$Mv&Ak>jJz|C9?4tS(W1T-z zlSbf@eS&CkBT>o2<|7jc%_R$CH{cTk-zfnRLpzyUJ#0_=8-cmbu%)|=fDFMWvm6>T zZ8%*-72<`Luq)3R!ZAZJeoXsqX=)cQYFic^XWyLFk|0_f50_rb??HGJ4C$cTe~g7#1rf(f3k$^} zY2il(3AA8@76O3Y%Vav(O!$;}XM?A-=lja^s+kCMySp0Pf7W3M@{!$!`wEr7*y8q(h_gx=n)A#Xb~;`HMdaiLFB^EBU118Uk* z*m+)Wz<1d!p%1Sg#*Pj(7-!Ejy|<6eFjaRqpouL374JvW+Lof4lFa?nk6Ofr7N)ZC zS8d*ap0*S*O6mW5;}eW8t%RRVIV6uF<>Nx@xQrLg)WA+Ox)o4=Yz!S}C7g7Z=w>V7 zZs&5TGN^{yl7J6t;S?xeu9=@Zi?LZb! zzoTzx2fsvoGmN`zV0@x>gDn8O5RO0-RgL7eJBD!Xd*2B=U~oKtjtO;65($>e@Mvtt z1vQ^`C5ei5%h!J`&PhKH>5nB5z<3!o9F;PX#6K0od{7l%E08zDAD{9AjB?Z?>%M9j zVXF3wpq%!is>ND`;m~X|eQA$rHvdds9Yl=ux{&&G5Fs`h@XLS)014QkR63NlcMxN& zj=sh-$vtZT9y+z9dL2cj>bAGOp(ET)>fXAqihpZ|h|VZ2&7JXQ*vzlR=^wfwp%Ig1 zbqLogY^FsWVc8i}m-crQ6~ec;0qip?<4}ok^`18abLwd|S7ty?J;Fwq%Bin3VTV;o zme>$10Y;)Qymls+PB3<+44{xs!nJa348?@^G~TB6(#Eo$Pyw_+jn~Gro={FB48`h3 z8rKP8X-a>Z-$_Kst9GzR&A^SYIWskN9u;%~INEKeN}WZsa`jypGg0&5BnCDjW!0KA zqcgadypc9_#vDqz(235%*(o;cRdL}3qtpQ^pbsziQbV9+t*E%Os8S~Jy0&1@K-9Ms z(nZwclWqU#0=YX4=W2BkuDZ8$9{(i7uD$32d87F?^6x6_%kS2IWxa*hbHY?@B6&gY z)FYJCRa6(F7Z^l+h`pL9QPq@|cLk9e;IQIkN5RQW&BCyNzQT`LOg2Iy{dpIUYkLo90~00i~H@z3Z&HxVqAB(mr(hU)&I zG2O*o$$ANON)a_&PQGFoFIER3or)`HY6bvf2GTRyk|HX|UC^cQz>k1ws~mcmB8J)N zsw43M9*rXPT4Of%^O<^QX)vC{T& zRHvs1ci2%GBIPce6sWn`@eqI^ zXnNL5#QJBk$&Gs#B3wOKr?N_4tR6q|xfj`Fh)9pH)r}o4Oi}?XxoXw<6wya4FEh0rYflh_ z)vk-_X&+I|rBa5U14q%GJ1FoV`BNgrcpkl zh=F2|S)aG)MJwJZ4)pIpVdv+YsS$FH<$%_ZuU>xxl9Cx?6PJ87o=r0t5C_l#S9??0 zLBg^8S{&dRmoX_2o0QoCQC=W9foi81sy9e9v+q0FK-4C@w&b^_Sr}rG-_p84AZx1@ z(5XQpT8G-{zl&Y&J^Wr3hxQ2@^Pd(Y7@zS1r>T{MknJ1GyBg<5kA4^4HLJZ~@Z*wky62IZtr4g=G*I0`4@Zg+-@q{dPkrzvB#densAFl6sycLI zHfFaK7me|bEh&1Gs9l=h1emZ;gJ)32C=u4YmL(q<(+V<8@c6ro^T%V8qhKQ_!p9&9 zzP`I5O#H=b4u^g>#1;qFq3et*7+;H8xP}{%=?^WeC#+@+*PA`2@@b;3?i#gD6F#Mj zvze~v!{WZ0Ca1w9IoyqQrHMLaxi%!9PslX)pgk3*L0auKm|Be%@fG`^L?egGl!2M1 zpcp9j-Hj7`_tN+GmVZULqs4LE3(}7fzE;C-LpX=n#6fP=>Btz-$^G*NgZ=2z0EW!& zLt1M*Hw{R^h!;MBBFBnqV?LHHE^d?&{n?^m2)Lk;1Z%pg(?upSa6JD9XHPja@ZH(B zc!~1jtz!;hQ}0YeX}F1O7}SXL-2^7mhvPzXtjG7mVA?2GF0g)f-!RH~G%(8QpQDu4 z0>lnQwpM3OqpxFyciq2nvsH`OjL({Ym)R7C;5HU&4NQ~8U?)%}J`-d|e+}J+xH0wV zkqLSf6#;q40-n;6<=iV`Ch?)_5L8Y-1Q}h+j>*G|J7R3i`#sGYCz}6O<8PEiNlw5H zx4<#rCm|OZQ?!fJf{hwORA2V{TAUkYt5FiXsO#`g#Ts7Yt$f~)Croq@NE9US0_TTo zf&%KyWK#V4VxtUF2F(#0g(NC&35*m+c13hiJs=8PKPK*i}I z9D5l)UbM5UI2kYsnP?g<8xKx@baK|M@q%=Yt{=?Vdo=VFS1m<6=(m^r@-}L$Hj zs_9OV=~PeyJw;3vwsz`%2rvtbaG0Kp$ehROW$HCm_(beOw6pPb>;C6;hU@$~zOF_m zYp>(qzrL=Y_B!bl4tJjlwxxeTkyC|Yr@}h$|9GJu+RF0{G(#^O+*))sz(83H2RtfD z>QG<;V!-}{BDH1&ozM$k`Q$OC3rI2JV+3LP@Fm?eQN`7D9X41W-me7X6MF$W__C0U zZN$Rgr}$~Y$@1(u4O*)D(!gmVuI@LVmT&C|rdu)FUV$L_Ne6-P#+1Hcm| zIE=UIKEee@Rx%mlV^}me*)=UX?WloukH=X~(}hdi6+EPNMrRI!H4dcXx&X`wa5*|N z%KevHRgJf*;+A%D>>Cc=(VNwMMu(=0VBcC+@IG(};Z3-1l=Ok_Y!vI8%ECSlRLfOm zD{`3ueLL(uCC-3-Y~o&8H$&93=wSHb%~Ui)luImo1VK)(-u&`~*@t<#@P$~hpl9l? zJi|A_GkXSihV(*(KRB~&v@85FmHx@Ve6F!!Dg#9N9Lq9UcLU*5a4U$CFSE6T9IZ1>Oc@FET5}(Z*TA z%h$id*W$f=OQV*i*lX-WEKGnF>IKMX#s#cdiayK|6%^febCX7yVJ{&5gUDdp5kOXT zwg@QehWBc^1JCsc^_eZI>P%_jY~i9iPP=CdFFDZ?mYh>~JrmDjb!%;UHd{D(mELGr zim+%{eO%f0hACTf-wgESMstb$=ZGj*v(pSErvZ2s@C%>r`3x37WhKvN%Iihak z3kh(x0umUkarp?EoCI#6#-_nZieGU3<*0Sg$h2BeV2*Cb*%`JMkEq9sn7&v~Si+5U zx2W7);ih{}HRnQ(%cG8Sg@f)94WBEj`dl5&gCR1W@gO5F8w&3(TJ`8I;p+bwi< zE~ue+K~LujCzmUM>mPt)Z0R1 zNZ47;$NivUL%r9jw1Py4t?5uWM>Qe&FqVT^ZloDKBdBnDa>;7G7&_)wfA$fR)X3Exm;aq$hZ2C0d3Xxna2VqjuEAoc^p(rR zA1?^w8`?mv3Rz(jP zP>wR71Tt(m6&e7gkO||rt8{3ADA%xcZPw3GJOKLn5e*CEP4s>1A&Q}7oIctG|3?SLWi*Je&NBN#E(?XLN8|{e19CI?q(6AXj7GQXuTtSpq4JzUAEz{8rBK6T;U*h%s5L`Lx zIHF6uXVA8VqOwo%6%e4%qSTujS!$vUl&2QpDqKg_<4-Uq>CHY;iAAEi?^_)M5_CH@ z%dl?8OmW8V-?#m-w(a@qIqI}XAOw3OEnOrkmhFkBzJp48nD!SzC>;H1-eM6`-+ZCA z%dOvi-{l65hFwNUE;!tEYK{qZ*%P9brb%93pmq28(Y?GQOL~ zhX3k|X+N&1$C_)LnD4709awe>W9EM}Hq#tHmU9GP`LjkqEeFg&zg-)QD`y{3TfL$` zmWZnLQ?(&SCjKfrC7%TyR4dQqmyJwRt7&h-kM-@1k`vwq?^`0X+3uNCutc~99M3a1 zF_LjpyuZQ!zJHiKzke`4!7rcxl4>p$yQQk9>BUmf(Q{flFA;kY3{kYBjcq{pT}A<% zRxxmy=q!~}J-HzVo=JLQ-C33(v7 zym6G7XtCsP7&HA(N?I<~yIG9U>`@9d2H2ij*yM5vZg7q$`w{@Ty;NZZ;x?L$p@A!) zK1GeAMJvP@-9>U*3Gdm6(Gw2?eU(~^}ULGnzarz=G#-Aju93)0sC8uOP3(oLnU ze~Ad2!qGgLRwV#n{7tt>w@TD@UxBN!$t}KLon>f3mDM_>kEWzm!lQ0yz6=T1c)6LO zm%Fi9-*6X(4eg=oh9>-wTGMMZ?Olb%6CcQVwRot*i`O7*t9&2wSt9~}t!@%ESTEK{i9NEOuNO6Rv3rN{5+LS~HG8eHTx_LN>MC5#v<1>aKS1^d%Jbq7 zS%_%>w!qkog4`&rPzc}n4L7i%b*T3S_&fijTN|L@y(Y(vVq@JDDCsHIMJF|88fh)V zx}-M$<(j*8%|@;J%eBthHFwnyGVdnrGMMTn;jX(%Z8nLHzx5c+$kV6o54n9J@*$Xv zvbhvk)mHVc&-jZUi{mxq{V7g=5BSSuM4Gqle-L@P1zB%~o48iyH^%sO9hsEgq!ycD z2(0oit=J4>(fCEQcQZ_RRxllJhADJtW3u>1RJC$m1(Is08Ioj9QU4(Dp~MtznBUs* z=B}lQ{~%EG6>a!O9I!t6^w*8wNyE2@=Jj*Vnj@U5pFLET-_^I5G~H#8dK;mRxYDzU z-hb0>d>_v#qyhvqNNX)XC;*8@zEQ0!mDwu(ln&(4jIA(y4uOY-d&k!`XaPRlI2cO@ zx5BPfa|eb1!&=&kgL_e<<(PVDJLs;ar>>_G+eCnF57pQPmzQ@ewc7@J>qF%KY!fc! zyZ^zk2H!YVI3#`SSWHT%28PqQZ3yQKyi2az(b=sbb=of6+|IElO&{)(r%`O~C(Qg#4JYnMC8`keKI51<;H$p|XXdR?7=L7~_Q z6AzHJ;ST@(Z--LZv|}e*=UwUcPJ|mrcc4!@#WgAEF7N@7>yJ7D6mUVEqD6P}2q| z)$bJc6O(c0$y8x3Z?TJZ?S&lp58d4hzkK^(B z(^PkiDjgK-rAAxm@b?t%2DB5DiKdI6rZR`yN-%6mb6$C0z1E=y2pgCBQ;U_6+yE10oCP)o?{5uzUqH*>zaemSKc7amqMmopS8S%Bq@ zuuuc~(!m@NsOWz;Xch>k&%xs%s{d7za>Y)`JBjw>Vt&iolG_PUMR%SOPJq$0T|z@o zz+u0XmYop&tb0u1A&nJU)1Q&kNzvYM^%|~=qg5Zy!^A+Dy|kHCLDu_8*wpJ(q@yRH zd0)OjPflXY4fRPmg*cc$y=l}b(KzA?!ZrZm-%SlT*z6J~#lekW*sWxh6_)_E*#jv_ zbD)**VtX36)q6FE%ukC*-71PZErv@YPtwuTqH5F1ow=aqPqU0BT5$LOx-#a!SD#eS z6k4@wRikWyi|{yA=%A65g>jsaW3b6gE4G6j;|#nhIVWiN8R1#!&rVEaTd>){ARi6l z3t0L%4EocakX?n2@?%ja=<^v-wc6{B=#_j)dxSZ|1GGV*G)~3sOIrIsExwi8M>|r| zS%lKsPSi9Jj{-_NE6SIf4-`i&Y({&iqK5%PDDTvT{yr<5D)@BaA&b=jPyV`Mb*(?X z&e#{5QbtWlBK0iT#WAux2UinP!z!MGTk3iarJRG`qkjk5at=&7wgX+||9@7eFXu!B z>pSiSI=P!cIk7TT{a4fuzI+@+{5Y`X7T4slN2aEaHmf3a@Ao^0A=eO&GW+9qT*akS#MWN-_8qrY1bUGzaS!O9i4-@g1oWzpw5H4 z3d%bJS`w}^>v*rOz%RaOS(Et+T(!s5x^rm81@XM{(%HW}JV-m7BbRL%6D~se3VH_% z!zlFNhab}Viz3wF(@~fvGLC`KIl+xM60JZB5%j$eZl+{Tc!)f4E=;_NUWKF*cue<5* z(_WEVxOw?<96g6;PzYJi9|DUuxo>_L=%UG$eq-=NpmAy5@kwHw&KJK5CbhH$L7!X5*#ts+v7 z^N;~KGn#97Jv}qM4FS*rmp zf+76%VW2LH`3w$gS{NwNW?KU#s^~^-Z;9&gT1~wr;=Hq0vZDMsj!$H|!s>EeD81_a zb%sg6VPc{ln?s*&Arhn12lBcNY2@v0in}d>s;z7anAbG+;mTLdAEMc#x&b;hZO0(V zEUszrP}`^%U1;NNalGB>EF(}^Psm4K=AjY4oGmrA$^X#Qxa4!N%_?jBl(lVBIsicL$!cS_fYmW*77h0z#m=7KeFhvqd`^o+Wb>NoPnOP>I~` zf=11nL}7PDA6+V~yDK_L!8OP-4@%BU3d<7#^5OjuFET0=#2THGTWM6DSSoe>jhyd^ zxXR@n5#Q9F`Rt6?%z)U;F*fNjJ$33>YXhl>%84q4j3OY!a|fDnPt?OX;pgv(-odW| zd2vSCup76t`Vg(m;QC8=M{w#rBW6%3Y(QVQn^>&jN^)w`=``TJaOVBHFB}u*1+lr~ z;bI6z*u1fbgH{z|_jvC94hk?oTMrG!i`K8OEEwHgvwEOd8XO}qS@23U4x-ohVa&I# zK>`24Yqo@D{3n`OHx9rY(?3`YoeOAgnnW-D6Uk)?cEQOPCYe}Ia4V)}&qR6iIQ=k7 zwMzh{JrIdyI_)tmeyrMR58Zem7FFN9+i)dB-E907p{_Fiid7dHe+8;DjK31qiL~~i zs21D;7ve)7rJ_~|ix|gBR=q$2 zABl2f-gRZ6b*grnJy3jjoT&+_0kK36cPJhl@3n>hqbx&zHqMOqI%H^8!bu|BJpaGV zdxmB~b3^ABhUUJ0hNcNmN^f@D*hEUD8MhBpsmEewt(m)cHKM(GGNQ0axM#`_<>k@8 z%u2Kbgb6pX{iv~M2%>Ahi!MHfgLWpB&lll!!pPht+ZS)uqPZfqzr52HV8m+D5(CJT zfW`;=QQQ+zrBcmqSnlK<+M=Rf z;pnoOaRT|(#cE+CE&rz$%NFWgTJ{9q^x8i3<_Y9;b06|46t0ffvUwt@F!)48FdIwH zwLn^nua0e1g<`T4oQ<@1gj94RtEZsURc2B5r(&d7)5DbGb>cIo8ct8Uy@UeZBAC1E zGa;lhTgda7h%?Vlgx8?2H~sz$7@kI}pTYL=Z84pHCL*gmnvUJp+x^S`P~&tU?;{fb zG-I3f;1UcntFY*}Y@$x5y3a)w`6z-GL7))$x4An8?pl#XJs19MYE*=-9y&O13}U$( zw?*O{;<|A-AG#PA6F^f&m-x)6M8q3j8ZRMe6e{#qhT_b|?)*l(h#$Q%`WAG-auq)p z!G1kgGn61q5d0nQM%R*tt{8QyH>?ID19=(r!H=n9k#O~6nIB?27`)EtOcBpOZk7QLe#364 z-C*uu)Ji~ub)RF@>y@bQzQTd!6u6p>sYBg>8615472oi8OfwAIxFx=lC~}Z=emo z0s7tQh-J{54WM&xM04x&X#D{5Wpf$K8%SAe4TDa5i^tOGZ-BnVb~Nw3Xec#ZO?mG{ zpl5hpmH~`tg7AceOe)#Gv1%6YeV+P-f<6e_idpZ!Xp(r5y6Fn@-J*>2%RnKulP$+O zAgjRWgZhA2XE}+Me-I8qIZ2qQb@T^}cD;bJZ${c{QVrTCw00E2O~O~AS8OJSb8M$4 zAB2C)iTnA@Y}FsqJ36!v0}?`EwDJn!|Mg<6IWFUkk)-~n_2m*_T)}80RIMC!qAgA> zV-J3jdK#RRC6A-j`=bc*`a^r#_~@H`{F>v18`05l33arK1s(h-T3Kea)0W)BnOr_0 z14 z4AAS7@wQbnSE{W%F(FL!k!~zK8qU;n*(@5(%jVvufJ$&N`%&W z|CJ_v5gubM*2uYhtArd45r}q@I zHe9UULE>C=rq#l6%sL=VTfPYw^D*7vm0qZ) z%iqLqYa2A!3IQ*&trr5k78N71arhG2RV*4=9ZTk$+MRLMbFCC#o4&|5Lucc~IP1AF zN^;ZkxX57(_WZ|}|Ag?LSak!ek(#)46Vxr*I%~@zrg9m%k?GGR^=@g_?I1uQ%sRMI zJR=vU><`PF`(CM{Tz{_Zg7x?!?U6inQfaECQ#{Ib)asfRvRUD+&^~s`yGTOXBXDqzDjr1iHKilIqG+~~p?n91z$y1Z()9Dh5 ztD9120Kl@0Njc`9SdlEunPCWhn0Jya%#_8|>^-$0@bND}t`XN}pJ{b-I6N&`JtYRK zkxYEe#u&gVh8t>cx@x9`NUrC|rljI0NmdkA60?teNGT;1cik?UR8nasdFkn9NhP3s z^)djf0_S^@1$yFuh`t~glFPBRR=ng<@*i(<`{0Qd`rn=7?-Q)s)nGFJDI zYFH@0NgchiW>_e7bdtwSI%}!;RQ_-SvS;Y$G1sCICg5$oYj8y% zGKxRYK}B&bTQ!m?w;_Kby%`lMilg-Y7Ma^BRmKeWG=;5vNT2i%a8cSd?!j`T+0Z~> zDH2)=TN-O2<%Xzv!LZ75I_l5*&FU==-ma1EK+KAxzcbOtiKr+C6RMh!k@_Rg4Kel+ z7}?GeuQNUo5rJ9R8K<=k4>2#}sEK#)>4YuNCG0CncFF>4kDf42v(Jd7m>nJIZ#$)i zX-AV1bl*;yDg^}4fO0^lM`pC3oN`8*6iYqID?_Day(q7|Qm2fV#MG@lXjW_ks%Wn) zk^Y!M$L*DBat|%l0)uJ+2x>|^SvV*j(snPZ?4b0P0)mMg6i?SA6dNfB*LD{hiY90fTmUbeOH zeBmrUK>nVV<5Z-kdQdNCrD0guosT%HS_^H^vdAzn?=X_`LESsG!e`930{UUadMZ&U<7}z69oJwC?aJb!vTu5w=+MyNE+2@qguQkOX`)XEvmi zCe=l0CsnIOQLc)IgGG}MFyHTGBx6iCiP`agk0MHQRf0ntJDHml)WZH~+oQcib4M1d ziB^V}_+Bu)WcjV1FX>i_p13N0I$yGLQz}dTp;X^Zsp{9Ft7OulAm?XjXl4Sk=h9$r zV9_VW1|a-67<}q-2rYC|!jQ{*%?*?{n}oaK9o*-4>`UTi-WScy+X_h$2G92AX#6@_ zxXBm?szvfJ?YoPZxW4X+eXs?dDm-ieF<8So+>nqwK3#_u*V2~o-U@a=9mFKzpP?Fv z*%sR4t`tiT3u&*1QbX63iaeD19r_f0WZ@_>{ToW)q+s02~_ERgKl^# z;ZnH~WM4tK7u?c}RgNJr5NI(H>YLMiY_9g3&8s#)C|A-|ZH{1WgZ`!}UW&Kmca>Ut zDUoumcG%6XjBPVGXLr6gt?^Qt__QsdjocEWEyt&*A5Li_^KZ?5Ht`FyrQyFGCf8cDk>f}_l`0nL?{fbcX_JV zPq!;#eOFwhJ3h+u#AZ14CJt(Y_Aam7FFzY}LE{Fy;2FaS1p74WfoAVkU5wALkw$%i zEP?O0)#M9VPL-5xI-fk){J@cuDr%ne_>3dbfC@jD?y!=`gc#|??NSHmji0i=*5?CS z=VW--!LRQ|gXx5zD_dkB<6gzI!L84$wrqd;(WBgcQY$MTrN#s4fxi-~8<*u@MUf=O z=U=$?=fU|rw=LuK?{e@Wcbe9KN+6@OO0X8-Eicd@tXQNn?Fmt&&pc29CECo-1w~>PSF8hhY!>A zyDJL>@@T9%23s-%gZ*%`1pGgHF3@`J=bq~Rz1l0Z-$BPIAs7PLa!LzUJYl6-9;`Hx zs=lKa!HR#?7dY(>hs4EHiVV#e#e1cm+r!dFp4#BpM@X7E1!cfO3_z-0qDD29Kc&Et zbgrfnE0xS9`&vqrbfGDAs0FqMGkReyrJA(Nn%qK^`mWip`J)f;La5WTct+Z97+dVs z;=?p1M7boLdPOZml}O8BsLshmcRDQ%RXoebqZt|cYz)%u^VNV|Oe^!%wTI|hsN!uk zyfRaLjZVxRMV7Ud8j^Jp)vK-8l^Y&~z=O=qKbDKP^Wk&to?`;;VG7!!4BDwpNBjNg zAT6k^bhdBtT-yL8F0%wu=zj!w?<2X6;v+q*Nww=J-n#wNxsGBlJ#0=R>L_g`$JcbZ zjfuyx(jqU zP6?EDf2ER*l;&kt!B!Wa3Dvv^i4xr!DNUU3RtG`7XgvX}!$h^JZII8s!LHO7-gK@J zfI1?Bo;L#P4LCv8jTL7}K0#F)E8TQ`XjWq-rLEHomYtBRt$xaV2Dr4IAQ|~9V)TDU z$ufi;zW_@@Eud=Vs4HBRyZp;EIRl8P&JAG#fM0x>Yw{Q__xGa2c*U8|@`_g)AV_{k zyfVq^Lb!oifRmxxN^FASuUnUunxLH2>CRETrb<1j?n)ZlR7ukvq;E}?8PZZ@-X$uI zRUcO|unibXOjNrXhOcbJjSmp<`PH##9PG>h*gBoACqe}&b%bg(Q)&hOQL%&xg6oqk z@TY}4Qd(h;?Ps{w7%>DKQP_dV`-Q}#EEfs5>wEF?&v;sU$UqwZ&l-ZTb`Wn`!H%3y! zs~Xma!>v_!N5lH4{~up(0w2@${sHISBm`l?Js}8!AohfWL@XI5OqdY0#oB0WwU>m{ zHqlHl9b+qwR$E$2DQ#&`kd!H z=h+V)NYqH@-}Tk%mYv~W23{k0nE1jeoXwfkyNh3xSIw5_<#-N9=Q z(msMTxOR}1*?3I@eMD<$M03D>(TY(H9J4bvh-4!upFk{pM4L3;d$2ZwTulaRoehmU z{0-tz(+WqfXQE~Y?l%Mn$Yb7rh?cA@LP#mPey4r*r6JllMOnkUCTZ1_d3<=1HbVWo z4gV!c>yG^sI8-Yrv)Gev1E1jiA!qMtG3ttwyzhHjJI(bcSro6rQbF{AVn62c_3vqQ zf>VB?_?ABw5qS)8>I#X>Sg34B7QZSYJh3Wz%$awx=3nR03V2E&#)wQRl;?-ae5saL zjw$w_ZL(I|e*)f7(kQaicE@Uf4ewQxPfFHWs#6#6Z<4h-Rkdi`4)+>6P^ZN5D1eo@ zt;%mCYoY8yIeoh&8I?nE$*;@`QW5d`!yvE>Y0Z;{Y3r@G%i?r$PW3V>2jY@nQh_u2 z8=p6Ca`6UFq=5Jgg;3m&3U2a|RRh2foQzd|cUNDgzYW4mW68^Oz0HtVC-aO;enGXz z$#Oh%xMoljefaX>pmT#-^V7q%p{jj7j~Ias1jX|RoFi$iva?2L-IRdF5q}p&4Gy&4 zj<+Lf4(Xqz%E>>1R~@BU%Jq9i(i0@~X5IP3QQG^}dST}q;ou!;y%lf2`=&y4IR9r9 zwmcFe_jn)Y(#l+(@xB(^CKkC+33cM<(7EzV99r~TcLl%$c>Ov1JN+XY zUHl*`L9J+5`eb_C!tMD$c%JfzwudPAzyn< z;h)jp$QwLstY%bWH}dCWwK#0sPUEym+SKN7Nh%T(@h8^)iU5z31VB7cK zsx#^HX54kF1(X^=zZdX@6E#cOo=x(gN-uEs(d6HJgM*&>W!fO7-B&~;fGK4>vq%FazJA1NLr(M+d$o%N&9FtL~ zq$I^UM&Nd}TeJE}BUimSa6g2BEDeA1>yduMWPc8gobC&aZeQ_hlOds==H*g=>q8pw zq!g`MyZ6pR{Dl=3tN{WT%y}_EmF7a+5DdrHU~8t3RsdLjsm>#qY3V*FxI0u8p_ z%d=CoPzXOFMGLN z=lE-s?bYcTK{29kHLUT9Tcn;P-=!5hN$Q6WIWmHm1GLc2%k^aGz(+&oRP0rJxlx+f zCxqchur}@TNwRlCB+Owp>B&hkc!L-%m!6i}t6d-(n-T1~^0Tv}MvwPDnvh(DO3 zRW5%HVIF7)jf)!fdBv&PbU#0u0hw5!L8&IxX5@!mmH*nQydSUsO{EI__o-T2)j1kh z0&5eiZwdw_9Ro^=M#PtRa2>=ULi=+u|2$2r;qO_Ouu^8&4~N#-gsWN}*5SXVX^qO9 zxG(YVi*{W3Pz&(YP@767i88^w-iKQ620zs$`d94py$(+~I zOqsQ?Bzq(k5d(MdPo`gc3}B^?4?-&wE9J}23zcW+H|e4|CS3XlpO~lO}-Y5Wl?yX^Ig-m1~m?!1Nr9vM%nYrrI(#XAK0^y>UoHsC^M$-j2v-l8AeTGa9Xuy#NfMfJMWH^a zh@9;{%$MulmEPL*R!i}BXKIy|*4a~LYJC+2(Ot8k+XE2K*Fb@R6D%Zol=Muthe+M>Vun{T#iRok_$ zj(bu*m+Ou5FTquSt8t+X_PjznkF51S;TLG=1|SAj44baR`=tCauBK}-W$rG<;o|g9 zxWc=oYc-T@{QY#8Ywq9XU!_CKwrCOmHC@}RMOtf^Vtf{Bc4cMulEvB_1puh}iPl7&>f~KM0o^%ky${KJ79^4j z&_W&MDW7Opl@EFErP^d=9Y3;Eo2E9p$W6<%cff!1W!hY|`vo4fTx)>fM)Pu*jz0UC zr!3d*s6$_659V5us@%!m`>EDbQJbdmiYv8Y>fBR&>PoExY)aWHAwJbsvde$2tyk2l zOZfILw5G5T-TVSDeZgCP38A9#EB?us-~t!$t6!qCQm6Q+Re0RVx2@71tHBHTx2w_S zkl(o9S6W8}F%4g7qmXJ~&sW+KHXi;3CfG$1T>?qB==>7L`Fme$!-9@oEaj0|lsa6z zy8aLZAT>tZ`bDyNt%)+4!}#s5wUbz~>@`5_ud?s0(Z2Cg`yb-VHfWO&`slL}D#fW& zd6$jaa@BB{U)`u>VBE>yYQKPc4ci16bw)0qv`HI-aLFs1v}VdRUVbx7jXAvOX3dBY zp9z}*s$K{9%FPha8Xe#VH$!`{x;L-+ofcc6Ka9KxMVUxU7ZNIe@SS!M`kMIfwJIdJ zd=HVU$v&R@J%)CeKl>h7``J5Gu|DtmgBIAZ?+0&cPs82Oh8nH|#N^h8BQsW1m;NNe>J~_tg{;17X%|G+?KjIWB`*ZfKAGJtD^>gu>+q6N- zk9_(zEloXon?Kp6eXGXr%KmD*7Od2G_CB=YU?6;;GYlb4EQn5;fNoCT((vQIk);if z`eG|tX-aOh?OX(j*_k?##3e9`BhSH=(UCgQwFxw)Sfxtym{pmlXG8lR@)s|)11P+d z_urv4tx^gifXf2-m`L182_9sDH)zjn{>2V#e*bKKeg~MlX@F6CP5GNDzTuKegU^?2^7XEDx#HbD$FUSG(d-mc@_k-O}jp1?o zwRp9DZN6eZH08hU<~jQ{WUS_yx!N-I>vKHt0E|_UJ$dH?S{L=*Z~4LlAXr}C^1BDL z18Rp&{D*_uQpJU9*R)w`qi^}aLt1?0i{D@n_A3zoIywXEnBkeAkaK^7!`cdR!r6Zq zjA!7Vyiy*lTQmRQTl2IywPPIrHxGh#LOgGO1iGfr_?jcovj=~Zee4LfI2_?B9|OHA z;N6d5=l46!&mPm>spxqcU{5Z=W$_Phb6h)38|;LZ7%+E@97nAECX)T)YOdthv??F0 z;WJNQQeD>YZ%$})RD+2(|3zy|JmW7~C!}Us^^5j(_@=M)x^GonfmbHwAs8XxA$f%* zBjs00@C>wXR`SG$U-8smAu{dd`+n6vC2aZ)dXHCp(Qn!fb=oSPa#HK4mO9RNoYcCh zQ8C>66m+doCf?^1RIe*}+9@#d@Y6d56~)BkeD5i(tCEsk=Cl@}sIT|%nBTP*>PHsd z_KcQ=_5bILrYfvKU(%w^8YNy=C7mUHqz3ace`?O4^-KPlJ0IlY9E^-@+VbA# zp?iqf&h6*1TApqA@$=e#_yJN7)(bpvq}%l8{Nv4?d3MO$L(ri0y! zb65k!pFHmxj^`CT;yN1L^*y&;*QVl<)PJu7gVh$HnHqL`j`K{Za zepQX_F>{fB@g;hymF9}QJ`v-?_rUk|)B z4jh2jtMIzY8s7B2R<%uiyp07>Po%sIvA7Ms35{?hHZuyfL)KYpp0sCoWp}b;W6xgV z!Dya-Ut^7-v(raI#!hz;IUf7nUSjv?*GM-fqnUBk^X3o0L?BVo1FbgCxewAgfme8- z)#0ljXj#5Prb#Ig66gF*{JjFLS;Dqg(M1oCSIIN9rc$ICp_g49m}dEwH%pgc4&g!15WbQxd4$D2&G$Xhf~wwMELoiX;tURREJ(sWk04ZQb)6SJ z0*iT#$N!^!35Wc9|7agp{RXCeirq&bE>zw#4*BT@t8^be>oIok?C$)F$69-}=LUZH zF?^Rw`S8NW(CLm`$?rVTwyWtA_?J($u-5Iob$2L$;?a0$PADF`t26KwhUg(eCm@c3 zKuJ!co~1}DS^$6tKuKBZnbusr(~Y-&rX^Hg7LG$5?AW+Mq;aLBfitn8=>-ycfBg(R z)|gNE&1cY4S9TYC@QnKvYE{%eDsNb*^;MmoxMxUX>PRon3$@yw2cc@-T?iyNgwLSIEe9$XE^;2r{A3)$^^2g`RxEbM*Hm=UY&%Y#gf5IBGxT zm!E6ZjF}$LY&-^e(1G<-h5rE=h@p)SJM9XCT?D1|Z`00@TzQq`5>k;-W`!;u&$A<6 zXxR#44<5eMszx7}r?2iwGSI9~(O35X9*Dx4h1a=1xjybVvMtbb_E@C}v#4n50X z|Eq0PXX5(hSK1)8!&q*3t<6)G@fEMNhK4a;f+kYz0HOMjFZs#W+8OW<>xyv74I0fK z6+x1z_{FjsEVx4c=NN3%CB5jCWj&as++w_P?FDef+-2+8T&0LNQ&=Kc*|`c!tJ-uW zRk){D2*LwRI!07p$pciDXN~_1^j%l((!#aJqbpQ5N!kdxJdFJil8vNN#y-a0ee6$q znP=aNB%0`GZF2Zeo?gns(9jl4vLXFN_yDNq5csD;QDw1j3l72yz`~H}PXQw7v-O2o zOAC>V%g-{cAXl7Vo_qj7Low$4cT}df3mn?Pdkmoq4sde-ATHJ!NHx$o zhF0w$G>D)SWikp?+*gGMAc|Y@v{{bH;z)y)zBCRQGlbcba$@K-&o(^xocqBMlY~B3 z<4Hshq-<&W)e6_395Xt41)80<;BELAcG2Qo8hj1ENShOisV!(g`ZN3HU^1#(D4i#) zk-dWy-Gj(*5!hjsc13q}~?Cyw6LsYK>#`3kJCo5sL~okW{1 zPqf0ulsm@?6AW~k=;x|<4SWR=vPu8M7(?#V*pk4iHh|y7#Fq!c`zrZ%E|A)UC*o>7L5{!PUy>c1uZ#Z zd@>3>4GWggIyff#nxY;W=4avoD5!F8jnx@U^)&<)%`R_lxKr}uLVrUwRdG}Vik7(x%=2=YB- z0J#*5%WTH4QIXN6iou5YLqHo%$dSJm#`p`+Jt#(-9IM&Jy58uQfy0g!Rf}65n ze4*@*O+ZDcxQ{r|3uYsrm0kpS5G_$pQp#Ha))b%OX&W7$Kxm`g6X?C5H%J7TI%s=} z9?NJIMz*Drc$OcCz>8M+kYCEU2mR4CO+<^{O6+TVm(n)as0P*;D+B;ZK8}>!j#wYN z71>K^F=^|#E&>)*zMZJ+&c|*1*uAHF#Ibwf~ zk0CoJDtA^HQ`95F{G%9paZ@`8S%^AZLqYlnXFhrq`jh-bZO}h@U#S1YE*cx0mLG4Z zWlg6y#m&)m3fJ�-c~HZ>AD}G}-mSb4$6=8;+RmqKu`eSC&|4zvj28sYXkKVHE zYTxjOMbcG7l{}(K-+t5nbA4$N_G$$fzi@+7<^z{^NDwDmZ3-J8E zumnnHevf(>JgoxR46!m+nuYy{(a=37GiO#)%ou0B2`A4yltHtEx}wnMK2@XN1Ooa5 zKGWM|&uMrB%`Qwtv&Ca|b;AQW7N=Q&Ki5#yVm~V?gQ2CpM7SWz;KAh&b_!Fl(&EZF z(BR*~9FgJ=C9xNgQECj9-u!GLZ$3!PzZJ(?h#1sUlGS1aXb1!V83~~y7n#KO zU#myQN{Gpk%wYI3WaeQ6vCi=bE0u4nPY#Sv{tNgJ8}(pT2kF0w^9q`A(WfhqtIBHB z19uJT9Eh-Fh3IK))RP&9W#zbJ@)jk^u65-O6ty-$-x<2K!rN$ACevu$p#E$Z4VmZN zpt!o|;hTH1KT0DSCdFABc{ZCI)hW*AU~J~aS#?V&hsA!4x|V569Wy+A#7eYbimI#I zc^1$E_EU`2H6K8wQ0~9;v(2!_1KGBqSAZ#vHbVVm+6eRIySU`Xu~FCK4Bh`mh+$&@ zEY0LzZRMod{)jx;R{-xl#i>&FF)DrWvFJ#fd&Jc68diPYDRf3-cm07MAP{CN`lAK5 zIFf_FJ*grq2^~hSl`pLZTsZ~QAXwO*zKt+0Jm{>c3*Kp1Zk+aJ=hEODG=;1Mpuz}p z%b--)2MLFVz*U&|h(&mBR?gAtqBr9CaKX4-Yx+u+iCL3GvBM2F>#)p=5Fcs`sJ@To z!0_$po(P=t#k$cy;_`@fgi%O_=P;sl8MBfgAm-pFP|9S#9~(73z_5ViaNG+Y(lNbl z2o7x8QN~6nsuD-#gO6`DYp`9UMyX#Q5nM`7_TvxBvOp`mzdbe}hyN1B!-#_r1{YnpVFl29^fZ(L^L_G~?z? z?3xhB-v^gJDUvSCMG1ZqmR3V%G6ojw=$uG|k)RMu5T1_?%~*1Ra9734MIZnp`x!G@Od_xl z$*~oXfanJB+i@n2x6Q7KWmun2){i*l-djM@(vNVKQ7T<=0g}0f8yDds*^b@R-p=-auc=> ztJz3$_DfWCqB%L zN&pq0BvUZR^Udg(5`$eb#b^cf10UbO?T7+1gHC)w9F60#5hT5}A=hP*>k1i$$^1Zs zSt7VIVs=M3JpjLoHvn?>i-vy}qetc@Sw;VBj_MR($n1-j@|V16hW0-kAdE2c|8F}t z9+tE-?Ekc5pb^F3KZfjF;8oaZ41!1l{Uf4bcFvbfdz>@HYm^yU-XKwFGRBXfdMf7Z z>lL*$7^y+59+RsPafI**%Di4Wg0OiqpaZdDtoJ@X%fIx>~nw?$`LGfx?P&o)E zc)W7gV%S^L3}GwY8F;{=oQsQkL?rL9ixxHBYR`+epKz7J@m<1d82iLSKZdJM&h#3X`#DGlVzieA z#aNJz(d_Fh9(dIihWeR$2{Z}$%+|^ z;h0w#vV0Yk2Iq1BB{D$p@pBw1S`Z+DHak+Ahy?H|MLGx@9LUJ?6(`cImq?=udb$K< zGYS=4MtxXs#}jkQc4!`0uX2xJ(E%1}(L-%m( zAERLQeL$5WYCs!hMuudp^oCw?rT2dc9hA%i*2ynF!wuQEolcIcGewkBq|7O!I+ePT#+S}E2MtB;EKBimM-JZ_j@nNtFD31c1bhRjb< z#C>AJXtm?~+W@+IsTe?+cTmjeShfRwp_>ZmU&e`e8Enk}IvPA2%3O!3v1Y|5sc|3W ztas5MBtF@5N6fyVsv~B{>!*?n} z=;a!Zcj;DQpa|Ahi({k@`NKmp8XnW#k>c+oS)!X5K9t9ys09L&@&sskE59_c_>MRP zhk#p72d-p%7^I}$H%C`Z6&Y~}LHRf0l4Apq3M1gHs)rC843@YK8k7!Q5uKt53Cr(( z0TLj)=J7 z{VC+$GAuaKT~%VaJWHZ=xQQOWyCqtR?k9D~9Wf|Q*9i9hgUmaip-@^KPnXha$h1Ij`$FB@?rEdh(Ho{Ivp0))NfFp2E3UDrXQls zC>sL^8E<=;m9vs^oM_ks{KW>=$=Lf>NzS(=2Z*fa#wPNcadAeI?oaZtU&60w-zZMI^fgIq8ELv*R9up;W{ z5!x&1=nw{FwC9inwmvLJ2G8mwhH^5{H80`BrGp&_aJBhQdq#cFRl!*XInKvbA3un+ z5xKWk!vls7ydLidq=gI>gM(e}2Sa8e09=Bv|3O!95+N2x5~LN}rc3Z9Fg@NU+Y%P= z%W;s^SL3}jk=#$I0k#3W0(d3tqy=TMUU6WgR~L)rQlh8(%E3ueO9LS@5pSD-7#E{n z)#$DpM7xj_01gy4ImQJ`Tg6v|0nXTP2T9$2q(6hy@hCp|i4h3Y7A61{*Zz1Ry;IBl z*b$2mheS651L3T4Y3^VaF#AlYfeurIS7wg&h@Rj`Tt>=* z|4e8f3dLdxPz~e&tx1l|H5&r&|0`W`O>onSYR(8#Rlq&ay$?!2Uqj)W%Cl+_&&1_Z zp!kGd1aq@vln*T2B5f~-H2$7!Pk#X@-H1!E$gv(4{<1u)Z5>6B%FA30IMF|%=|1*c zz<*w8d;wSkY2POhY0JX+jSjD1$z6H{(;AJ(E0bfUoKaq^KA()I`k5hWB3=k&Mlub= z8IHz>jBm+YM)QsI}IMo zW6yJaBdg(l<2uJmPOOD^S3LM`?Fg*@8M{?tF5LFz;EisONJ0rODjFB=enJvM5I#Ck zcg;YQsm^$`#%C~Wp&o`zL<7kgpb%x~y)FL1)-N8EhH`E+kV+!)^mNJK{&{TGYnGhl z7gm*=^3aV6z@clVLl>AX&uN@euKMWHX6Y3oPM}n5)L4qNBl!PJmB>p@o}P4n9>%;P8@GYwq-Ys4+j^vyCv^%AhytO^ zM4SVWGGg~K$=Ktni~o!;SZkT&kwS%j{)lAtga0{AW(~2}-PLT52&CY~pmp#;PMbB<8)^pD;_{fpi*7Ho7ZQ- zN`KzFKKny$*_t8?!2n|3c6`ZFoOW44*W48qEO9`d~b9&~7Y={O_}v>VZ-&0tgG#7R7BuY(!cPmqNz95UiF(d%oR zbVPP3dXo+d>5&!BgTh#YMo#3gn@*P)pWd zDb2H5vS78+NPej$Ygx{jODsvJ7;)xZB$!~0ss)UqlNr(p*&La8_IKp@}|5H1ueZh!1XOc$M^bOwN=JP<8-hW6KGa8$BH18D6YO6cK_=srMQ8Dq2(JZ>bxtJ$KPct53bZSZpAeR^@Z6CT? z1z_7tX;{S#Ual<*Q<8YQwk%rRb~1ZfTeb*sL%(s~_N;|clXqy(CTI(AD<91fyzC)e zb_w?WBfqax+n)96re1iq&wAB$9o*qI1G^t)SP@;v^jIHXeXcAfjKKi z?k20KJ}^2e1Gs+-dsiKmz^BBpPJU}ZB;PuzfMGE#S@Gjdjckh2DtoPw`6|i`zO^Ik zuKseDE1lRTHT@|6z7yM{E_sKKHL?C|>JG%x)Jg|1F-1gB7KkTV{Je<`QlI_BTgS4; zD#BKqc4ke~mKl6tXZC%_njZ^gf_tdla7>VIvq*YC>9Uc0wcX~f3NZRGRL-Aghjn40 ziaKy4Pd2j%PcOKst~9f-DvLmK^4Gfcgg7kCl${{I5x;51;6cUXSP)42s5lm=jN+Mb ztS+s49E%TpDifUL5+Cm`RaJy-q2v$r`B7e}D_f!_Ugqn&vi9LVhlyvB8m&RF;ek3q zW|W$ekGCH-IYtFZG4MlPt~(^38gPS*b9!BYId}%K zqvW1}vnL+DvLFJZ2ZLVl-{*>L-7| zSfB%mq-r#;1jNBk?7{pSuEz(0dP4D6(I@B$LblxX$;5+?hRj*~`yQ-n%rfXI<$_WP zxa{W;KLr-aVCyPp+hxZMz&3m!^=%1Ac*eJ0m5HT>A1iZ!y%;efn|I!gq8X{8h322rEx(Gc;XNYD{?QSQuhAUbh~+{AWE|;kN0Mtd zY+VC@+zF@mC@*(XQYPL@@VD z)A7l-ip>d5wgmT}J9{Ub>}1&M)qoV~&a{&;=|yFx+=@wm-N;}gUuO~rF*97|2o}Yu zud3L3M86ol@kZj*q1&)pQip_ufMHz!JH>hE3PZOo2wJ}w1=k?$d8Ji*J7J@ioe z&%2fvf4A7nBKKJrxN|*qMe@Kttahc{g*XOg1&PvlORQW`XWpX^YlfMC@QN~zd3qlf z+ETipx;l`6>uk5{l#F)YgEfLQ@vhE%n{h7s<=g&OcJJ2tZP~pYo?HP0f&butj4%a& zZILJl42SU|775gwUIqHdgtxuDVO)jH583)X%*5Hyzx0e3P<7XqTa0iQd&RYsL_Hm? zdtvbtLhHF6%2(Lq7RSUGc?Ak3DyFp$f)|e21I7(+KA1S zLuDa*bm4^e-36P7D zApKaV%<&uUZ| zP4xLN8l3wtrG3fF(OoY3&)Z{neMXpa7~e;!}^&W zb2diw-OymL4b7Gx-51Xt&c0U! zqLv1}y+UKKYfkS~z~@-|$N=Q9Atv7Gf430t$!=<=ij;p7w1ec4UgUa`^A3uL+c49E zOcTqH(w?s$z=B(k9}gv>`<_9!BaIKn8t3RBe%eCkXpyLHq_dvR%RJq4!gc#OA25*B z4Y}o#2Ls&r{2UX#$P(TfAjN$Lt_WzaX=*>h>)dskuN%l(HZ}fCAo~A;ByCb#AKH$eBzG;$cHr$Ffo7aZ!cxO4R;>&m6+i z%3XP)z#-^ig7|X#@^>M`cHtrKvQA2EKK5NU#P7%31rRrn#5n`Y5s$ql`@*|SQvyA~ zn36`nA9dEEuHN$idhj>!GDBH)>Gcpg*X?$GpdC zst0ay$9temJNcRSSZbwCQII{lE+SPP?0CP4e{S-D$rx z#wM$?n)9IHEI?hml(!kqQq}v-_}1Z&DL>;khqHQ03NJH)HB~zw;*lfZ*Lvbr&*=zww3&x!@y*mt;*}K!tS5a8;b52TU6^ z^2A!Y<_p0&hs5Z&%Y26iKl<)3FX%%fd7>-7IfDHh8F)x%SN_%e6r1O|ZK(Np;coXT zQMgDvdx-B|>7!Z4&y8e(z2~_f)9vnIhoO7$j$(rQ!$|r-Lk%OHrbxu=lEF5{-D2)< z7;w9imd&Hs7`5SIzI_z?*80oFd!!aSYC`1QHi!2|Ovkq>w9s3t>8lR(^bku+>G(!& z#utS*9BX@xxX(Q11;VT<# z-n{~w;mZ5Wb4rM5+wyVp|mz}&q)mrY+4Det?R5;SKh!{lX1<9YMZ!0S1@-)L4t zHRtjvqgkUe_rky=6^V$2eB)@=vPu$gc$bepM2N^Vjv$f0j{k$I!IMxn-$rS0$n7dX zyoYDGbpoo12UTqej;ns%H9}4QoB38`tGGXKBBUw_g8@)p1&qN zs3B9qLwxeB*5JVi20kwN9*F?=hPqdX%(8KgRB)lV!#xiN`pys7k@m;W6hNL$2@W)`aNUv& zLOROf5S091f!Kua`1HN}6a#cRE6(BAm8U?5&-lJctd-J_Kb^#CsdpywDwCl~n#{XS zW*O!7g}95=|CFDb%r+|lJTrxTtkmFssVs@||E021HShic`2a4s{!oPy~WhoZ&a zB-s7{QRjns(iFB$-S9K7Je9RlC;pt>eJbz@TF)tIY?ONCPkt?pT~=!Gy&tj^t zD;uwP^N@7*iF&;}|2dtR%gwFs2F3#i_nXb?T91;yVVwOH;#c8fxwkq7+birM;#leY zFguq9r{fKY&h(f5iPpF$j;zEfRqTT)$czfwPrl_nM}EQSC>fW$%m;W|Ow7cUjktd# zdD%UbFQ&)BdJHekPF*KV)ERmscL>EiG*QA%(_8SDSH-k(ZaTRMP18olZ5%f-Ct#9w zf{Zfrqo@O5*HuvyAB+wsbx6t3p5iv>J*1lm$qy;EURq@^xQ`gNsgP6%K4e&njoMCC z3=1lv3#>*y@kK!t=&OeTnw^`2b1=A_W2IOHkA z9x?G6{tr&6&uC?|2ar5e1m6Jl$T%2erKL@iqy&8+%wdCUgkqh|h*(-JpLEw>VFd0| zakzUTat11Ga{Y0BE`t?I#6oO;V#&PWJ}ncu&cIAa!%HMom%`psgIJQSOJxW!EwIjo zV1e5lpsj|~j7U0Si8?#^yI3Fu3VuSsz&qghb2kcv9lX^Zm0s{egtR!-p;{_lG_F8Oz}atwh$)ey}@a)M#6kCdvN zzNhfP4B;AH!)IKh0S0nLd3)?QZc=KQo!ex;Vp1+m1cP+7l4Wgj_+lVl8`FO#jfID` zc(5t8&5f7plUQN4yC;B}uds^6$l|FN$iGaSC~2E)bbSHxRMVjc%~2@q4ezE>7TZUz z+iz%?C2Sb93d@O6be9uRC?!2DLNmi~O2aH|j&p3^L2Kk}SN2!1eGZ@!3=oi?nuSTb zq&!IRS#vChSof&3p(gMXs%?dRvcn8Y}IV6T5&?(X*6+ovBkvUy_aP^_Qd(=v2CrPu( z_zQ4L;v<@+5_^VQ=m-cv5m1LbasCQfhGx;GNCLmG6KzXsn?MM)TA~VooN=f?U#ZLh zwAj_@^%s315=TV{tT7n=eINIO4_Fu(@5Nt?)q;TCCg>AU$d7)d(Jx4pWLT0~Zu?a* zcxk9g{){u|FUf5|Z|_hP4tQ&G($NI51~F7c2_cdSn~2;YW*Uu3eY*W>Q9=;4p7CP1 z6;4pVUkN6l>@Z#74s;OPY@l~204vbgO6H>rr4&KB$SvbN-p%0u@ zKQ0*wIZs-Yvv0`F|8CB_)O$w99HO6bVSm&h{lEgcwi<9vr72*z12pY;WFS?3i42t*EhI8h{L;ChYI7I+$r zGAupdS_9#5Hw+3u_&cHtz9CiJMVAwA@n;VH6kBN=YbE)}C*YXC`ruUkgJKsR_p#Uy zxqbN|V5S87Vme6r3gq%BEV2?ww{5{wJBlVU*w#^3PVby`ii}T)!|!?c-A;xlMB{0Z z{4y-1Icy7f{9Zl=T7w{AmdW!526;hK;LY(mJ~PK+Fy*)hn7;c2I)JkyQWxE*3TIxHvSu$M?^LRQXLtp9GvzaAonfRJO(%b+Lvhr=qMB!WUGq(BwihLL*W|2F&x zX;$@i3mfb0=C6kU8#dihE|`r+67*V*hHb;fF5=OflE z*s_|gKE5M@hrJ{nKyU~RLuO`ah}}kCJ|53gP*SZ{hOhmI^{>8amAoujOohXYEchwb zjTE1^$MJv+HeSto#OGze8R4Vb*_$&UqN?%j_$eFg)_I@vXEt_8ZJ5db$Yech{%N}h zx;`%47(F=Hnj-IvNzMnu3TvR)W#gtfti!wIfphRR6Sd`!Xb}f)nz)XNc$V%ZbT~Qu zM?CPxtpLMA$W^c=NQhYcxIiA`{bAq{Dc5wa+d|f!WCUfw(K4l}hiDSZZ_HsKYN-d@ zcP^_{!CmJrRHDNB8jqR_6P}5Wp3B0Tr{4G0bx}Xk!mas7Z+#0r%(<$!z6KBb%mAOb z)sY`V-IkS6$>dml1RqG4rvjqAyJ}w=Wo>uWI6NQ^nV8*?H=V~CtHV6`fO)Kj<~_s> zV+X3zVx)}XAJ2m!^G+mhZD+q|=OXEj2apROXpD9wqaI;cbHGFoN$xIkjCRujqhjdt?;v=YZ;0wl zTU$A<&wRE{jb4_W?1WmwA3V{U%dZOPR1rUw;ky^G z?w&vW`!Dxh$O7x8e4;mI=_jX`(f~0+sipH`lL+~!^`D0FZVOp;wQ>X>wUEsVxd;6o z4(ZHX$|s`VwJ4K=k(VlVr1u&5c?8Uui&$v+CMfOpU~QPo`z&HXzOCh}J80w8em;8< z3n-nQ4Nv)5fqeBM7FO{hLLP}xL~~#?#0ex_U&I>twnV-Zyh5$__jCWnETKxj7ynAM z>OkuOLWZEO0-^TdGZwRYeixA~96)WND@n(-nImXSkp>V-<6>ql(7oZ zeSv6jlsEW<)oM27-DfgVxBy*<^FwhGgZRVGG%mSIsKVw*m;QAi!c^zu!AJqh-VJf# zrb%LTk4oa~9@5fx+$guuy%wH>`O8mO3w7Z$-h3&mT(&g|kf`~?Al_psi*Eb~*~Bpy zN^d)IkgjeijRwgOY#T_YeX%?Dhm-mCrL4YsJ%wLh%1jkrjwfSLG4119c}2!MEo1)b zu%~>$G8WXWjuU8-{0SX%Qk0>wSHL@+^wZO|1UcB$VLHhFKCGWmu6H1k*bkNf$$pq0 zTE?OcGxXvqpHtm}0o<@0oBywIJZd@XUpgImXT)EV`KQZSpsxz-kj^cl-Eh8tIR@2v z96z_5HE8xE3w&e7K`=K3I;D11U-(EK?#_t!7vP(-T^fo2Xa0eXn&*60t`=W?u$)(w z1LEU}SQc5;eVZCWR0{Y=&O)tiQAH$y2Fp%k!*VD>8G6zx^xiDr?+KP?#=x<#H-T4q z>&Wntxwzb;dAYWDG#9s{uJ2oQu|&YW2oZoLDCL0O2r;z0@(RW(?m`9ENvxebTE)#V zJbDHDxb`y#*2ytFNnCjWPTzeM(rNj7dYU-;qJZCC!Dh$S>rd<-!tY;8P4H%9H4|UK znHFX(uw=Ts$6_LSffMc(*)!6CUgVbdswl-jF8L35Qv4|%b?2KuWr?cT&r5yA!fI!J z?CyE&^EW*w$=~R?-}3^V_!&zJ+tZJF#xcDCz)Kmsg53#e()KR8dl|2jm0 zzZ=Jul`OQj!|rZ{J(Pd6658`+7x>1N(6gRB%kx&kuj#}&-uZLZ zBIt^K4t$5nh#klDb6_ahp>@#n05nWyLnyWa7X*ZqR^s$M@+ zCxfre?kzW{yiWec_2P@aV0QKE`#kVVR-^7Gvt`S+>KHz4y_UrlE|4IC7hk`_2Yt!L zssG&L$G>EC)$cR-!!JQ-ljcwl1!7beea~L&>GsRROHe8wu_~Q6Uxl;!PMT-IHHl#TKYN zZG7Bnc;FS@<%d_}ILW=s|6R?p)VnMBwy)Snfw$}YZ==0;>5W=C^LM^xW7XGiJNcT` zua#xhfwiF1OB`baMjLr*>4fKbJojG1MuxA2V*#C^GfUjP|s)s2fNcn~cTxpy`4hrHOMgAS4*$2Qu^^UhAy$p=uCbCzF)9L)) z8aTuBp2fSaMM@=+?bZa-`Pvv>MFf{mup{tHz)BQ{sRWh_2g);1#$7^z)0DeJf>=u> zut8*rJ9wZru68OZVHO`z3E+S%amZcbXOt-CZX`w|W%CDXS>0OsnQ(m1n0pTGDY(Lx z$owdhIdT8RWzpTpL)Wo})=tIkQBRe-Q(y~-Cct+WyU4A)7B$`d%t?eonaMi3lzsvix)goGjAiqQ2!PWZme0FxV7=8LX1;m@tE&FA zjPKsSdX&8@zh4ud-Q{c}3sT{a)@mcl3g3P?e1pyA_6yz|%ir0=I#nw@6;n?BqXd(lP0{)F-`emWHnEzlM^$V& zH=5Bxnnk;+{Q4$vA4)ubwTZO|du4W;E`Tj`tPkFzkMK}Wx)|~)!4ZlL9j{Z$iU&XN zq|K~zo61-JmBX8d6{j$Q!v@>$6+oY`Yy3o%3HcLZrA+wNCd1HiP5TvoZ8NLfdQQ~a zYczza+OO(sl;25bEbd8r>eL{8lb*({4}Y`lrr)vmkc#{=U;I4_Ds!s5-XTge@$(qMG&$3{*;a38y^q&keqN3#(S4OGQff|4eTC z<2U%tE$}&Bdx2Nm%Ieo0^Z}66*|&HF5CDJ|#E#UBpnR1DVr2)OycI6jEiUl+TjBm$ zFp>YT70b42GL{ttD!@%d;F~{@U*F2Ko*O3WQ%DcjGhP<9FLAyGH=8GRjMFJ!Pi*Qq zhZhv@^5!#xEe0=&{Hx}|ejkCKZV$*${dnw;tVwudG>e1TjVgCUb$2)awA8y9gKp5g zD;PRB9Z%0!%wG2+^HHGzVUGlQ{>p%RG^Gx7>Z8xljb2p2NzFZ=!Uxa1{e zn=vONZs(aS?;F6?Z7f#Zew4>;gD`MpJ0GzP&YLfMdGK~NSM3?izuV4QcMIrq56Zx` zQsL=Zeg~r|a;?jU5v+Wrecm4Apn8ymKqGWa)b%&?5WH1~$!8=HLV-m}W^vV@H_u{o z)Y5?{_7EdSTCSl!m2uG7(9>Ed>Zbw^o-;k_i1gl}H$v1fGB44@wpx61Q2*{pH- zE+4=eOj1Rjm>-orDI0=xy+J+cteGF2j!tPwp*Oq&ZQ@!yD#k>!k8u zO*iw3yHU}PNAG4~>XtHm{B9Og_Q439KpbwwckE_?RYM}6T*V%bA)PC2UfP2(qGANU zzZ?AWH=}r!J?vujZ-+ldG33d~pDeoX)yK!F&#-TK`JY*}))fFY?2btwYF(YCb-Epa zD2|^Puu2E%J200K!K;Kd(7!zVk`MWrRj%UG(9MA0niY@OsN2@f$n`lln>&66H)d(c zfBc#CQlGWprT0QyzU#@u_p%+TUkmaH@lWL8B9!X*0Z&&wUczM%u*5Nm=P_N<3kmGEhBSj9!n zF>+H9RK?ou`l?+b2Wd#Tcf=PpBsQcpq6a@*c65X_DnINc zu|{&Yoo~SF9c7)YzZiQPp$dFEtw-|IP^h&mSTIumCeUBpQ9G*(MQGw!zHtSDUh=PQ z{}FN=Nv#GA`!9a*q3gmRRb<@8RiG{4PLc+YVLSX1Bz~QH@752i14sFDoZ)!Ft5bZQ=Am51CJ2HT%_Ye}9AYg``EaKk9p)ye4cJ`XX! z1H6=W!zBwItNY0skPO;bJP(M6l(1t~pgCiD0+g9W_(qY(7Aw9;Ke)N5Xm+I11U)f9 zLw09!)zaN!DEBCoiWZaIE4YUowqkh;xIq z=E!%DM{~8!K)HAXzsK7DwM1{CP>vaz!D_3IQ`;21n=F#>kk^lJi`_R^)Hp!P=}R%K znNLA<9o^7{tOx%-lU>$`xBr%x;ft#DuXwVVN3Atnxv1e*uu_Pf(HW~mbqY1iCt41Z zd5lcSmU_#ptE2aQ{_b%WU>$}pWTCi4CG2Mgt$r-<=+NcLU_Y$|X=3p+9k@03Auy=yph|jq_5Ml0QK?Xlac5z&9Y48{wqC zi68Q;QlgXsyB0~ds=_y#4pJYCddrgQ)@1J^^CcR{-zyvbZ;p?rUTzaFHr@s$^<&Xg zPUTREa-}>C7eX$SE(l5~vSt+e7;NWJ3syz!NI$L&$=&!s6-zrcpw~Vuvfk1C*8pA1D-U=o_3-s8KP4tqsm_!p#0CpKjd^ z^BxA3Sx6wjzE^bpIo{CqlXADX$VHCUG)#^oQC`%6=FQj`!UNf?b$rDXa6uW0lHo0p z6ir3qQBNG15}Q*iBdK%oU9x41{1f5*k1tllkAXM=@zVl`T`IzzTW|rCRcN@>sI3t= zC)X)CJvvZmSQx1U3pO+2&A=DPHqLmy22ki78gQ*b4IO7F&e-W+`2vg>IiBVf7~mmF z9)uWdt9!TGzQ)QEC3uSjq_i;GpIPi=;)1V)k9by<=qNS@rk#)9<|yJ3@x_7-kJyP$ zm^(HZtSbH|4uhB!=Nppb#MU1{9{*jLejdm%OCvRssnx?hT^AI`NQP>68Fv5&fo~B_ zW=XXBv>igDi(Lh917(HIhO9szQ)HlDYSrRYG)6?k8$S95YYChK>YYPk8Wb&KqyPcz zZx@h*IR^g!8r%oM`KCd%XUGcoi-`=!)>(^B8AW9c3y_Zq zgDu~Y25Wyn7X`v_6jwICp1uTVU%`NxhbfZzrB*2(aAHP*Vu?DMQW^urcrRoW6{S>_ z`=!J(kK;%B?q4LFdnKiYlXe_8NMfyK1ox)C>HpO{+&ge)_A7}*z2ynf7Tq4s zpo;Kp1`7&}M-}u!1Ti0Z^{{9-NoB&GN+>C9cDsl&OG0WTRnI!?0dsP%B)6D(+U;2BimM$QihR{aa%;K0yX{g+{Yr{j+Ru^VbSEu6r?M{$UBxSq_KCZF^8PtqhbRg z$^>wo=9A_}-zFG=ugS?5v?5=^9w77o4l%5Nc7PbK3X;L33<78)w*v`r{cmr_}xUMd>?$);&hQLUn)qFRYbO0^7=O4}?n zOw3ietkJpW}bX7{Q5G1jC=uk-m(MH@}+yneqN*V>N$E98RpA|*nT{}xk1ow$x-`KgLj zrY)WtTth#|t>fia_LKPfnf%7pZ-KO7J^x%gLDs)#wfwM({M7!2g}lrQt=4ntz2SfI zozEX|*E=HPLu*1U;ZauZUbjxZ*CkU*Pqpz>^q?F5@@ew> zKkEa&X$_)&MEHj1U$?1pR^?Yk+9rmuzXZLA+Cd$k*p*szm1p5I}GjA3$-cVyxl>wY~o4^Q+PGlGn!C)vaRn%hT00PA1|AFv2RnWX^M90%X=SOoZ;6}oOu2b#8~8e13Za* z&vLM#>p}iKJ@oB2eyCiR5ad3SAA#UQUw_`Pa@_I(`C>MP9!A4o;(9Ff@`NvOy%>5qw}8j* z#@Z+3GWWkf9EC5fk8;CT;Clv5?1&6q%v@oi#VXeE;9tA`_t#YmHe90cqA@-~{&VWf zp?T443BC8$^8~?aMr(Bu(Ra%a%*|Y=tZuHYlaGGCKYH;JE@i#raPO;qMdb;6pc|*uE_y)P!r)1IE zAp6Z+EC0zkbkh^E_yzvMGh6L`9{D!B9@>LHuzgFXYj^OU4Sei~J^0t7+~WgTyo>+H zlX=tIoJ_gQdur{AeBm+lx$oKu@pZtsbZ-J#-<=Z38f$O%a(LWnk&8#WoZO_Q~ z_1k+c9@fm2D>nzKC{N*oSk0{1%^elR%WrvaZcpZU2VX8z-~ZWo$_c*~$afcb6LTY- zWE$cEL!S)2j~d5OuMQP7-KQFUF^-juE)Cp?;2Hx+w@Y=HT z8jMj9`k0r?E^9QtuGe2TuPjcW3U8H{9Vsz`@yhzPy<-_a4)t6e0 zLej=3HQKFZv)Ya25&9VysKNclbH=&&#!X=VaiQ;M%#>dO%vdDqlF_>8*e zfYCM3a+y3Q`vSW!Rd4IyQ#k$kJ@yVhAys^d`dp9&KbAh+X`D7r7kbM0{SQN*$ZuhA zVif+3X5pWnhCqQ{y|j}Pe~q=w(J4Q1HSG$usLL3CZ0aoeM+3f=_cqT0%wc)FQ_lT) zXQ_L;jLFBG!IdQMNAuYm-V41~@$^u2&OzgG1NZ}wd`=zuq?U!SR_9X4Kibo@n}=JmtXHxBd8 z>oxbQ-yAm17+ZECFLlFx${osdY@BYI7&^&`yd>wN1+SEP z>eL>5l+QnJ8_JPce9#=&)2!YtSV5#yeP6JyPN#ZMaA9_CIn|V`Uuxg7#uPg*p;bP9 zEAmW*cdY$ZKDux0r|^%Sf8LU^(R950mk^JQ<7+2`PHn$|saw7?jnOY^+H%lz;pzMy z8+*Dg{*yh|P#D^i3U~CRGv!rckx%67jq!n7KT|hEn68UhP}US-GUx~X;~aUJHU-W+ zM~#X!%{}|RmEpgu#LJhUZ>oaW#K)_&KoDSeDV>R2jkjIWfv~ zg8n;xwld0eaolvh`~yW?e4n?}==lOZF#r85^}{IB@%p?6)O}H=d-O*=P_}G<>6(a$ zG(Pa0%8S)V_*?4m&?9xtApu5OAp&6|9w z{P6OPhR`c9enoav`qNw~D=F=HznFI_j{3c|p_i&6+H{)UeMp@<*fdT*XrsDlu<1Pg z%th*JgH3bva}!lRLXri_7x zQ|0A!I8Z!8eJ;jyjeg0S>d~>LEA@5L)r?rvCHl59^_^JLnel`2qM z>zL3jXrVLQg6}-qF4W{7dp=;*@58`F`&-mu!DB|u9k8bPk5_;4eLDkhaPbL_fPFem z@|RpM_a%S8*=Sr#LKmn#P*3q{{wZ@f@c3uyQ^%Ud>QA1oZa>y^v%WY{opGEgN&n+C z)qb35=YTIR2z}V_lPqOaPq7V1B4 zQTLBA6&TX_yU8Dq(HBOmkDE=CCLcdZj+q~SXOS1D{1c>{)xh^(cZ9y=BL}pS$3$kH zA6E?&ja9qMrc3o%U#k}#Z<@qk*VY_Qc1wx+?eV5*Bdte={|GsLXIJ=B#S=oib_CR2 z>PcfwSD$q%J*@pwz7lqA7(Dm#@B>f@mAG6Dfg7#~Pg-d8p_FswJ5v8;a#*a0(irU${%}BjvTTocbOE^Yr^isozduJoD~R4^1##sBgMk zwI-N0osuWy)6dyFx?64BfO{{M+1~dl3g+?_(9nfm+S#>E9Wc=}W7z5e{Ql{(Os)dn zl=vtx`bO0{(G-7N+ADlKwm_chBtAgkm8V*M5h-AaQ}3T>QX+<^+a{W>jo7IkKZ!@5 zf$yuSlT4fR>;3AllT3H%FE^-*C!6B+_v}?SOg5$KO$N1gvMEa+^OJg+!mSawRlQ9y z-L0>QE$dQD3nKJ$yHv|m)7Sw6dAEtqJ#&e=Y$~(x+K94*X{MNnaWjJ*p_|w(`;ZXI z$giC2u*AwUAzypPsMjZ&5*%~S;xgf%19e;`fg8^YUm^>*AOhBz;rmLinI5`?`EB;h zz(8KB$nWZK-Q;%h#?gl9-Dk>AaEBi+JK z9SFSpxH@b)PX{;cDYH&DjgDZJZl1xd_wFL~)fuLVWA9%i9|=TY9oC-90~~9zq^v&_ z>J8u63EZ^k;Zu3idw!vM(y68^^s~P!yXREX$cQtho+1B1z^E!iPpP~;5V-Pec_WgN z7d&fF=>jvS%NKq z>k|94BOfdKwDX;+Zl1|`yS`P8on?AE?yx0%Q;wG}1SXypp6!EjwhhzNrdg&0{cEZk zH`{ca{>)u!(rnYY1806+&!{^Bd#_eE&Nk(a8-sbQxUPpTbIYw zuAghNvYy~~b4{}+ENSHZ6J9Xo)W-17MEQIYx*Ze`XL6qWya6S7OjcmDN41=8I_Wb0 z0n;^yPZdm1snQZJV#z!MWLgI9{-P(r|$Oo;hB@)Xbq%K3SXy;lRr~eoV(HZ zW@vrUjdOef&jadvr<)4(!>>@&EvD`hb7nFBOkKX*@p+4EWyP(5`x9gfE0%`;)unAx z@0!PJ5Z@v7iFu|mhF5spv@YdG7Ull~*S@cQI?ps+|Jh76a=vNovHMOBHL^VL>4Z=t zH-sCRyh%NMK98b94ym^JrsE8)SNCnC$gAEr-*onXVUzmt6kB_@uWZkJQ^mkHt){#e zQl=^9DKlm%Q)W$7%!`vwow0cOlxvm68PgX{zi!%;sWYyhK6UZ*X;YQN#A!38U8_t< zyl&C-nTd<8Uwr+wNvB?a{dLo?OPV@$`l*W+CC)hY+Oq0SQ_hW!_|`_TtL1-2;t}Nw zj>sRmPwEldGkWsbm`fPj!pDe5tF1|B*AQ1XIYeV_N~?WP1`(Kq%xbgr9wVgqN_A&m%I~CzE|Sh)AMbqfFz#i6wtT;meLD(f)Fi zSU{nShJQ4PNb)jflg}WZ_zDNF3x^ezKH(wlChSB!_w4L5|MjS$ZjIxJ9SV=g|5bys z-e1-2W}EDcjPyR8lJ(^_d0?5AI%Gl~q=b+=$b4^EH)$DtJ0Z8pvITt_mfL$9mFd3Q zvdJI0e{bDY3!5Ec!9sTEi7YJbNe{x*K9TW2v#|V!q5S23j{n)HmCC)*dqC$A4fO4d zOjo*^MbUo}j(>9}d7$3tJz(PzZS?JoOpoUu?omWB|E4}N9I`-r?2iq3ebRE9h5Rnw zC%Es3__H!u$H0pKX|9B@ zHg}9#%Cvc$eI7k-Jw@nZEJUS3$7XLXo|NmU@zvnkF zs`|f`;`5ek!9L&jSle(CdkTOl&&^Pa($Ffj|pY>Get^5hIl1U>AX|TBO zPSk54pXBFGAe7zQAwA0Uk&*lpWkf8YBZlxWzge-nL_g||KPo?qIjL7Rcu+;D()og#D&EA z+*YBiZxxwD4v|L`6I%&CA-7qHB$?+o=CuyeL~&=UC^*n6yeP}v!LU}gY2+7=ojTSt+k|=H|2-Uk*T`di4r1qE@}SOh z!Xfj27P7th{G!O;wcBT#<4-GgEC@GlK^e!K9kw_B?>L_h{dIlE-)(FY@33<>QF2S0 z$h!IOqx9DB_LSv+T`#()PPaW=C*MJ%x%ajS&prSDgroPsSNC+nx3*2Vh&Ai}=uk$V zw1sVQpKe@8`KUhI47uTL-}Nc$ZT~NH2p^5f@Eoy|Y^=94^ZLwCZwF+99X6!WbX2=o-D9RcoL}CPm)m+{$q>F4+nY&0qQZsbrxMRaw2M~{wu#$mNE+MYxjp5w ztT&eG!gXXmO8ikS^T!`<6K_*yWxqA#$I;Fj2Z;}Q3ih+J+|W0Seac>=fxg>z9%>UA zG?>%BU0h5$yIokL^N-gt-odedL@)SW=xik|wt+orLfljA6n{2)|zp9W+FnJ;38E=KOAL1{IO zNqghso^qLA*|Y6K%F=uG>#etwZLu7vl5-wSyS?R7nct}6{HL+;nW(TQ(}>LX#$!F@ zGXGFd`uIWZVt$`;xot4B_c{%3p!}XAw#oeUoTiJYH3wfnx|f68!NC$)Te7I%eo+;P`u(DUd6SZrp!=H2iF5aQe!gc#aUQgXIq@QK3H)Td++NzFO#e5cgm!qFpZ`5nrZ=k2FGq|}ZC{PBIs#805K+$@ z5Sea%zLRi2bwD@?nNCA1+s6~TNy|FAo+!W^8EgwYc|h2U4hS#p$g~^t2s>dV6v9jd zsr%0J2SnwwzlY=ZOhNGhv679qVJb0|Fc5tz|4Zqne?GwfvXA56Kfu4+p-1RY#)uA4 zV*HbE{8{0DP_}>r$ViR(;~=@@ONn+*x@h{oye7Imp>{9pd5I4pB&%j1mt1 zXYrqO>dD{wbjHzVRKCCLWuG1T)c;Qo-aFV{9lePom5tA?=@4@Ie?JiU-_!rcj`XzS z_&=T7xq%MRz;vc@s$L_V#}_O9l@2ES!f9o;=kIfLh?5zKJondf&W$vXMgA%p`-O(f z7`=;8-^c-E!*bhCe1PC>!cD9ozV6`jE1ezUEN4(uvVh}w%x4KgnUB4jV9~x%klszC ztqF?2+VHmB4p~7KQea?*JQ@f%_~suC$oy_9%bh|&x4O-XAnb)eY#F@4{Xx8*gt(B{s|CdnJ`cZ>?aOd8`FX@DjyJ72D86ts1;r9V z7K~(yKiNlP#NuCrqP`|5?jZEU7DiwG=|4wSRZtumL-%r^FT=5hQx{3JamtDrkhJw6 zgCy=EW)lv1;N{&+IZ=8jD3q?C$OzJF;-Su<*wYad7Zc?NxIT!d8O5Bz;nS2I-6^7p z)Ipr@Z-Sv1O*(o=r`STBO=CL6p3$AcNbKR%enGxsV5hi%&=clrIq}q=Y4h}q}Q^XPmLKa5g#Vb3-8@F_dU06b_ zBie846i#ee(JA`pgwtK*pCf>@G2Z7)=bgwM!gY-X$_J|A>p1b_p2{%5NZkBi<#RAX2HP zTiqoBtHS9|(NV~MqAA>YN0*pMymWh)xb^`Wrt*{aE|E`MN}cnFiMMr$F5#*8R5~yuA94rhtLsnN@r3g_1@GavWRX*`XW)igidS-H&Vp*W@fG9PDV*o zke8iX!@<&TIdCTyMGbDD@tuerY&5NmmeZ3QLJKd4HsX_tIlxK5^Z;E)h$V z(~yfOVs?6GO-^eOv4OJN2$}ZN{tk{+jnC4F-m*Fe2gv85N~MxKpvo>d1EPBYlh7B`zXbH+P9W#00`| z$3tCWGO>h)PFmI_I@z(2kUdS}!igt3Zei+Oe>C z#1!Jxja}jcrhXXLKyN%pTE<)XoPQ4+_p!r8#B5?LaflrsCzcZz636gh(SBQ(_=b3i zSVf#qWH7StxzcOAfy-$IdP>X*)Z7$?4h}Ep^8f@cWZ_>zJbYSJj zjP&&`aXJlr&H=yrfOAItNJsV(H|**XXAt9v`s#4mm-sBPoHlZCPg%J95OuyM))M+R zxW;5#m%YR7N5yNXm`!h!w=rFGB%T8*l*xmv`-n$IMjb=`z*n4SI$Vu6QT7hLOdMwP z8)X^s1fxvDGl_}B4rXFF#zh_s#j1V>d9n+IL+qh2ngVG_k13eLi_w#>?-r{wy2a~6 zEiq3qx}N(rsvknj_g+x{*b;f?-3sU*vyXdov0 za41&t-O0y^4C1uqhebJ-K5$sX<&(buuxMZZ_mSRHCxIW43)PkR<9l{W?JYc_k+}S_ z5v~z?*F{WGgCk--`tN=oa$s!C;kjzmSA1V%)8#Qy>Zg~*>@17AJjOjtwJ(cFQ!SUp z*pEIbV{z8v?8T~OSxmh8!xE}}zcglxTDdI7r`j)znW%0}iy0C*%Y4GE>gkuo951tm ze)CdN7ha@Jx-Mo!+3Q&`+at@Ix5VW3cdWWVr)%QN2eyJ*QAyhWM6J+J_hhXojgQa` zMBk|qIwO|nMCe9i`t1?A@tCxlPv~M^j9xbzGmg{i7Rv4XB=7~8I$E#0536xATE^&g zPhja-y{;G&PtZGbuaVGB*6TjPDn+krz*X`y-R@e^jRSE!OGOybI!CV?g_*23auO!< zLGXoGd=3Z1Ip^wimt#9F!o>6Rx*IXps@JVV=S6zm8q{zDmS4*EPPdS-Z_(@AnD(4b z=XtMI6fgtsZM7nbFHLwb4!x+L4;P>x(@?`KH2Z4BR&;(*D-0Ks|B`yBU>aI53;kcw z5!6-Jip>rZ1`@?+#&WdnV#?8uHR!~k^y^v?eGwf)GkP%*{g{lpZh70P1!#kvi~hHp8?XvR6HpcO5cfqu+E4f9d=U9E7V0ZY;KJr^&!aSwV>LoY^N zLI*Hb`U4jsntx=b(DtK)hDrD-C`ZFj^b{@Fj!ul@8y9{|Ma9p#Ll166!`@oqM=M5M z#sScRx}P}!+AtUW=tB(ya{DjLG@2bGV$;|W)6mY32)faO<*4lATwl%(zcKY_tz(MO z+dxBTX=M8qY;R&ax-b{5%}l+_V-0E;$&V0QHBKdZF$*2ORz^(1(#FM=&V~bAmFVtZ z3enZcDY=Rc9%RJm>ZU#_hp2xw<(Pza!EK8+U7c{F3ro?9m8jt!X+)i9M^9v(NW4bp z&{+o5@sVj78dN8uZH#1aohU#HR-n^RCz7sZ3NZui!|H@b<}rY_;dLVZI`+qOv>(I% zXfU!r+AxTIT(F4kBkDvknq%sOZ;^uvv2`LUgAK>k2^%US>qI{K(1Xr6dM?XHQExH% z(RCsftz+s$E*i{rVk?@DuM?5iQ;zZI8(Swb(KfD5Y(^(~&~-wc&@Ex0C)Ek7gM|H* zI#G_+1ZE(U4HN5x1)Z3IUUZ>0nT|-6I+1V#2cAMbv|$E1F$c|4>qH6qu?h{-m?^X; z(($G2kE_r>y-qkhB$T8&k-Ur!U1JNo5z zjJlESr`HJut(b;h%txJtYXdEoI$ms$a8eL?6BRH4b@S*cT5%Pc7cvr=#{e46;#A$t z2$JhW5gN|sT%#3(vK$pV2RMgz(2Mz~JC}#Y}W#p4_mAYXV)Up%)`>!;CtSg`UMsIa-#~iMW-_P$mtc?}j>&g33~62yK{+ zcFad77NHBv(cvahO+vSf1EG?|h;!&6I?;I}6=fdxp!p{5Uvy*K?c{G}CeVs$=*LyE z{1)n?4ZCGI#@|7QmosDN!Bux~|0}n0KT_brYV=|N{n(ARmCVqcj0~OVx}EK4zJn33 zV*6?uLhUZD0d(C{Cyc8(KrSk%o^%#;gq8CaGfYb zt&sN6|2W(4CjTVm4ies{7!kUkrswxCQcOVmGfXMEF$--)TwJK(9`rp+$8tGE#dHj9 zFK|tuhE=G0sg5_HnW+*U`Oy9f`=hm#ixIu(NLWWhZ!m@Ed5in@UUqzsJX*XwcBA!u zt_{>MA&>kAJPt@dM;#nKeIpTe&PPFCSm)9o^PUoU%A-OjOl3qjf)d~=tpOO``1N7wLB@It&WbO z4-3)L#5qQDGgtcqqb>Tc|gwUgV%3^U-^Hy)ZvaeM`N_MBn^+QHt7vdQpkqbNQCE z%5hTaMFBdjSJaER0(y8gJD~lVdQpOktzJYwLjGC~jJ8Y;jE1H4B8Z*`IpCvA;X{<8 z6D!e&HE7vfFQOi!{+4=?g$g=l{$aMG1tSZ&|Lr8=3+WlAqgkyNE_7lgDg|`paYl}2 zv|}RrFh!O>LPyYp73g}5?N4x^A_jss^rG`Q+If=wia8G2x7G{)libJN59`GOHw}DJ zFUrw}KD6$nr)b9@dNJWCI`}D5jtb_Z1>I=FQgmV^xdGw(RYtW5B^kDS!w1*Be35`S|8t!F1F*IX3DriR==Ajb{(S;uLVg*|B8pLk& zU;`S~HwaxZ#W~W)8iW;M%TYt0-2SA4sd$MUpJWQrgBJ8+D*7-J z{kRG>bfM1OAd1j{ThWYFsGuJ;Y)AJ~4I-+94)D9MNhp6GHWhWx&>=K9NVrMZu@p57 zqEgf#%rCP8CZqY;29b>(%tOO-bO0^56|Go>uIK3hdaxV4X!r;16*q`@v||!#n1T)` zKVNJk;lXTlzsLd5@DdH96>DTU2GN7juh1}>(N;o3GLJU&VK!=*ht`)l=ji$e*9>~F z0=>BV74CmOi3SQZ)Ok4YD_k^a#__1&9JHVnt(bv!%t0^aqYvGvVJVtD4Wbei+=Eus z(2kL>(jkm}mHXdAB7p+)t2B%j%t0IGqwci^QGz}Uq93DQ<3MOe-Rs;vXuxDNV>&8m zM+@en6$?;T%EgB+)Hz;fhc_58dT~4&-ekn6pcP%1fo6X8ezPopi>nxIZ_^NZ-=QO= z9H^X*pa-+j`YxvcZCHqQ^vLq}m=Rfy4oz+#5%~r^+r|jck1lk3sVMWPq2+z*y~&Ok zi+)T%-v`_^(hs@1(NMu%gJxWXR&=2si_o^6YYXk$x&Nz3I4SU>8{5%?QDuw_3;1^E)|3Z<9wG+NwC0=*JpajzP41%C+$h4dVhde?~i~pbITnB)8*k^gBp2kkEb3 z#ZXR<(TFx5*8=Lk;95XCrlAwF(1lLvmz-0yRWnkwqlQk5e3y>l0#tUfKYG!HuCF-- z=zr8_(cixvHtE)6i% zsMRt;G}klL=tUp;um=4YL|r2teBVLONSNPe2TVi-lTp{ih|$-~$k2}(+BK&313H4S z=x$+((SvE|#Vk}>IYnr11YM*b+I2B4l+aNK}WePI7Cm-j5VlW5G@$Jorchi zc1%PkCZh|}W%*%7Ci7U1Ho?^`%XN(+?jzcbXcSpeeWTbaJ*rXYc2F;}k*{8maQABz ziD>W7_wvzjbfa*gH>y$Wk>vv#MM5Pb!yI%EY!sEKVK;gQHHzeqsTbWS3ebrq=*9~4 z;BM*QM$wMCA*==P2?HGJXcP-b*oHQWbkq%N6dD>ZYA5;OY)1p8p&fJ3iv{Sz67-`N zHLOO(*eGJF*v~|}Xu(|cp$EMq=)kA6?}%v>b4ZxciXP098)6$pA-b>%EypsIpRps( zLC;9)p*gNm6rqA!(LRa+pdTYYXJDi02x^#vhB1vIAMN9q5p+07G?4J4&c}h`=^46k z4jN8q6d5v)F7#p%+D>W|esqs-6iHvuk&_!mHY%8hHY`FrmZJ{?XgP)UzhpZqUvmFD zNu*HV#!R$KVC3k*O4M)<8WI{s5EV3jMSZlO57SXMkts$emY{~a(LIU!)pQ&c)J^7i zXhT~y_rHroHU$QSsX-^YWyL9tq7=ZXA~S^^EJ6c6 zU$PY~ScOjXqcw>RIliWVL<%Z1=@Dv}kKS2y1Z}5tF@8fs7Onww;T-g%RhG}^6rtw~ z&N2EHFoUR^#kt?j{%Aqn*_;}g#}f3S!%spvhuiC03NQx^=TbqM!tH`)jQWm_VH|qS zqvz;7p97=iGWJ6sZbjvCF23(6$5^yt0@~1m-Yc0QG^BI?dq~)?;y|cf%~b9oZ)2)Z zcO4Dq~x1hg!rL+HjLv@PQlq7S>}_AKiE#LQ=L z|HqT?Qjmlirl9#oP6gU98{L?PmYbMbwBO9tj2g!K$=lf<{g{HTm@V_!%nTY< zFi@FCWiJDA+{OcpOss4aPPF4@^k6X>a=3laiavDT&W=Ab5==(j9UKVln2m-zIdw9R zUi4r!T2|3v)K)VCGJh8{@C*09n?yVbGc#dD1vAisIcUXvw4odASc*=pL>KNsH)`m? z$Qou8W6_5R=tm1`n2I_lr@Dsw-$24iff)->K@VE660PV*8wSyihF{qqp9d%h3EL)mQi~5T0`y>(%s{KSYS=EzpXYI+kpp8g8j2Y?+AtSAFVZ1Y zUTPHPCfa?4`#+b2`xP2S#lzK$e)P%wt6WrQ$H-pbs~rVH+0{ zdawp{UJl&GNHG@86^tCc+c_XAAMxDLPDd*_9-2R<<1+6c;U(eTNssokLlrxs@+ns@ zIn#Kr4FDUd>gFwq2atARWMT^nXn~w0%RvsM}3@ogDaEPAR&v0(IYUD$$OS zU3BPs>UDAd>-KQ9%K|Jy4Y#81M=qv=_!9?259XlN&nZH~Uak@JVq7;<`ZHHGx-k!} zzwkhXo*Jh95cyv@mFPqpdNBKty#M#H0|k~^&K24*fNtzY9~urb!a5p2b3GkELj#X| z=s^vY#zrw-kVgyZnm7=;umFANMME>~%k3H$vqKl5^N~nHLkly39xO!n0j4S^F)fxX_3B=pIcyw2z^l+-|1h0~siq(T|B}8OzdJPFXOPk)jgMvRkaa z?mUqO(T%C7jAvaiw4Y4R<#vpYW;>eEeoB)_LlD}%GzOQoyJTIrQY-=u?qcI zgq|6+Bg>PTM3jMgGZ_$?XLE|tVVJ`dkcKcPEZ`bIH>RO(Au}XBlhxIZiQw;l=Wwnm@M4sa zsXmt}MMDa!p`r6Ut_}2Fz;bJ-UC1>ey@>tLele#64XJd@#K;Q+gcU%&Bn5gq?GWzFQa>nr~$WMv~9w zDn;uGE*4boqyy5`O`;n;XozFPT*T>Uxtl3P4a-r<<&?-gMvY?R>!^qJJZ1*n>$(4H zNLV+pVKhD8$o+{17gLHJj2}bAE!-t&QJchWv=>m{%uHc6YL757^gK$3j>pGX0S{e| zGcf5B%#bX9k`AHU&A`Ue&NJNqr6df`vH>j^H;$e^*Cghk{dw+t)V;v{j6U?E`$g)b z>m^P>JoR4Y0S3*la|+OlQ76!DDFZhSBEIx-eJ*y#&XGSm`&HY)X2c6h}_9zysJemD4 z8x_X@mQ^BQ8Q3hMPoaT9&0-EZhp?6#nuoGP7J4ym0_DS4jtR}fSuGE3Scx92L5rzb zBqmUfR`iW%7FB3JmZg>^(lJa!`*F=;Gdc_-SrSVYpkWdfZ~;2wSiuTyqgj3nbz?XH z+R-qXo|~J64Lz8R-s4%a4{c*ScJ|KSe#7Z{&$|p5^Gba za1sroZ9F4G=gF*Ug@y#Caw;8|$Qn`Tn$#=;GCzgIr>0SFI;$q3l@+OdXij3JiCiOS zMe9t~{zBVqIwbR_aSEn$yt&N4bnbtHg&tF&Ve||dn8&(Is5^rt)1(WUMK$^sa&Awh zp|fZh?a7Q7b*!x3fQAb>bxCySB1Ve-i#hi)e+dUhh?c1U=WV2%XH^ICW@8!yGz* z@u*zO(pydv*2S#Jbs8gI!pP8xS*T=kaiR+=QNw`TelsJP%gF7_5W2A#y;zQhTj(HK zumSBDc{=ql4mC_f%W{@pOCjM}&dB8k%th<1TqNj49~!c02z_X-3@*v!r*@K6+L=xX4J@oK%=k2kzmVqBobtp`LwGtq^sPyi8AmPPAwB5&uQQN@9 zwvZh*axT$%KO>a+ONQkbq{bVWFCvq`yd@bWiuD`SrIz(!`%0%U=~`? zi4H4?%_MACj2e2;RY1?t@(8zCG9!PSQ-fw!NGwGQR-zvx&qg;Lkv>hi^cil$bLdzR z_dhCVLBorzHHS{DIEVY+_A(d4xm+BtFcWC;Gz$-ESdFe%89@p=zD7sTg&F9_JhZ(| zhfu>H`dC^$?K}?n1~Z0E^vL|1TodTU*z;+pjCRgfYu+7tmli7Zd7O zLa_?X=ttXo+-_Ft;{vp9qan0o4*IcB`ab)i?gREi*N4p1g>;~T{n5Rh2Q~)@G!NFq_-iQV z2etE2K{whQ{G?NyjUJE_@Nss&@-F{uEki^_(Q|-ny8d{>_*pEP1vtv z#N#wkf<8qP#zhf)7L;`XQAyOqW;9G^KeXWOrA*aDj0g=EYoZukY0SVf@>ep2=)8)CQFpb*hg9jUa%KY_o_(le>gqcNGrY6c!w^S3cH*x=amuVv7CZ_0S&N15Tnh2uzcFyh1 zR9r;|(9BPLN7^}%g9D-MZe|Ld{5n?Ks_CU+$j1b+}fXWxFXt|pDUuvQVUEgv_?xOx4O=O|&H)fJk>Z{j8Cb}A! zYP2?Ts?d*nWO*wccha#o&SfeIdpqYIl@3irtzn05%F%~;=!{@VMRcR?ZtCk>L>fAe zY7ynAi);}=^z>^H>G#lZ{}y3K-O+4EH~M6Gbc=|~dof>dCc4yEg}nTXSIl} zXgHgWuc!PRI*2}Wp~G-)3kwU&sJp#Ibffu>7GZmc8N0JZ6ryEy zi}0fhqc^kvUF?tMwOj+JpbuRby@eTFN5>o_w0mg)t?RkSghwdf!YM-+=A-ptMvNAfYvfVN3tEJugoN&K zmRWs_kw3`}=yTIkv_4Hw3u)*XI)pyVMRQS$@JOGfBah>AY)1=bq3wCjxwM#5iykyS z!A!ltDMt5;+#NFiQVW0oBjGHe15a{pUS@>Sf3yfUT3?|fsJz-D65aSZ7Z>VE840>D z?kPHk3()-rS2bGS^E)jf6FpdrmU3=8RNmw6DdL=O;~GMjmjlW?W~1&yE@D(FI5p3*9c^fKd`tr* zoS$$}p@wnKae$rdh`P^O#2!?>X%XX}=W70uQ-oeDKuax;7pOFH;9?p^I~tm~rqHUj zh<3DL)C=s7aj2mc9qu3pBH=sC44^?UwP=fAk>%F2MtI!(7f}`j|V+r{IEKrIbOh+@TqHZqX{&$n8k_CfW`Nabo#yRMU=D=tj zOvC8M-Dn%a@~Nl{Yvq>_XmB_kL&ez2FDEcEobw9hrdE-U_7SaO5Bf3A!;BqAyXeCb zkAo49Y!yBV{AhTUQz3tc70shsMK1cV1ik#IVx@FUt4Mea`Ng4C=pRcty2o*V*Xc++ z`=j^7R#7PP{3zURbWWsWrPSl+@$%57w6fR$3CmQb=nZ;2tyS1iH=X5H(L95Z%KWLV zV*H!T2xg#tCI>|8EKWfg4bNpnXtuD>EP64BzImLQtsF43Rk)-}S#%by%UXr`E!w+_ zrFZQl%xgFW=*?pUZ(}|kK_6zLwuyygk>^cOiv9I#PWAhAu#Ba5vq^Z$I47ukiQ(F z5D+59=8b3jn@6AEE9&iOZ3`5)agcCg))+TnNWq6y2uc87bq3#$~!$dE7 z(PnHD4d@=xCTyQ#EGt{0=h!we{xkA%tOY7Hw}~Js$J5^Dw09CKYNG9AmhSY??gWnO z+>KDw&^fs{-J!t%r5uQpp`ew2=EPCg(i7NEWWi`~VXz=tl zk$`SXn^=X)yf#sahBN30+Rx&E)zm+a{n4D-CiYZ2sCWrI+{M(P6=ADP*$tn-V`x0q=(yv=s>q9g7nrtTehH>+ZE04 zbB@uvo#k2gQtu-Uj7lXVLC?o@=x6+d4x?cwE9s(EMTdVO{}tQOT1`3Xb}{v6+ttSB z|7&RI8xDk?A2_FI`H89hm66~abpPDOXE|u-7aBmzuUso=McqCcLL>Ux7yv5mw1Zak zqaWw|#({&hgEn-da*!!b2vFfLQ;bfQMvbhc!q9e+in`&f|BA}7?R@kCkK<8yGVP&-UvkPr-^6xNg?=tZfr9LJd>4F(RyCH=tdtV zYScTQ6;+X`5mo5$Ue+!OTBvAi=MxXOhz45eSq2TDXE7Dgd_4z1UnU)Dqr?14Xd(KS zG61yP+%7WOX?S_NC`M%kYy0k}{El|93VnC6d@FjL?ZSM30o~0?xd*uam3!EM0&^}i zAUCXQ7YjPL3+`_hF7$6|XT>Wz_7FP;8Tn>LfXbsxHTs|Cly!1|5)OnO4;@1D>+K?; zi~Y*lMG3m!YUlF=wEs5kptrnT*bj35`#x+JuGrgf08 z58N+yqceIx>oV*4Gx~nvM(YrEM8nYiB3e(qVXR(@K3s*?;Vepu$}#)-JHK9Mi`y@h zqx3pm{C?p?`{ez?hi-*+VusI?rY4UDUA} zZd8AIj0#%MqhWMkM#D0H`F_!jN+!#z9?kx&l3R?sH-4v^B6DUFehfM(VL%h!>M$SpP%Y&&VjS=?;kWSSt2AAd1mzV0Bv5#T^hu z$1)=G0scx(y%P?IRU;`skri;!GyZ^xk7GoW4u}f$PG*tXQFK&cwOsVfIv{-L&O0Eo zS%}24@qlPYSHS^c8^ih^20t6jjPMs4Kmp1=WE=d}nmtUwz}t@2anI_oIbd__OzJ4iUkv1F$7 z1Xi;=iBoW5hp0sJ_zn>}p8Uy_qvezi;Y4#{hwz~{sY94gX1`f%NB4Df@D$23H~^ZL zu|g_(vO7dKy6)sRHz&}}J*@ePy7e8r|4+iDvMOx?J$kZ3#7(5ZZR~)a4?0B7BpRyd z5E^Qg9l|=9`k$~+ELy*06fk60lQeJnN^Ih_u$ z@T3*3EGF2E8VeW}vWAR{1qtJlm>CuzbfRGxi&>&>IExK7$PKJgn8Z(&x>>QX0JUQ~ zManE1n%yaqXXBzyVQ29f^R1mCkHu$nEIb%M1B(uBo=eAHV_nC2wDUGgFQV=JPX55i z_77QP5H(Dh&;Hw4U=S@>fNsaIE|Ix_9WfWJMiz%c%LvwcT1d}hSj`MQSc2wQ)^$VW zSk{O-ll&-_P5Xazoex}9MH=@3xmPYCT?M^!5%8j@sA#C9RA`u}q-a=JXsBppR9IM4 zRHRr`ROI5W_E=HjF11u<*wQYw)M87!)S{tltrZ#;73u}9MP-4V_dDmJqVM~j&j+60 z`8_jp=FFdG{+zip$ofe3aYGi3WRIx%JTQt~v5-Eael;qPc4Q6Gg>2L^n%&Y;sQ;~F z*-8(PG@h-~kgZ7ntMC|0#E^ND@Q5s%%zj^5PGO_D1@MUkge<#;ZS@v%f8DP}Xetk4 zld|+hL~tGckgfTIw-}!N!g7&51-}~2$fWz&`|E1zzYlx#68g5Ay1@K8*^NKXj? zE#aOG!`#UFZM?}fJm?uV4ZM~Im$PRVGVb|bjVfd-(m$OPc##bVk!cm|hK6kY6DfxD zAWtEED%o9eDe`4@#9B)Iuc%`4H;A%V3E(GBVWsldyFb%+LRun8<`bPxHnUVF6lAKkk!*S_85mWn87w^IXFn@;VTsm zklDzjOL;>rFXO?;`pbKagj)zOvBxMvHYfG4#R_?x++)Pw%Kcm-giM>)V>Bbnkp8z3 zk@=)3GApIW*p5tEK#C!&H!kck;&LIbAx6leYl*48PbVVlaDXgAx~}6v$g~XH-%ipk z>tP2>-gr3=LZ;n7-rj+`RXs*JvO0^1Anj{pB2SP4$O>eWzAq)E?&6J**~qeI;E_qs^%&9lMBw=zqeRP> zNLi%kWgc`l?*2@Kkrh>hhpc|B$2fI2^}lQx~|x5!t-E$4I=F2-Hyckkz%M z2r}=z9wWH`{XZ$q$h?13Xpv=&Jm5Ya)J#etUHd6?`u=}CMmw_N3;f;BiyeVSdcK6$ z_eUwL4{Rg=K-L2!(bqUYR=42*Y5$HqEyUqT3Li4-dt!`i4(K(KA0!}T7ShFm+l5Gb zV6V}LtU&r~K#z<^)(7<(+mU61dyP~2KDgJ&;JK|Au`Aw2fXmKyd72o~%U3B1(@?h3 z(=w#jC_>sp30O;KuMxM2fRLHUtVjYxHY1}SBH|-^jXY%D#9pHwSr*%Cgg?xSP3mPw zOeUZWf7xrzrq$^(}Z z0Mdv3{t_PJf$RlXjBLIO9$A*(Yq(1Ae|N936=}bx*QiDoArB!vNT0`Xe;+A;%zB`A zqp=l`^dJt9txxnCNl)OQyw|8i)<55Cv?9}X@#atRfPe93$m)-H<5C{5uh*zURv_KT z*5+O#?J3-U+G~^}UElJ+%|y7JltHF-5FXO=16lVwQtIc8Jg|&_dk7fmV>xXEZ6Uyc zr;Q9`we2+fcJKy6PVBypy>|}^+b)7ci{=ogH(?&5eZR}~|AhLekX~VS@ z|Ks72Ws^=Dy~v_vr;W00=$GRknYZz_(?-(Ms@m7F&GpCKh4CnCtQ=S~}KNS}(+M(VTZ-#l$JBkh0T#hxRj z-#TsNBb)z2c*tR`0H1Q+xaqW!jm+E2_KR}Mza8WJ?03lT|LvIUTPAzBb+#{Nt1_0Y zpSkRSO#aHmx6u(Yv-FN*hP6+pRmJ?3T)=JD`~}=jxFT6X5Y|FeW9$Y&Xl24~az+s%N>?msT;+=acc! zF=MF7csb^Ie6ryN_v0An`(()u9YiLo_>1zaMWM~)K2#$HsR{UVr+D&UcGnXl8e04@}6U_W=IaP|wh3b>#PxSGE3 z`ulB!^Y^-2X$Gku(gNvofoBh#j$nV!{{GDDUBD^0?hCkBIFIcA56R?4)jvbiQMF&d z<-qA=>hG=)u2rI%2%_ZzRV6B&(w2TnQVVww?uC9_6I_<8*Fj|Ra)bJ*x>04o^?zaj z;ibdf->*o9!_~_k9Yo!u=Q~eEReJ%K0apX3lT%;O{N=(`%aFZ}alR#T>0ZZ(h`N$v z#x$+ID%k$8Uv_W+Fp0k=T(-*ky^cA);j(|PBgCeyKrD4VPT!93O_mOVv1C5Z7KRda zol-JoA9S%S+UJ;Pse&$$*;7=Al0ALFlF zmVQjE4$6ZcI~HCO@FaUt@;sm9VEaPiq;aB-8axp*FCCvWxZWp@8BWd2)^BjV`38yH z=JvV&qt-2y&PP?4#5X&_ee+~Vvtzz*qde2>7-4Y}(5pR?1;5+T`>B$233tHktZg$5dN|?T%x{XziJl*Qp+G5oP%TE*#Dydp>o9ID`JkE~VPJ-)F&QCIM4W zcT2~ojw^igWzzo~Pg)9IIc7YnlTOLHS5%N3{hwpBrS7$3#&|jUXUM2Sjyo{>TMjuU z;^o~#j=Ox5WXfme-HOi~3w>+lmCqf1hpjU63&)MV^|Ip&N>z${_yr!)#J9z9y%QjtPFzZ_DDtw1*Ay;9F25aiMEXVlT_TS-uH><+ zj}VCldFlvdsx%k^k zC1{jOk2*#V??x4-c`lvnO}c(G%AH3YQ%SX#jygt01%23;&t@T6ZPuC`TqWYqg>I?r zNmtQg`^quLFZ3f>{FP&@CHJFa#tCofF8#_8Zi)F18@9@lt;9bf(HSKBzakr3W%k$9 z=QdgKHRhqW>6r2Gwk1@q*S>Zv^9$N9);34vuyA(EozBzrrR~zzaEgtrZqvmANNTo` zZ3SK?C_*=tyERkgWinyv#rGSSLz)?B({H&G)+0;4AqivU^=}9(Ad+&d;W&x@))8&V z;67hYYk#F)7gaEovgli)+Qd%1d*t=OVM-1kRDtr`w~p}08N*`PxOOU@eXb3* z$0E927=C%C-Er}-DpXNg#Z|~(0yhnExZSZ4leprTW1&T{i|unVdp$|{@iE63OD>zy zI%V~fDnf=IcTDH`i;naBd|7wgvC6kb_8xcKJU+FJUX2d(R&Q;tXHNs+NhuXEW-%9NM*x?xJn<{U0IHnET4sAXgPucusjHQi|(;beREvf8b z+ooHLaCxMYxX@yBI&K^m&X%=@aj7qD@r%dNWXt$2$B6NTY+`%8sqpsjYEU)8jql@h zZ>ABhP1bce9L^S0+C-gcQ?&XN>VxvURySRs)(?vzeHvsh53>ZYQ|=_)OenEjIbj_H<^UUnju{oUl>uB&P6cKpDzE9B@8j`@~$HvgR|dtM?bUJrE+mTS6c zgj#&q7gyHTt5A8W+i|g9w4c1!?O05C9Q-4tH)S9@9?FhiF%@_J=ome$ihEsh^p(P2 zz+_zzUdJgl`j;Qc|56$A6K_c6{K+wLShwxC!7sDTD~tavxNntBKVjpWP_=^m=2U}fsw;Cev{-VuT7&|=5>H^;G^e+yFwT@ka1N>yyEVAXd zcE>=O`70xq)Ce{s^#&jLmD48w_|*|b^K|rAUZ+?F_c$E1Ib(Vp6Nl^FgU#|WKiKZ# zb?WJY#kyo|4=LG*u1uE9r0Z1C&Qd!0xG_LB4JN;4|3+(+dNKQB>O5DnsD}J|;Wx(` z!t*s8cUcRkA2(*1FXoV0E}H7+4eVE*>@i4%j7!LIop6S3JE}%fv3-5j)fky2zG{vocjj?pw`_Ws z3RL5(!qM*6+9HYaQ#7-4<#s={*e`mXyyvH;M+(&Q?%%o6#@8}KUjrWQ=d6*9I?x;*GSV{gVn9nE@!Zsuj3f37CJ-Ocy=g5 zQ+?^CEPOsjZ5Nx<>Pki18mw;AP0K~3d#h}@NIh(cWoOyxvSdiuD7oCO##mhJB-`R0 z`4`$%jJ1yYw|yiyM~#-fb~VEi{%l~_XV>Gj8s0y)ZAArc$qXzIVhrYhp8+4>U!jfP&L_>i&ibxt=YT7)E#8&q~Ypb zXQt(Z0cl>kB7|P;|8Ip7*PWN^d#o|c3Rha(N0)Pqv7gpon?tHRU> zOH(YHs(M?Z6&suvNnV&r92OmS&UdQzeXSm|?g^v3mC2A1>Mxeq87GYAy$0~;2z4H$mprzeaXWy)}@aeahJ!#)j(R3R2OyR}{`Q@(^w zj8vhN{Uwn+pjmdHotgRN34?btFa1){bW^I}{QGeUaFuWa`*Epo6>?GsQI2XzKUIET z5dFClxS9*xmBV3kMyilWb*KjP1)Z5WA6(E4_ask1DH5Fb}I;w!9CpdrFduiu6aPe>4RBU8mPT8*5U3*A5ZTXC8L*S|zn!DU~-)xj~s8cj-N zUZ842m2m-g3NHNuPM;aUNLUAvimLz2RXnN`xWDvEniRNhxYzqQ-5Je4-W*J{;K6n3gm)B?%tXloo_^&Zvw)mJmyK>x zpL?DA`sj-y**!*u3@b!+SznPrwF+)^zmN*x{C_>+9S*|l z&`aUsWXf0-GP@krWBr`hpi(_2j8XkKeZEFK+;@GPPE>u?hP{^!q-C`~^XBDaF-_#t zST%82HuU^{-cwhZwuYw-D@S!EZFTP|9~Eu-I5lx*(CPDQa}BBtxV|?xvw5^%aTpwC?Gpg&FWWq{j;zsznyRO6tZ}~cZd5UF z{bLb8Cdb2_8RY6%gu|uD9vwvL1IKqLMAk!3h$??M0E%*qmR=?zZNcffUKOTCNtQ2YN8tF%(b|UalT$R zsfg%oI#^aWXYVm>5-BGps!7AQ4`c(`zF-oOCAjeqkjb%X*0A^h_Hgaf>6~dnS1+4l zsWNq_&J-tIW&Cd<2J%X*nm9h!=02|tO-7XicP5#VaGn8|EvI9#RMj$jlA3Qx31n+t zJ#vbWSr0HYeRGl;HM0)#Qk?5cM<97Eg%%FeWL{=*fr}sHKEJrYCCQM(8kGnQ0yr{Lm)-Nv0>XJ%}J zZq`BUHiJNA?Wc-IwH0&{WyI%P)&&2c%mOy2p1<&@hW6qU8vi@68QKm4OUsf0XGC=^mL4O;>14e zT>a2oJzNmnnJN|wcMvXMnA{&v1wSOO#8cG@9p|z}drMx&^d{VyW<*zLeFPD6zVYgc zVU?(+LFr4U%1%_xvg8tNn3Ozm2_1!I*?kGG+v0Q^lpFKX0mt7?UoPzYlum(*hYRd; zmyFDWWAHeg?A(qjQ_pxs%5Bq?b7md)j$v+vri)2nRg0@3WZC6o2nmbPTTmMpqG_Ah+FL^9(~4`^UGukTsqvDYNy?0 z!ll7&0dpKmgxpFxBxIVYs>&R8Z70RLn zHDXdTFf#`8(=WmFAyFCQv3`AA3|>yb<;%7NHEv@xCZK)7`B6`RYl92IslM#|rNXts zjqDe67My$H`LCF-!-G3he6`;a9Uk17QkDc)uEU$?_A@?^J#RaQ%e9v>Y0?UrD-T|( z7S4{t3cDwrA9gZaJ6tLL^`*nkfXkkI&Yga}T(~T;UB>He2c}gQQbAD2}HcX_{8ZihPs><-^CZJI1UNWMMPiPVKihT4$stI z%_YEf!(F5uacM3U&I1=|GF~nVt`{z%AD0goFy;IjT>|G1ca`aGqt|meWD?}Oex9r0 z3gO20;~L<$!#&l<>Ed|^E_ABfxL9+^!Ev|tjkrDVvG8XGsoJf7K3)8Hx3NLHy)js= zwBtAx9FC$0#dQ6pFhrU!SMj!7xV%f;%wj~1aSoGFiE6B+8m>teC8~=pZNLKAlt?Dp z@1`tFr>oR2BckCF63%b%65!(D&XhAVE#cze`j^KnxLCOUd6N$p1J}RbtdBDzym9B1 zl=8j+&v;JZ^{UMPW${ck&)EyEC!k?E4Y+6_SWc#2>viS=EU~~M`EaJX!jcC}mBF*r zLQ6exr>vNT%?-L&7v5K9sW~gtfhv)m>-Bqk&Cb=Bo!Mv1jy@hOVW!)d(w8p!Q6+HM zv)smqV4wNHjlO<+w2Af6c2Xaormk=s&uZNQIr23F_%&CkFiRT>()tP>A6I}ilD$`` zg;srtTHPWBOd(Bzi-8M;yIi7<@Z_U&)M#rioIOPXlbHms2Je(b$xMzO0@ldg z$!c7n|AT~d6^9}CNaPadX!$Uiu3QderC8>w(athp9r`n-C7vf$!Zph5xoVoT1?XDf zHWotbOQ)moVG%bdN7id`q~&ZThV0mBzc@H~o78Msg;%~SI)X#u(xxedC~XNs)3 z9!J0BDRlYh&X_v=>>w;up1d+oO`DPoELePg4sP69wnShnPVO*2|Ab}-E2;~9Aqol(bI?Z1-UXPZVqlC3trfu744Jh+ z4Y$^T<1%FV0yWv<0hh~D3)Hx<@P`RDcIzN~M|YgW+f%vkH# z<)8~i=Z%s?EL0a+w!&q|l!Zj38kj4K7V4r6%$K`0)ax>vZ|Li3 zT_3D;l54lE@P+WXeQq_^4R;6*b7x+f3wVV5$UIjVbzu*G1e=s5Z>Oqh5$Wiw(0}Ch zVj7zqxa<`iDkH0l^=F|)Sd&V)Lo$1j3fWi(^q}Tx=A|Fg441poeRc{_b8T?7aI3t| z%xIs2^Ivs77ep654Q@<7cP_YGxXb&vRAfBd_Em2A?;>^8CB@vRHE!=L-V(i_B-Q-n zuOD22E*9M@eV%nz*T6N(lEsvmR$%6hZsX%VbvCkF2bV3sU#!+RGan;9IULB+rw>Qw z!MSDd)oR3*Wx&*1+{T2A z<-s+<{mo>EGqM=2K%%Zu7e~|r)AQZNT>)NwBBBYdzR)y>9#+{EU8ACHK~ECggKoZG zvDkyv4+VTr-G7Z5d1VHQ=nd|(pH%cSbKzWYeaU6UqX;g%pF3R)w!*0mGWA-uU`!i0 zrpRr~*6~;#Y`>1Sciy06v%)1o`IqX-yyIGRg)Ie`zsYUfE57R(M-EI^i)?jpMGrA) z<^BG$&|IIfVyOxla|o{T z(Z0H9nwVS6csxKnbkdwc-!0pg@;y9Zvu+|kS*pfavVke$dmVy*_J{yRO9_x5%4YSMsBrRQ6KY`B=G+{R3vsxO_c1#syX zaHViXaFb0}UUwC6<#5scxEi=xxP*ROBV5~4?y<&{eq;-zee<~~z7%vG9iTjQJt>)3 z#`AuM6_fSH9g)&=y&AT(0ImU!meIU)Tub5N%G}1S{kRIaQn*+9)vX%1nBTk4ey&Zz zeIs19+>}9H2W`P3{ehtMK%9?_8Omi%feYO#-)5-k&SG%JR?d3rdyIa)?Qm^!$uc!# z=|N!Cw)4kF?QjP#;CkVFo_3#Ixnbwl{(Gzg+?2kcGm+771+r(Ey1`Nm%#o<&Dr8DI zut@p_KFPsK_fK>PHSpWv@8}CbTkJ+S<_eapX&Zh1Kv~(&BtxHCdkKZBg6p5{F>nXr zs3GR1-6g`MJ>xe1+%GB9;M~u;jVt@P%Z7`2&TTC1<6@8naQV-<#c_igv$2w!MjQ<2 z=cyL1;R3D+P9H_t-(4$Q9bErr+m_?{M!_IW2G|q<4fVXI#OLO|*+Vl%JeTZ!u+@+=~N*}TU zu25#KP@^LnfjSjpwVGmgGsRB#OU5}EpQ>)8<(!&(QpCf zv~aTNQmR?&56U8kSI|GtLy;+iSE|dM)xhulQ#{5OM@tSu) z-uj#~Kw6nRvt*$tmD4NL#nZO}t18ZQX?1L?;2Pj=(ZTAkjn`svuNq`dMK;bu?E7t~$FiP;J)+R{q%#qyPZV9IgX7X^mIjw99jnx6TLI9&l5vrD z(c+3q6)aa|sR&C0ibh$TMYqrmY?jBf)Cgv?uNTv)(@c#Ub{w(wRXd)UGjUd#r2#H>D@KT zVM_!y?{XW*W&I&%sGMA*LY(^K;j%Y4mC_8*n=<+o;ueXxk+-e_cFWuw)wsxmz>I3Q zaY>&`{qT0UVmO;sR+g(M|K#AT^|EKbW0+L?h4}}j;v^m;obp#WaHCpaD+VY0jd@Ag zzm}<(%d*w*s9Lzn+P;pm*|_@Yv9&qsIEb!Y)@QSj$_>nWTb{^f92oSxu7j^+tI?D7 zImfkcpKB;|QBHyDhCB00iEx>4N$<$7+3GTDIXLefx$Gu2%Bjyo-u}+HfoK+P55XOj zyKhpfY>6*m-|9G}(7OuZ$D2sSe7JyjNe6SO_Kdaa(#eOQ+Un15ZryM`9RFE@(3ea9 zdy#6oM_yQ~A}@;u2fW|cwYl#6u8n?+Wb_H>r)z&)y2xh0Wxp>!ttI9~;8OIrn_3DM zaw}ZBOu3nk$U)$CS${KQ^)xj86e90crJnCeTd8-b**~q7B$V92y}fUowul!mI`p4EV-3sS52C3k`1>qE^G(K zH_5ZN(nYraN!Qsux2n;XB>)>ZR8$v3?>HnS{2m*O!?pcJz1e}){3rN9$cp! zVZFd+oSo?$X|?@jQumPTTBnBF^a<8!hZvW6dp)h|RJ0`*u0m|LQ&qPDYh?;>wm#e1 z{u%vuLhz=|db7hC&g~&|`RL4kgSWojh|>JV;6ks@ziyLlxAWN|9HXB1d0!DUovy*< z+(Ei{CZOAjE)1+M9ds&O1>7`EnC>%hKY!3QeN9j<`g-(J&+7FGmXtv;-0Rb`+tAJE z(>>~!EYt2#PD>4nQ?ld^N<}L$^$Xc>hYEA*)3Xb|aC?8vgr5Zd^hw$!vilA-!%dF`*FG;WW&{p?>!WR3Sf|1X5FJ!TK(Uk6Xupb-lN7kFy$+%V{dQS$FUe>g*)5OX%Y3Rn ztvjGg-n^ILzdotk)#c{LL9Ft|hTf}UEJbil5>dc9jGaJze(sr8HkLr^;mT!2ftqO5 z=W_?0l+6WdjV)t0@%hnhJm&qOQ^;GU5wFY--cPa!kSsc=aaeIA(i(ls#)u1QW8 zGRQ6kdQiV1CvRcB$jSpuQ7m~-jkF#@kv>rFc~H#?3;!$89oTVpg;_jd#K8px$i4^Z zW$L54YXUg_Q9r_KGxglQnd8Oi+9hg(nr5p57TG$C<$CTQMDjL}wLX8-iS+yi(km6{ zkz*Uw!ZGE*qQNA>*#LC`BI5kjqANysiEdJqtly~Sj0vwr7tEP}=)DnGdDeXbx@>gY zWdClKF`wS3X4v$J-4z#g7<1%kI~8hGk&3eD)4MC>ks>AqU2l`wLpg*^2gjxBU_4w* zNC!V7=LUF#oj*iAA3Q;RCF;q5eQkOYh?~v}H9cL#S zbza27QD8QyaZ~iU;NinN&d&PlY|e+vfXnO`dI?-5+)DjM{1D?IEX_f|aM&3-2(d`{H7uY}i8x|9n_QO-@Cj4-5|Mi=B>f7F;gekUmZqmV6yRgbXcK zQ^R(G?UCo}>*2y9WhMHEQ{eP|dR@bV-X&bPv9jqQjQ5^mjCZ2uM#|^K^f+4l(M zAq%`yPCue9x9XG2gGR}$M`mK7lr-1Qe<>|)=F|J-$%)O7%m}dghV&vDyXmzW=-7%CK z+5Mw~O8Nyst}9U^ZQUpeCUh7_z29zMEm5Pa@p~w!6XigOy3$ezZWia`d?;!H=Ecgb zk7I5;V9ed)%uKm_Fc0tRI(YJNH6lW1U^ce_lRM6?ztW|@04`rvKfyfQgeQn-1NZz~ z@(BvK{ht)@i)9z|Y<;+R!^IuOy?D`=4o)959v9bP+-NdhP9Hj63b(Y6(`jD}cSxe1 z#AfXTCQa!$JF%32x?X#c6;IM;^#aqT%Ck?Z>DGh>%IkFbltp-J^wH$i(>uItv;F1- z+v!-j@R|=FFoTmu!9In-cE9<-0qcV8SDBqJzJ`QDZ^umoZf^ADhWYdXGkndy*Hze& zIH+3mp_j^|rD{T;E|G5TU6;#srE2VDiu>>nxS!c!`~=oBvHVi+YW*u_odOBy{AZm@ zP+cTb;qqq5as1l~z-{Q?*T46QmYGlSjxBI$Npk;F3>O0ar8^uiJ*CD?iU+35rt0g* zn3nctGn&iHcOfaDGjLOkn-1@YWB6u9LltnbS90v6_Q#dVUkx0e1UA#?`TyJO{A{M& z#Q}rn%D&C&vamdG`P`1PKiAMNUJMs7Pe%QYdQk%|ktM&=Av9|Hv*UMEfMj6C0$x}4 z-$x6cHHr^|zGZrv7X=MsnYzQ$4csnU${0$;d`RJz56aZIsB~b);tubcrJP{QYZW+t zsm%L5^9_f<{@2MpzgM$t;r}7*>pP4qW%g#K20s72nmQ#P?iAc>x*Txn{40Umx{R~A zO@<1BEZ2UQcNm|`>M!)vzW!n3>Ob)I{!P@DRUBoiGjpu`=MO5vnFbfTy2Cr(z@L7n zY`E>>yOp@=^V|z>l*L==jQ4`eZt5`pgcE&f>uKMM_qDQXtD5Re0mt9mVbGMCR~r8_ z;acUFt?FuPH8A`ZS-g!AT);l^SYFzOc}g(hC)?CrmTI6|7ClX#`Fw1CMR}Siqyp{h z<@nRgj_6a~i`UC=QP)`yg4I28r>JXevCSCVdpnHD;#z()Aw0$ICV%?k|Ok3qVx!`RKwu5ROJ7<;#q>)DXJ{xg_VeaL&p{c`0qYI4*e zuzz7+HS&9k0QGp4s=!}2x^~&}3_rw5IiO$d8+-?r0JAr6M69{%fkXccF-R6Y%Xi&? z|Kg~q!+2VMxsQ;4J zvwAz8Q;tclgJi=a9R>+#UUvS+!?nZly5^;`D+R7nzIl$}dl4}6F^Me4Qq_Td9+&0i zYTnp@Pe`8o+r8~(aNffMAGMZRp7P&3fGvgMa2BKWo8@2SBuOT?dUJ>O8;|*=?+!Cb zbTSv9Ym;Hm(|c+FGG2dPtqP3!lo#K^nXlahro~t5{xScCHjyFXMsEYG4aKbUNrOn!g4(V$ILTY;K_I(+=Z3?~kx1 z{h6PWzWJhxv?UxOw9h(>PtNwdT-JQJgwJJY1yhC9;8Iysp;lQ#KjS42%bOKg%_J}# z`3iNtwH)aBQZCy;>23rke<^Es@H@C(a1o~h2a4~vSgPtBD#e=hIl0^_zwN+Sl!3#K z%H%()HI`H0gRo~$e}j*>W@4n56rmmPtbKh27}B0q-I%tTCiH*$_sx|!^eh$ z%Qzxhf~KBR63SIQ+X(`l&(26f8Hmsyh( z^rfC-dF5pqj|5<-M?QU-RxKNx!NJ6D>t7p%OVpp$#IPE;MmYTv`qD+95ib6uto<`p z(gP0vUN-+(&5DX|rF?(SiOJfbnQVn5+nhnM+@_)1DIEl9DFV7BqDp@|1oG{$iin&7 z#&^rpRb)~0QC-INRH-YhIl$~6#rg`-t^psCC9mMo=PT0?0&S_lqMxY|GW$FF)_ZfA z{2THrlYiBwn?*pI8<@qB$q#uu*e|_`JxlyrC&Fj1s)aUv*nRzJUQ$l3r&J}qrs8ae z;JP_Y`D0oAGA-EiuQ9@kZsP?9$osF+MCF2g{3URwni^OMPVw(FUNh}wl-#_NC7Ioj zRkCF#r8(^zjEYq{chWN~2m5g7a=W*!56+{lz43JwVQWWGiQ+%r2fqF~4~+ko{0)=? zudA_9S>TpH4mZWWPkOLjn_1JMz<0wR(Ei5C6}$8-KU|5d-o@xN<~uTNaHsKa{d;~T zga3iC?bt;<&qq-uL*7smZI!?PJ4e)>9a7rlwl@gJgMx178zh%L)}DQ4-cSx}5-@0} z9C?FoaT&NtCRNh`Y6AL%$*tAuN?YhLTA>l0EKxMO{~uQKGHGyy;nG>HF0+(@vEI9x ztLz4zk}bQ*vAE+pSNHBFR||o5j%H`VaTwQ%Wh0XhY^v^m#@-lxHtm5%#x z{#xNOU9#a#6*kxB1U99gUi%4!+kOET16K)WL9ef5{u1FT;9lvMRRjK_oVH>V0Z|+S z>#cT|{)NvDHE;!RX{L8PBOBpr&OjEx<-?VF*Xm5E(UahCRkFTDJzz`kpwMwf^+&RQFpc}rx9Hwg!m%LjEi$Pd z7&JjvzC}aU3oe=<&%Q;w8Q!U@+}m&Q)h7|?Gf_T&OD(pRffJ|50y2G3Pswxuv>5`n#=X>1ETpD_;}8y*3F?0tFf=8fNDMoKK1{>XTWFwKlnWO zLio8HRc}5(|HeWGRDz-gh0YuOV7=Ru<}2XcUJqy8>vB*FA3d$pJ18;jQ9kx);UN7r zM(You&;I}DW6+=K8lcVRw!g9VA=;z6GJF1}i$5?tUXJ{YaalH)dAV9zLl-{Exb2l? zwUqW6V9F)3p_Ue`6fj zoT>+=UMef!R#R=Kz@e9QGFb5aBbyYw{x%gS^?M!YvA5|@Rse%$$*gyn2ljwdXUpby z)b#1GKTt7dbJjA^^crV91L&TB-bj@%U=e~f;hEvJs z{Oa%v;F4u_9jUKxE4eMvx8p3$z$RH&N7{LS;d5nk9VI*ZN9|%y9bM^sV51CqS6v;^ z2<)EEQQ^J>;@1#tPYVvvNzn@LmIvR(b=*(7YqIxUo|FM>yQB4?L12Ap z?jT(41zbB^4ctYhD~b}b7mnZP{eztmLQj!R9J~HPU&rwu%4JJ~D^2TU#_=dWeU@I$ zmBRUOEc^T3-6U4-r5RgTPm^&7MX{`_=i_d`FVruNW{>Q9R01*_E)Pz;6P|nPS*e!+ zcThU&S=n6H%x`ue`)Ed2^3iFeMjU&*AN7Leei+1lI&NrZ04zV_V_c;SRGB zjV&LRyidoc4X$97-2XoLuX?mWe*JxQo3#WOy+$JcNn73w4$qdg|HO%ZuP!3b{F5pi z0}Q=M-uoxhCt2V^S>MoC)JnN+mZ%2uz7`n0Ru(t#oxBB{wpM=nC)46d#3$giuHnx& z@Mft%@~}bOVBHDKyIHRMfXB6h%jND5XpsGX(Lu#m>VYXiKAdo|uJi0- zX`PBLxL7zRSYJ97n7Z0b_%SVma)C_R3bTm?pi-9HL z{E!h%H83&1lP;XO5zmSbDLCzLTjjwI`8MJ5^QD5m^&y`L(txS=$hRM=<(6u2ugv{O z-4JLW;On#V-cIA?0Wz6#A$vbkGv?+)p1PkS>~%!Av@C(^zJM!-^T3sxu5=PnW8exO z=w#u(x%bkF|L7QLzw+RJ=+~rTPKxB{f5_Q9V4YZ+NQkY#m?D|b#EaH~+2N>3&9VAe zi1Q|Sx{2x31aSVQb8*VxS*dV&a3jvGI(d4pO0ZVJ$3G;q_Nw38lB~Wy?ngTLU68qb zQ2krZA#!>zjY}ztyhl6fA)EC#VV|;FYT?+$Y9C!K|AD?fjU}B-@|(*ytM{pROFG;k zIkt~)Yx%&0CpwuOH8+Zy^068*IF=~Y!&_B4)lLo?%A)V zT3vx8|I@N-KZB1{Fyn&#l(_<6+tZx}n=k1tE~5_6`d4eGBC`(Am+u8Pvq@x^cmKsV z4yY(w${=#@*-m3fzZImX4=}S(g(Chrnf_m%aS+@ntN)9A4+^KU;EESIjf>e~lWtz;ab}X293)rUQ508T$h{52iw7A)#1HoMN!g(X z7ef}aJAqF*Sh^_@M9byWm5LmRk)A+?AlV4Ne zgXRP$JUnm#6D$KdWdENSvoHEg4YW1kD(-K(pSJr$5_sch%HsQHS-qX#`c{0V{H@_b zeSMPtA+LU>CR@|MJO3d^K4UA2tR*s~P%nx7URejE1ZT;Z&naIGxKQ<-thF#L$St2^ zAbi*srMzA?f3DV8bHFuw<)_b?GpPhO%9JlyEZPp-+T6+Rk>*~bMVC7LrR)n88WtYP z)Ax6t{T!vOR2*F4etGW;Dn|~u4Sk3<>|qkpqGs9};VKVw8f#?72KE%)(1KwK9j2eP zqlL-3bl~=boyH(0>y|PVc)CU1Wow5F{Zxe`x$Fl=puG1q^Qq4t<_+S9`}*X3 zChs5C>!ZK{Ei~M+X+9q-cU|oal*A({#~SX?M}5hwM|fNkxL5Wbp@>xg3tMIKmo$6_ z!R@m8OBz0xqS76eU0+i2lE8IGW#5--xwS&`U&-WFb*D`^eSM<8))kMr;Si~7Rmrvj zxHh;N@A97Tqx^cV5iY&0)7a!qgu9NaCDz0+tkXC0(NQ(sRsgR2mT|V8x{i>sU(tbY zfGhb;-4FcXBN2$*-xfyT4M`S_?`TAPjXln#E{G@~M?nc+dm&pxnYI;;`1czJw+-Lpx?xD9>Oe7PN;bTteUXy8} z+uK;GUJO_AOQ-RacO}=PZ#lZ2_@qM=>PH?S{Vxct&i zXR#bEDWuDIU)NK=9l`b$-g)U7_){|b7^T2x6e&AQHXmbXlLiiQ%8_GwN(Jm1(ZyPA z^QUHWk2A<_hf9a+kxhF4(dUk*DU9J9AFm%_jtB2$JeV>_k0Z5BN=Kg(E?*rd z$BV#0krI4@Nyi#+Ok|faR8OIdlABNP?b#<(w|yNz=0aqw%4$s3&m<(5v`I-haAe5QP=le&}zERB=S zPF7Ylf|I9p(aO*;M9YI+)Z&~N8l-p~KeJ(v@TeJ)O>k*5y1d=I8@vTjCrulC!3??6 zqsB(s$Kz(~nW^x&hX-&xfVMO-@Wl!8SC8&4gIlD-!_cW3_>Rmx$xy5rSehs+Ptr4s zo1hc$-IKg=AuuUP0>38#8^P%d<+|@lptyT(ioMhvDeHIaMt4Xyb+eKwb`q81ny$0U+V$g-;C5ak`?@KW zrQr6ccEcu7e;}XYepLRpop8<9cF~xdb9FcVs3HPS!PTU9850M}Z=3ny;p;!rE6A8k zTHesbXJR%l93_K(QZudfa6v0&@lR^ACH-PuD~|r8ZnV|`vvOs@&otKU;BLA5XTHpZ z#$g`Tb^Tu-3UoB%(2@2(>v=X{)}39c0RQ(7{qK8?y6AMpuAq2)JVDh zl)5C?pWn>Z-qmHi?T3R@S@~DC3;g>j))Qu;aNQ%vPcc(l1@4wheqn7x3oz+{F1n9f z3NWW;GqL3tH6tu(DurQV*V$b_(g`meZu>_0>K8s0Mj$mCuMsvFG5q5FH81Wmj|_X9ud z)ltNR3Nq6uggN{ZXTrF0zM+xD#UN^3eWpnls|&g(4Iz!sV5>%2Is4VbW}%llKAZ0~%X&V*k0 zEcoHx-_O3}>zomsei1TbKYr9=J);u|B(ZJ z&c(Lv;F_i`b__Mg9Ek(i39t#ywYST=rpl~XTg-~3$DHlxD$%+7ed3S-&hgfSL@d`n z`PTsFC~Fotcb{|)a7G3egKIy=gO7JF!%O|0BdyJlna#4&-#NyO zzr5q`9Baz}M<3{7aBI#?pVr>C!o~boMp>L|ti52@r}BiwxxkV-OAlZ_vpA<&ih=Z^ ztDZz1l_ScQudfYzg?M-e8aE`D>&!(~XQr--3F0kc;Q(C*&0Mz`A zQLFxnG}`7IX01j+r)!qYd0kl0mAw8}U1#UPbp>(3g?}ZxY~*(?xZ*4M)#ePdmV)hH zOIV;YENmw@?dx;?V(?cFm-@9VX5Px;2Di$6fzD~x=s6UVZ{$r)r-6Ifqtv;|Rs*d4 z)--un@Lg^7Ag9CXfy@0)HVkskvc@NqtjFa2K_p=oxbT>C4stHH)`L@z%i_xD%Yz-6dD^0h1k2ombmp=41PQ>Y`^w5Nvrr zFf52|Pn`=b6)5=TaglShr4iUBOD}RhXU$2WiT_1@x`^^!1`hf~BJIvmwpx?#GX5d6 z576nj&F;L!s;CU-lc<(*LHbXyLje}Kp6 z^-kan9_D0iC|o_9%gg{iLnG_q7@`kz-fWFsjN!A%JHwn|GgHA?fu4TfWcA7g=7jN* zgKjIjB{~?hW9MCjpwpok-60t=oOEaa#stYV!=0De{I8}|1bK{`^zParQZ?L}Y|Dnr z8SG(jXMXZ?I(XeixNN$x4k~sxIN>4>oB5l+HhIS346#M0QDESX=;2c|Td6u{*h=8K z?H=PtJ%<`9lN6P@8E)rLS*gea*Anb?i0slh51bn!zbWUa!0q7T5RdTzE!Jmx*~QCx zVT98;($dj^<-zGHtuO7)=UN(XxFH&IX%ij_w;k>= zZzTU4=5$)J;SR~kFz3j~5@6+UkMXp2uh(?3P)lcC1$?YSCXaCPi+OOhLl%s1US{nD z`>-+72rNx_I#E#a>ImmlYdSb4Ouo{%6kIey!or=AQPtqsaF6%H3B{ueK&HB|RhMK)7?dr3lvaRHfmON8@sTljStw$UEU z$BsIF;q!h3(M*FYjFux2&M-?Jn3cH^&TDOr!1ys9W1j4eqHW$~2^%O6MpE$NuBXzC zllLO2GlgJwi3%J^`_csV$g+{n5jHo_HN&H~WB&=O!S36E^5RJ67;9n%&z~(H;oepX z_9T0lsbfVvoeP&U+}Z%A=E^lL>YxXlJ5M&aoYzcFSw=5*zURCjGG@Z1!JWxn-Sf?Z zOPw#jxtxS+$7v8Z^k$;vt)xCu%-n@k>0Y8(P@y-n7RCsTda5M-`w z9`77(2?u-RmGRD1)*@i(ItiXY1e?K$x68^2)PwLF$%8z3b%JxTH4j{vC%;W_POwyf zTV&Ei=R&Io7=D**nCP53IE#43W>ahmbg?q+^SW4UZ5dqReI6#5%#%nyh;@z|oPgUF zc>4n$8Z ztf6a3h>h~cNzUokG;ny49GOHBEd)0gdGvn$`sXpO$xfH87A|^|hp&U?lDoB&ovd2C znPUBr$M{0bU*&%=nY_$}i+k8(jORCZ(F3vud?7o&btpf-U9xG28Wy~m5tuoJeh_!3 zWc9_)85VmEMM<6q+ERh_C75m*vXQBU0ddZV!0m9wk9&;9vC?^vHDrt8bi)A|P_3IH z^Otc?#X09#Qf|Qz%O`Qpae?{3m^VGfv=Hw%k?~WgsSS|o1G#33^E#{RR%*w;W!Ds} zRUWupPET=O5mp1tIN&+^0a7;&jd1A)f+r@3zdZ?f3hP0}VbrIdguosSj* z7O7lHz>4KoQz%fNK+p9Og1X+ty6F#r%%<^oL4RsDi<^J9-UW3f z7bK1-Nys#o6dFa84ken+4KM4IqvCLE6ru+Y-|#_Pe3F zN6pb{%szVMZfFG=pj|$HXfij6bfM7QtiRp^tdIuxV-xjJbJ0D~%l+6umI2aL<-akF z%2(ysffdrlerUc0Aoqd|+wjTu9VqD@mSCs=7V|4TdJpSsjB=p(fAwRJ;Z&@|pt5^d zPvazD9$+=<$>N)mS(3gKke&J`vu?&pkb8gghX#mAxuwahgTCE7-l(@Gv(b^$K_=It zzN^d9+Ec6kY-rqJfEzCRZyaOFv-vbI^A+e(*j0%>1jge8gZU{m>3Z7LAC)=-w5uLf zg8J-%3gPe1EXE>W`9VKcqNsu^bpXEbG_djpUio2~x`WmaV0Y`SPxG$y=m4}`7s#lq z)Nvr%)M?Q6>wc^gR5wGd9mqQC6LNSFzc-MLFy??v)&@c!@JolfP`5#>zp)b723-Jq zivCh$^mZKb?iz$fmhcQZ+VDWARv7obAA|^VfK`!pFni8e2Qr~WfZNCUJsRF0+qa>& z2V)SIIUg1`IyV^g!wqsj^-4jzIt|iEPo$t1z6#P483SM(#{2;Lr(#oDS&RT$acSiud zyV?xZ6|bFBStorN82L0T6*c`lNNf#Gg@`pTM0vmjn95)R1id{W5US(zL%8i{2n5Oz zVAdW1K4-*-7|#r0JtAYCLrgsbA#Z!p{ErTSMp6Xu(9i%j|EX)^u3d>~MPrAu8OENA zPwvI)j)&>N-&_<~9GCZi81 zxQz`p7J@Ww2!zaBH%y_2$1^Nd1a^cLkB2}R^dg$a#sKDk)eQM)JywJU#BD znbjaYv>=n^862xo&|lH@Ovudrpnb;!5cjGIJ?{Y|KYk5Q{+rX&ot}ViiC>E<_kDnOKzuFl@d+4hJAf4fyBjIwKc3QjV27#AM8sJRau!XV z$krRPU1&>Z0wGMi$V(hs&@EZ4m$3|t%(DTEhR}-TV%ynS&`4s}p;`C>p`Lu`)Qu{# z&?1Y0Y0d{i8^np*qaS2<8moD@pVjZ;<8If3EXg?NC6w1M0UUJn*Y^FugQy5@FeXv2 zhuCQ52N_irxG{Cj+er9&E`ryAt4WGh8raE_F>e{@D04qu6vkalMKk%03CRk zB|gZX&4xcM5C|Pa61mCX1-?S-`7nN8;@L=bVHWO89NuycXdJ=;dUQ)H9^|{DL62xT z;s%Zj1EwR2GQP%?;37&!E9@Lr*>wfdV(>ERh(d)-ZD(5 zrD2b<_)a(rG$B3OjNR_I2nA+{k?P9+y@=s(pPJAZv5lm>2fq6CM^Wj+Uj?IY4fdm| zmpH17+DGvTJhL;wj7h=~C~QhAUaI@yxAw0QHxwx}bQBGBG}HK8b337^-E#-RISVctz^Ia?4zTJmvv3Bqn4L~WXF&5Q|mtPw2EZ_rg z$mLda;xQJ3rHEYDaDkmMvL@7pI{%X?)O!YoY)61uN7eAd@n^7mwV1)4!D4h_J$T8p zNIsF9@f!LP+`2Ubrr=W0jt405adhofpr=o$35}qoPos4$e;kUM&5buqrf(j{(6s>c zhRGC}4cZGDGiyV#*+Y@$tKe zLrOeF+h)RGkOA8KG##4>Bf(zK+0WF3I&nQ8H--*HUvvMH?AEbXMC=DMV}1=LJ@7-d zmg`D~iFKtG-3lx#MXiQB!?MzmEpe!udFWqWXcc%YX*=q{eA@9OTc}ze%HXe9SQC0r zol%M(8*K|~hna71Th7SHEQcY-sK|z=~e1!SGr&yLuC0U)RoorQZWa=_=|t2YugF(9Xh| z&?O4YMHaw{X)&h11qremUru{Q;blL}fv_k7c4$ov%wf2pDUMHqTT4Ytu-NR+ZczJY;~|s zky*eh-mVG#Y83NK7ad$B1DNqQN|}e+p0oqf;r$xEwTBzKzLa006?qf7JHLWAZV z2-E#E=P5R!^CZx&12y76lw5HL0~Z=Oz^j12NmG}jvZ{CQ8K1@{9s(o%U=3Glc`Y9E zG`_@CirRXZmOPC-&IMg@3=)J-l6Ix&9MrPYz?@&xs2n!MVBHC+_)prE!=8#P1D*C= zP3Ws|J`D-;@)az`8T}0FYK+*0jQqX^v(15Hc+2MRV0?V_8P+*66O8QhH6dLXHbG-= z`47+F{ceCgFHrP+_9Cq?%2f&oYxS!2>lgtQLB06BZT8jRu*(4`av8vuH7epl#vQ_$5{MWg)^u{0-8gHO*fLlTi}rbW?38(a2{v zAR!jAu95iw6Ig9%QwzeO!?D8n%bw$gPjGV0G~_uLz~c9!`uCuho`bDnI_QF)wNTr! z&<0z?k75x}<8$012}W@*>bMA%$MPO5V|{4LB5pYb?Mb5F7GbJjJLrhJYeS9}bgT!a z3VJPu4t5owc~C9(tEh9&&c)24q`wbMbXe_;bAaQKsgr>DhtZddG0l_@I%{|>zw~kn zdgfb}Ku4GVY@TOYnJa(5LMb zod+G_DrobgwV1NN8lMhSkjG+-$z^=JREvvtp&4O`Rvv3-%m$Y9SZydyjEw?$Y?`4O zSosWk$O+jP^LI4-$LR$pN_r7!Yj!Op4nGWi(^3{2xff8(6G&@oUKqF2$fd~g@DBjy z(o;+Eyan{4T-ve}HNXx!b^#q*ivFP(boqi>?2tsW?Mi)@v5tvVz_veEd(#^FtH9jN zury?#=|hyzbF^d`#!6YB;}_S4#!(+Hdaa+9v0mLvIF?r{7O|@HQ4ZKuN3`UZ!P@cs zVeqGeZ`0E;LS>ooJO=eW_oI5}*WyrPRc+k!Jmg3=uno)U#PjUFK3>pK1+_Qz=@q~t zfHn2RyqB#477px(8~2ReMl13$&71TQDqjI@%SW!*K_4lgWBF`sKtG7a)gAK|42+vI3IgDrnamwJ_SK z$Dl7?fpK%P7j@&!T4;mni$7X{7f%OP@+N(=0+qKAv=4j>Ej42t+o=Gu>@+a%TeZ+# z*R_RR>gfU&XG}PVYbS8|K` zKk${iY0FBKPY&p04=?DWS0U$(FJfk(0$9QaG~`7j<|=5{2es%&$FIUN9@mR3ykpN# z&%$2z`;OQUIyDvh_z+~qI&FV#=v{=76PfE!b5v_^ zJ3xoQKM%f{^D*4yhpqPn=>uN9pT@32B{v;Hh5v|_tb#Fb5NO{=wYc+0y>sr3%sZUbbS?O5XwOpeoQHaP&mUsg^vGmZKzfh#L7Z;OP3^I z1>RaQ-=^+z=BHwb30WI>Sj2ju5R+xIK)bzkst`40JLuelwJFKqawI6UAmL}ZyJN3Gj(;a1gguSQszKsS+kD4WGMSmtNA*gI<9B8wW>g}D&eow*M%yZ1)TE| z+oAV-rPZ9Hxb!1AN&LR<6{-3e9zwUW2m zz@9e790jLM9WEABEp)p#pp{GqR?@Z((@^R~RO-&uKQ|yZO2P28C1oR&i1=ertzzp! zKaZg)XCN&2@&>&#JS-`kmgTbLe#9ZsVz>RIk*e$KNZhsh1{LDHmB2rfmPuRo;bWiwNtJ#HMs>qA>Yn$)H=i)CN z{IofBAzMq)A^fljX4VY=Ge}FUL*!nN2@C2%3r27)D3%i6MG1@|_KWdwIi$qLb+CG= z>mer>LH~+54q^I9U1*-@q__0PHmBW1Y)s?^Fd`1sh2GF{J7jx`dl{OM58$lN_Kkg+ zb6-HIsSZw zO*Phmk^O5OIw%xq7h3Tu8*H3ZfkOVhF0_VHQT|l*DoZw&0m}q7U2NV(jWW`>Vw7k2 zw`dI2b)geNEL#`iScKKZY}y?KV9Z+Bl!dnE4KL^m!&ir`QCIXK6(!*By+pTdW}~_X zL7(^6iIsI~E94V}<62HbQ{*i%<^+l;P#2mLP91|#hThqXIqPhIX_x85W;BGopsTJ> zmn~>YKF}HUG28^HVl!USs{@yuhvkQ`ZagtixXgurlpsOulgiXw$c_`#<4EDaN0KxNUhEhA3P! z98Z7eSPrnF)|XM*xH-8Cwb%+1oflYC8%o^Dmgv(?@nx%fwxXF$2U(Cz-)v>0BKLyM z8gMx@*+6sNVqIzUHWp{le2)yZ(wuE*>^9J)Bk904Xvf8%t+vad*SYrFg?hh^yr~A} zo`^FC*zm~Y)6jY+UkFM9bh>LLbIUFe>-V5hhW%=Ze-e2WcFO!uK$ZM%GvE;I?44Or7AXkC(v~dU%^tm zCiS2Vjd>g0YRr%L`lk^)xr0W%!-gvf=MgC9$_=agEPTu$ zV7?sM@eUujgSM?Br4*Gi;%9_icLn{HIzUp_bZst0Ey@Dp(92ga!J^I(TrB0*Vqh`F zS0K67Qa@Xbb~k7zTV$~Pf~cAtKVMD zO{#77LVO+qS$Ri&=vZrh{DpdW%Xj+y7qyz5bmx0e*-nFW-Cd8lZq0ckZV}N?8_`W6Yvmv_3tN>KMdG(?B5#p-x zOJ!JMPy%rJ0=n(*=!%1&_vY2p*Lz|*iCs~v{|*sstHC!fr2`0pt(WTyN&z7aQ#@18%@+j9pew81w}NXY=5eU4NTojvW{cv zz&4z(4_y&^?Y=(QKAf1nP={)zGp)MEwXxwZ<7CVTn0H2=V~ ziwlgFbPZt)9*{j-VEZq7seAfWt!8p&Q-65#**>xO#BA_0BZHxrZxNR2YoD;%I}5I9 zHQnxSddPQ^9>R5(67cuN2GM;(n~351K`To6l=Y2_xQ_bXDHwXAg)k^>{*=oRfE9NH zvFm31F$^v)ehN|V1y-CuiJxHz79WBXyfYZ;BkU~xiCDY)x6d$E&jBN*dk_~+s=J;R z@yWmN&tWh-0*13kF!ZYE^QL~zp4QLO=rm*K;1_JR!K%|~s?l1%U~BXhp#PxMFA-%O$e5u) zSkDf=feO3$OUy{6h3T+Jeh+6)2bncI7>X5ZE9$?5Am0ltVPp{dns%PVbY|LDFfv>P z<^)zsovp~Y_Z6*fU${EEw3FcL-wp}coKg(Wx%N3f2f8kh$d z_L1M1S6O<5bxKUu>oj#^gEzV_Ue_~#`I})}mfC?;W0Ct2bm66--8PiHZ1ek(QwyEub6R{1mCph)>S5Xf z*x&?RIE5}9V~<8wfzFu`47G})Gp(VhEcqI<;Moy6P54v6&@VSsfk^uEYxY276&N`S zgP|wF>A-g|eJn1A=_A>Q@>)V~mcwY}0DXE1ohfH88Z?ohoiyh-rhjapW0wVQbnOZF z=IOvJKp3k}#^fkiGJV6*6C1s49) zfh?i8Z?SYCqm@o$UKI@O<3*11cfQ5c{B~dkbo5)y@%llYULAy$Lp?;ra)QNUtEvuL zRUbTo`9LSgN%Zy!Hcejzayzy8j?L9iYK^Kz%fDk!>W_eQ(B`us#Q58Erm^iEaf*BkWqgNVlA6$ zOtpN^67)&8=rFN4`Fl*t9s%ht3qre9M?=x)F&61`n#FaAX@?D19|fE4U%-5qnID3v zj-r#mOZW)G3U-^(209kuCQ#}%G#1xsW=SjtX7L7Zy1mZ>Y!I+pP(1D z6`zAOvk(mDH^I=0w5|eKeB>PKsjmQbn68~etu-r1;)x(^zF6fFPxF4ntbPHoI&33_ zu3iZ;?Ry?AZjMEt@e}G{d41=Nbmb?kJgEle z1$IVEqhrhvNdwO#ACqHw9!))u$?<%UxwP{IGf=TM%>IeIACj?UoBz1s30l zfA5$JP*o;@v{na0{}46KT!Yca&I>5E5-<+Y@e5d~Pzf?V5DYy+ZG6xyI#oflNHC*D z*95szz!%m$RRtki0xZ6k*C2Ix-cZG!G+H~O#a{_xn4}t%oxh^R3LB{rN2$|F`-*k!BPe4J6yM$8AxC31vJ#z_lsu-lTUjxR@oj<`?NZo&T5n+t6 z-OxJwH(Hdck)^{JAm4r4>F5(1|Xv=KxWgm0Bdjb zgIqMRA@rHp(`u=Kp?FYtNZlzkqXx=d5$H@hSc4?`K~9?15c)|hupLl~4r@>k1bvKV z)IzA_fUcy?wdj5Kf=rk}XKGPV{h&`j-hiE#IDxqf-CM^x8wd47gUN2dMa}BW-Re42 z%mQE)w5N_eZP4^WozJ1}m!Sq^fVMx=fcYdWr-PSSd;MOJ1@r?* zV>!s;RSh9|$lI=o5Y@L|flVeh5v5VsfOU6j|2OFhi`8cWE270$(83Eq?xj6fu!gD{ zq?%p#5%nS zkR^02h^1GteeeP68!!$~^+rbnOV;NDtE8O`SZ3n^*|UgFHLy*_jJ`-&aRbI7>OQ%` zMyw*s1-2bB3zPAOKqhadOO4Qt+TF!pF!)c1RtLygZ#RU_3sdu+KcPC70E^$jt0k89 z;TZBEn7B;5+#d5~f3o`w2}$6V(tTHv8+Oo(N*f?d#ygN}t0NU7?YfG-x(p07%&X`} zZFeJ#rvZzn#o7GV*m%PcV5WEJ$~D&Aconq&-3Cm=oZ|zp)azJXncffY*xwL3)85m6@1|r8^k%x!U8^(i!VNh7v3N32)su@ zi}g#G=ojmkGMkn!@o+s6&P@+!@tRDKRkT>E+;1!e>G1Pvh_;XJL#y1TuL5?6+US&f zjXejTIxxF!TR}Ag?l~4YKDbw`r z2J!A^PnhzEF&AWhN+X1nDv(5v7_Q7VmhkCg1|?O02v`A4H7HN&lkVlR@3=vEPQMpq0gZ2=eBWY&6$0z=M*72# zEem5Jlt=XKQq_-%K;5u|#NK3(#!`^h`Hh(MSB)&{6#(;$N{46%-W&uoJhw6QrRYjp zr(%PsVI)7zWMs5Y_k?%n^oKyl(Vi#;i*rF% zebU&pVC#=4<<4k6fKM8Z>UXFyw97TO0O zT?~fC*BI)@O>ej$xUzkFI*unIePCP#Bhx?~H*zyE|D?Fq%3VflIyk>HhCUTrdi@{6 z$S}JaE4fy;Ryr7pz|FZpyIL!E7!QF?u4)Wz=SInR(wdaV4Ot`6tKy^*lX8b4A9Up( z^omK@)gpNmgtYcg8rMdd8tI0oRR3q_zP4OoVbfb1Wr87oH0o@78qikhXS9R9+Wt>; zN@_2Rrl;JdabbUDCBhMX71mj1$qg9~60D@d&qkw7^Yc zMfCRJ!nHgpqIY~E!ugMhEOy>1^FTgtzbM{k7RiRSV3>%oe42Q`RxQ&j16t*G*@la7 zcBcsEYS#{#6qjduK_pnq8wY-iCf=sHp5-^=D~4DT!kZt+lMj@CB63Iu*L>FW;*}zN(+5;Y+_p&IE#w2|niBM@ zsI=iK{;)>#hh(^(yE&qe#FOW=SHH+1UAJ^ArE8ii_*UsUrCUY~cPkUe+vbaOTcm59 zCknvPR=8e8@NM&j-``ERB!+8p& zzbV{YALkH;Nr7q~Big*C*R5)uu$&cqi^P2=q<^G{ z$N7!O1M4_}TaOFB>A1>QG>$Ifn?1|K1MVUbKtoH1DeYVOq-?RSRAtLRvqLmB|5L&> zw~(3ePlK8sjdZPpMRcBT1n&CAz_W6srHx33Pd0t?RuN7-j44u?d1fhWoh!w*c~3aE zKx59Op9pW?_uz2lt%#}iDiOc4n@oOhksg0{nJ$ZPy*-3$>nU8H3~$rOs@hSwUirL6 zKIfsS3w&#e)Di*#KxM0lHYEkoq{Bjo!^#phUC$^Y0BSB@q(uEwUTzc z(kajNl8Dy&zHm*Wu&^CJi*$X1WU;?2TyLs)jpttBnit7rH3|W5vxs~%j}rOiyH)tz z9fWI|Ec0Es4{NL=1>i{%0er)R>zA&1tnhmhglicpUTjMguJ;33@9q%^asMGcpnMcH zj#oP7na9ZZWr6u+zFAs`_{y(|=S{NWxYmpCnh%BR{6M<@5btw@M0k&M{nE8a*D2$7 zKCh-HPh*M}8kJo(Ag|0x6K+P~KdWr0_Fm!xGxMOD@&(5U8L2fK8w?WM+m=VjZB-Y zElw#^{JlgbYK9Bfnk$9TIPsiDR6g2$ztTC+e;j52{QND%hj||ruH$y`!FK7IJ{2G8 z9xiZ;y2=R8MTkV$&kEcx6JhBpKEmBc^2^10EFERypHai-X?)#9K=WH70yQ=G=aV_+ zyI(XBbDH4WI*FXO{wN~U^q077a@Hb|(|(dU{*Z9J*bT^kwgeI0q`FWY>~uU6ZO$@5 zB-D1FZ1cq;*E~|>l}p!hw|L$B|G*LyxfVmXu9)oc0n~A~It%QV5iHmhq&>j9Dv$M7gZuE-B-!vTEAZ zt_|noo1{?k$QL>yWs%7u)yU4*CllaaE)we9Budcf5UzE&a4nU>wM*CWo$z~xiIOnO zft;1QG<$;5QfD&K!U>QMHrf2jWz{b4Cmyj#Rnga57N$kG&e@_?`EjWr|CPsyZ?`m6 z0+|<1>3XER@=1AaiWZ+zK2UuwQ{xhZMl)H|0+V!okBHh~nk;LHY!2?G!dfq0>=`IB z-TAysh=D7iw{A*NV#3NZcyAU*WfP&0dRhoiOcp$Li}2)TDVENDw|LZ-D_pm1?*1LZ z@24-al(U_ko8=p1FwY6$x3{|y>_MfQ)<=N{m5F(#i=s@;D}A|3Z4^J&g1?|A*=Eek8y1cllWb|2{p|@gm>;8~M{_k}_B4ckEj>N$IH7 zY3ga)WM!<*I&5FfWaWL+lh*d41~$3wY2wW$**cqC`!Z3rUH=qK#3x{f2N|(shz{!M|mX1Ut+Z zsg4k-XaR~Ar(P~lMrge>?>VItB`gGl!*LcWBf^{-5v+`3J~{_XXS+hCdT; z;+YXzClB6`DO*dR>1iQ0F2De-i z{3cf;qx0dmU8NhdOK-V+{Dw>G7Aw6K&26H-mj^^FO|IovI<;6yWR^Xmp}M<^a5m|} z2(d)z-PyKVc2RczvN&&!=^>|*5>|emxbT`q7*&@rF4^ir*u719$Tc}B5g|E z0`Xk=O5wVe3fCfCr&IOQi073%|9?mXqlkRP^#431l>h%eJJ!FaYct-~PIMwBF?_%g z=c4?Y^bVgikho+oSUz9YkL@y?e9j^}A3tqf4x_fUSVU`=uG=nxo26~sF;Tu&s=VfW z;rEOagAq@<91czv&)M%6e#^bm?I&E5Pf2r+pL=}Mgc;gdh~7875aWPm2x8HSC=VB+ zyRuWD5ItQ}%vr0Oy~f?#Q^h@&A>vWXnwvc)@~wwbk4w2na64^Uhe!NtxjyDnvi_5>{nsI^ znNnAwdv>kE%Us!dRrjle2i?5(C49X9DmRJ7QT9tpf({ER)c)NA5BmJh>+xjp1`VA+ z=3c>i#AYrO3PL&exMO5dZBW&K)D6%K+ytjL&z%?~qsN)X<6MSux^7@T}^b%6!$rfQE ziV(Gx`V`?~T|GrAi-6q-?c)Kw;$stD2E*lxP_x9rJ+=|zkurFY+Ig=)5q8~h`FwF-dOeJSP2YMB+vW*j%=T#)p{ffeLe*uV9daT9&!Ud4P9G68ibxT#I$#v4w zVyGxhY=>V2YjT~n!jF43i=ihq1+)Dj;3n5eZ8k$obX*j$M`~S7ZaHn;40Yq#%}Sep zAEr0+j}Q&mJ4RO1dxh(yK3njH|6}$7JRN53!ZWZVeX#{fi}1ve=`|EdGmnX~UsH=Rb!#QLbBwX=D8lk8E|L&Z(9o6UmRn|n%{d;HBk$!|4##@XC+xVgtvf?)2EA`7y($M%cxxVfiE zz`9>UZ4Z_}CO09Lw|QINH}Y+Tv}l9pb|@d~G%NOPdj~5%bW0Mc?H(mD(mG7cGFgYw zs6EQ?R^Dz{cG2`(f37ud72czm+IXK8vx-gbA}kzKdbhQHF5o8DK4xFrca<%={{_kD B$1VT> delta 339327 zcmZ^M30%$D`~N-XW2s2D^|sNCq(Yl5dr`SjWY1pKEMr2EVHDMHHJS3kV;O|`Vr&y; zT-y*u7(@1*5I)yd%vi?O|2dy?FVkoKzj=MXozLg}ob@@+dCv1Z=X|aL}^`@3fx4-IE zr<>J3r!|`g?w&0;gt-Q~+sPRNLtW+6f)`T-x{F)F{av){d22caSu4H>*SJ)sS<2bt z6x1ZqGeToomQqKiCW?2%HDX+Z57CNqBLZ9lU3ru0Fh!HD;;9J#G_}rJF6N^koAE#e zUO9(%B1D0!n)7->6?p7&&QF~JPoFL0;*3aNTG>uqAL&nG#dDFGsLHpT2X7Sx3cu$K ztGZMlNA3om-$H>G><;QSjs$5?43)h7I{0*@6>>bfPUE9_;iICrhySYad|rB;EL zb>yS;QQ!r6yq-WME>4NkxWu=uEw>V?pcabjkgA@`%a$srmEyT5O;o8>UAb(Tf|?$~ zdnhUJ$~Z0tl?psp4C=0litWxzsluy|H$R4t%R+%yMsQrMz|~@2ca2MF5pPSYpyrB4 zkg5`R*+2y~U3`Jmz~_9_p$e)>^z5N=N$<-08LOZsiM^3p@RXO0S5OPZxji%^^G!7; zDX694yv|ewo}OM)=5V?aAHYYKufTIN#dkgYX<(-47wu0A=ZS+cDM%L=ViKAv?#Dzu zM|_M);7rjq#-9|3Q859uV7~ZGj6W^?M%;o)s3cy;ME#9u)ze>$?P+0qBBJ_~Y!-X> z)QIUlEyAuUDC)1daw=2cIukA_@KkXp)>MXVyj4&t#k)O!Ac5kPUYa2FbiTggBdhnL zEQzxxQGv&b`+5bqRHm4ir=aGFBsL(ZtOlnpS5PbMIG(S-3&e!jO)h1wTmx8itKJi} z=-FFCb6v%Dy@!+B-79*h+0&#?qU#uc8XLO1`xtNPqD|tgv52i+G)~ly3lK}kS=ee7 zloPwpjeA3=YRc|Y<984-ccKM3A?}>05tmQ&AxYwqi71S3IA^5Z)hkttFOaG=QMG-l zQv*fMNt&oo6E#plE&PRZAVh(OZscu+Dsge{By1~_Q)3lWwYZZ}Cvs}8f*L5^#hw(- zZ{0H(5ht5ANPFc@1?b+`@a5)USHWDluUSO3gw}P5%!yZ;B?Zbd8m)bT%uf@#(x& zfda2I$8tBX_M+7mo~yaKN*<@`ug;Od54aFP^w?mRiacx9TcOZpGI&U8hd zc#$M`i&B|(qkIK5b};W@p#qQpnwx_s6gY}%vL-mG78j4J3Tol`TC(_+De(OB;`L;I zmsk_|t%8g?Ek)y!Z^OIdJfONT6pFo5G$U0e$qQ6cO_Cj=!1GOpOsE2{oNp_4QK!JQ zf_N&$pQv{KlVYetRN~IL0cn-~e3;H7s`n_=kK*|J@99vVFjxB$c|a;n93NR2hM8?T_M#B=jT&_XLQI3v;}(1Kfw`HD>OVqS)Z zR(=$>WcWwrTk}k%icAG2{Hg+v{f+mlOo4}ro|&kT|K!w41vOpljnrIIo!WQ>cg49# zEv@3B6sVvEiaRs0yJN&tnf@+n3!W)fkx4DuW@!>~>vFcoE2#M9+@XP{QJoIk=PHjg*pqoAt9x$`yM({(oTG6+#n^G$fD0*`HP zS~dz?yIj0CKQb+87H=$3LC$~6-Hap!UKzmUELDLQMsbNrSK#T6JpTd(9_l9J;-&?* zQDsAU+2x8n1tvUSfon}|ZC2p1BGKbM8^K%LtDvI8gVe$pPCcQZ#)=90Zr$VebFq{Z z)Y8_ROO*;-{hUw6TLm5(CBD=Tr-jjCpM{YwrL}mQAtS3#cY(Nbp~fZYBX3iuprVzA z)cpONH*pH8RfF&#x*^M&sM6EnkP9|e;I=}(0x#<+K3=paIP@G3Q(aY%lWOsqC{y5}3F4L?B57`s`0@w; zpiZd}5On)Yv{^mptaaPsu~K^RBos&mY4voEQ0uyk)@a*sQ>FO?ZI< zSBYe?hK4p3T^C295tFcZL_&IhKIFHGtc9_r-D6C3#>TJWvuUBgRVE`tt-!USrx@T` zID{_~9|g7W8*ze&8?|YF2vv}AHy6=P=*~4;tb!UU-bJd`B>eFTYM^Ml1cmaViOULV zSu6Cw#er9B2w3<}2{BjpF$wk?6U*EDcB~%;7qzRFNsvq^qtf z@G_H~SEj`K@V-k5JXHL7X*XJEDZX6lpHQ}quYKpS)#s_u)Kjejugv80?W4fsmzkD? z0>?1#GEG!j1gC~7sHImpu2bNus~nG2;J7fBX)qM~&$1CT-a;GccA(&#lBzhe;t9DyXF*S*0PRyIofGA};Z(O;wDqUWHnm`y*rKiXQ_= zsd)0o5hP#qT|FZx{wWvw*a_A1tLB>qufR*ibE`E`Ne_9cLcwgnyCEErg15#rFZ#y*{i@qeK=mIzyrk>Yf!s9;QcIB zQ1RSjZ9q_=i6@l`s+lKm6?myQcdaJK%oB@=)j4VAiCTfH#FJ|SNTK-8+Am`dQRK-L z!}7n3Jyts8e!VW*)v( z;Gtsg^_rl-7rZAHld8|DS$@!*hT#G&d%Zh&({P)h0!OZA3g%R= z#*FV(;OXL#J({QjQy}hyf@;P~mH1q)9IqCCZEfydA0eK?`OF+7ZI#gF2nzN(;xis$xfT$4=H)b#43E-e=6K0ID27K1U- z-VsOgWHBa%E5xHbdAZLY12vxe1E~6p*k?Z;z?>21@njcI?qQ-W7VQqmNf%6#Zi-WR zvYvql#Pd9%2mPt)rWlL~wmOn0i!sSB5|8raB_>!|!{6nk4<<>=#d$p0g-QBS@g7g? z4*5p~-ryT${DSI3({AK=q5@Z&@FWF};f_NApKIH!q?$?f{@~`ne zR4S>^57NVe@fMAu8n@92ASMO(~2~YeFE?z$x zi4Axb%?Q>$;e{&|nF=0r{Ox~m@l;V{_gGWiAvx9CEPcj{h5jG7PJwGBad5G}OTMYP zbOkv{Tvv?Y22&q%71Vt3Tya29zA0RDLP1S>!Mjqb#KoXv8nLw4LX17;Re?zydr0D=LwCdKKZ4hxc}r7C!CC=p)JK-C;e$L> zpyFi=q?*SYr=Vi^8mZ>-CMu{nM@Ti#Z>oY?Al^l)dAti0R6H~&W#jcN{W9JYiah4= zmMU<(a#Q+cyk!b%x_Az$=J~BuP?JP*?#p;pORIBOB?ckYJYKbeigSci^LVuiDjpUf z)jZxn1ywB`Ij0GZPv_DetDqLzabqe@fmbGrR_Fa)0!{X3s)CG@cOFAF)A`a}@E_{j z^B8ML=1neFP)l2L4V$mTP5FJ6RcB4Uco*9${E>GwL_tj#Z7-mUV7hUoQ&7wL^HQ-2 zJl+&NiBsUXM6ot?EDsVVDyZrxjwdPbvY~vWsS3PMJa+*Pz&i6%3l!8`kzCZIRhr5! zS5QMu_l@%Z4}A0gffp$7va=>8A=*5X>_fqQKL|xtGw7G0m7xK{d~0tO7UBWSj!8 z6z^X8GLwl4YN=>@`O8eEDyZg}O#eUd1^)-WT!EWrOqH*|O%vv)+N&U_mzd%u3Orss zcUj{SZ_j7!t%8~_k}If947{v*dG&e50Nxdh4IJQ9t%6$mGq>k`6nO3fjt466bTJRx z3cSmyp$clQc;t%4(%jFh;@m45@$D6Lnz?V4iv0PjOop=pH}_VxqWW0Oy|qx_=H99m zc=`}|nTzwU;vFATpS6lSx#G^Ncv~+{ymu8{xi-7)t{o?|ptX4YI^ObYEn3}>lXg6r zfJyvFaV1YqF;FGGyMfmeMBkfOOKWlPO*#KUp6th@G)#QV6W3evTX&v(!;>vMxqgdX zl(oE#TU<@9ZR7H*55CZk;JKpjod8>GQNQmDlx|aE)lND7KfPZJ=U#<9aSpY4|7Ox{ARJ6RyJgc_y-|=^`s!(y| zUF1M#@f0SdG2*+s{%q^M$FdE&hZ*$Z!h4a}%DHUfhLAX}ox^d^nBWCw6(jIx^)!0IlpPu77|Tdy40I zLLbU+!4KI{T*5=#>YX?bQ@2&;4|*^U*_qzY4+C7(ueea|Rpi0ze^`UMl2cD8s9MqU zQ2@5m`;jK7@;T3AvAudLW?Zenwc?6L0WSGZc`2QO8Y|v?q_K=O`IvEHkfafvC7&R3 z{#<2#Q_kf|T%3X>LnR9_SMqU5isb72sv;Mv8VUFAPMlAYf{MWbV?dO-taeBB@x_}C z-+dIgxwb$Bt`%n*13vd8Q9+Ftj~Ku7BvnDhP=K);E%OxHJ&v?2^W@!Ci{~C|#QeuT zjBx7laF_H|e4kerRPSl581{ro^pq#;Oho@Az(s4yng5@h=P+liNS?C%LGs@O`EQ>5 z_lW%W#Z#2NM`FWgDEd_F!;^VD*@X$x?(xL#x%}1z6U;f4zpdxVd7jV;IZH54M)G7a zPmc2BB~Kbw$~pT~MzR)G^5kA6TMxD`utyKXE-z$tG?gdoUqq7p-NqNc5R}vve_f$v z-|e3IcfW=;Ue&9qf)`Gt0Z2}y2^4CG1B7ab6WD5q8}x7{^_Hr;p?E% z<#a5#uTn`9ePNUf=}QKH!G-+fwJyd&CCxsgQXL|AjpZ;qqX{aMvJpK@`Eyzfq`4Aj zw^r^JNIJ~!#_4h#lT%ogt;*KBs3bSopIv%rOTe}6&Rfz?WNXbRV8bsJ9uEH z)0gP73T-l<;@u3n6=~lT!!bAFK*$Bdb$2pHsGsbFMRR`jYKWb{%6AQSFgGO)a)J~s z(UKXkOiQX7Yi0@9$W|S8RG0NE`G!tkA=w-2sKWHevkH?>v)4>}!+uXPnbM1S;O9jG zNgo*Eg*61hY%em2mfON(FLIGSpALnMNmu&M4^Y#aq!AxOmN!Wvq&B>6Lh?x@fDd^? zCwDUB`jR$;M8F9@a)BmvfYnV&iASQ9g(^GK>nG%fv8b}D%EYZ`Jq}%()gCgMk%>47 z70t*5x}hBmX-=BCM_5)HrN_`Oqx3UuXik2pO|BbSv?9Tc3BcIFq;vDyT?Ax=E~D6@ z$oM`?P>mhyZ{v}PZK_m#b^7@*9>zMu}W_>Ob~&JQL%$@kzngm^&w5Ml-0hY+WF z(O6EGbt9#M@uo9O9zup&mW3jQuUFyH5Ry&?!hoTq6$yjyhav}5@Np<~`!;0Z#t_2PD1NU*H6Mg9mL&uS^bfGU4k0ZmWpD%bNl1=o5t>Mo^Vn@iI zP&S?{wCfTqsE$Vv^5lVyN2n^O%81i2fp`;F*f4=iqpiKcc_L{-zqK)hO(gdTSpbc{ zBB6AXHH`a;{6;J5LW9X zMzQmdVPQkVhJ_6e8)003q^4?Yt}L?BvIeksDsd+vaA_*(LtkA2-)UqT4tDi4vXNLq zcrx*FD{fFjwU23@u#696j;}6zmc>gO+i))n$rUn^NgHRoqqUK7w?8*qa)h-m&4TmE zBnl+~#ZB*s^^50eG?>6j6M}a0az$JsUrhm4E-WkN6?rjZYGf=0Dg8dm}9xV)l zPMO5h`Pnbn1j;UQi#Ka*?<}ZnJm5}fZAbV%lUR}I0GXtX*YJ8Za8=K;7#n3Xr&tPY zRYNrd3k{1VWnn|d>TD(#8c!F)%S_VLrmAHPRTL^2th7ja*%F#%ktOs)5gg4TztTN* zA@w`*%(2__nmA+&o2;r&RaH^h9lU~WNPXd(`J^-b>mnSOkE{O7j%5poBWVLp3s5y| zgfJ!#os%RIG8Uxd1;uKp_HLXnL}I4W9a6f)^~ZHU*C#;9_>)00*-Xde8o zC%$xSZIJZDi>42RdJBn{|KNcrbUCe_IH1bKg}!wz)_4qSwAM>>U3T^NA#NGL-4GLxUEN7f3AG2`a(m4W8 zzehIZJcFPda++4GgQ^_Tm`dda??t%UH9BN53aL(yi^C@K9yS!MeiIrl-7C^%f14I#COiXr7Jg9ZGyf`r(OSXomQ)AqSd zW=~W!(Wnh}K-CJ;%*7LNqXS}0t?IH3>GE7xNaG=VCDGdM-65!qH&Fa-Jg{FC(sD>y zNn$)66G0W$c9K`!Z!bh;AN1Obg`~@fu_dLJPQ%@msHoDwe-+U?zfv)VPqT>1>E~sS zyHHNY{8D?B#vqkk%uIpSWbKPKzRo6KrpIzhS~Qx6yZ=;Yt!*NC9E zD=nS?z1QK&p76*<=0=wfs2j5gOZr@UG= zQ%CDxOC6!`e`4A2$*=T3!!a zH=!CoV+W<1h+~^^_^AapZQ9YXeJ1GbrGoxAE2GMy+m80KNWRFBL&IyT*d#Fh8*Bvk z%_PV(;47|K2L6pxt*8XoL;fk4ycx}bk&wNagpjsSyqS2md~_QpiPglcR~yMWg3qZv zpW~nq%23d2$qQV5CIhs?%q1l;oEM7Z73ECAh1Dwoe)ySa{JnFSig}Kj zC?cpZ=w#4&>Ea+<6d6y`O!27gU6}_5w~+3gj^njj6gru?`}wmP^{upnKRYuuyB?o|PI603Ux9m7y%S8DiX^nF zw&IRfa#R4g3CMQfkYUEf(4&B)&<}m#XaVVJzbTqAti5izPG7@| zac55qIPWA)sXhiGc9M4V<0zQBlQ>vvo-hmTj${LCc9Is>H+snBqDQ@zD*M6housSw zhQL%!k*wuvqczC(w~`UqL;amFeX%qN!gi5Z(i9f&B3tPXJ)rY$(f~E{@ZH4QFK!i< z%}(}mMh55YlNmgQvg*Q_bB3$2$wyXEg){?W>JzoI5K?n2DQBb_N1T}}=A<1Dd0 zB~etu@3`F?wwDQ;6p8m{jhUD`_w$aP(~4j-*eTmzaj>O_pwq9!HO-4v>-Dc{+2TXX zgl%y?Bde;6wPYG=$5(C#?OA4DOFfohLE{J3$Ey+OH?+ZN%s7RXeyg;-Ot>nflejq; zOE3qAuRr7PE(RAM%)BMI@++}*Eyphum}qN|fw*S-50zOs#CULtf&NC?*PuT{K<9mA z8GZ97T-iq^(o-!Ud_S6GySKuu{UpS8Pz%1Oe_)F`L~@OV;{9jIu*RE{p zkb>J7N_`FRJ%CDO7K}VVx~X?}sYc9%eFxCwoCenqkT5bA+z*m&<5v8Gih)(Y7R{ud zbr^e0%jvfCAr31*Iq@o^D&tp7K$(h)&K~WhmGVkKrEU9>bf1#FEnJ^9FjDI1!&EH<>_wI$i_ol#Lu*14a)t zbIl@wAR@OQv=Fzjl`yRkms)?=%n~i!Dnwfft&>7r@Lr|hcZ6ip;mx4n2yvvEC@49C zreOYFLxZDa7Qu~gWfAE?4X@!*5i!u)v5;SkE@(HnTueNe4_=H;pC$Zs48aR<{TRt5 zi(%q%vaiXBL^O!>Z-NS=^;OLJlxAF_s%(6CVxJpkV@UR@#SArElO-g$`PoTmaQ!LU z$1=^E(Yh}cR8RJrjk7T1UI>E)*iwSK(4!?#QbGdgo+a?M1U1aAanRuedR?P-!H^R~ zPn_Yw2{g{To`53k>+ZbkCypeEpr%(ya2J#1SvT20{S>I#26Az|))Dd|NDAm$wTA3e1h{ys;>+VnYvQ=ikZ)sM2GSOVkE;|$xvkLSq-jX29lw;PjP>ndF=F)HWGKFlE3FCCxk2&s*;M=Feih>v6B1Ad16Mrl02Z^ zO)^+$>0SqdI@WZA^qb@>VqT>lQ&19Q(}Mpsom+0CR84FIX?GOWE%x_gL0Oe3hm z`bFtK^zVy7D794RT}SpIoTWY9U{OxI?9%t*^k#pnmS(UA6qT=`Q#o-Z{a{czuJD#H zvz)kDJ0o!j>N<3cjdfvNIq@ekP+E=}-7-G%e&EVkyt_ZU(QXmMPCu zq#we3a-JzX&oxt?dqsi@8oVVt9K?FnD6_1Fk9Q&)PLV zw-@gFjO};(Sr$|EsL`8AKVLK~eM|Zg*G6;MvYUTGj`kKNyRnTAO|$2c6$tN0uA9qx zoQAo@n|as1h_kWsqhZH8a*d>oS-_S#3UiUPC4_|xUm~9dPGjS{gZ?D$mD8rx;Nd=p zaC9`$x|kvpkunG=vgcVL^?b`L2B!Ox?d6ikCAS-lS|Js!Wg>A$nz#brk#1@3Mv;{I z9BO?eJ4u9L??-Z#prM&pg?r>m!|p2bh|*n);73YlVzAdqp#5p@8HTR}>PTI_DPW^! zF~H=RY&x%(GtVERD~44yX?6|z`Z@Sm(PktL`diVy4f<_mLzMeAoMrF#5$$+=MOI-- zM@h;v9Jit?D1CMm60B)BYQc@xvklghWi}b7#o4r7ekt;g~HQM(S>9R2y{<3Qm>O3;gY= zzdGqN5|(kCNI@{ko_3{wI>AnR?A~2mx%SkL{-y>O2dp*+LLF!mG6oVIXg>J~EFEcl zy{_}oXqv#BU7VxVFvF4dtY3Sojl4eM(Ug^KDRlR2GHc_T)a)wUbEF;cV8z3U`qK&{ z^m3wo9VcAjvYpA@W)^E`@;4ZqXjjq&-aFCyECQmz0rl!m%%yJb;TX!^%GDcf;7 z`&Uf5NcPY7)i-2mXc?tfTn*z~>0&}JjD`1ZbPmZdeB(}g*B}H=YmwEv4ezwH9-(Nu zSv91yi8st|NOv|YUd*Pv1ZQ2^_xw{8PIb!RQslVQzA>}#WhK^#9-(*hpuQJ!T0aUR zyl7D4Whdofq)cL?)}kf+8xvyoEH6>EN;cepRbJE;EwMdbv>Ej~3FTf?YkBp76;^yl z$_MMlG?KQx4gDL_CP9HSQ20y2y?k)CRmK2h^VnRehbgZ;Bbq#rsw~;Ch=uKqsV{w< z09PB+20l(FOe(`1M`3*my8iDzF;~+A8hBGTTC^0}d!snI-GXV}v=N?m0ekIS0%yHx zgL=K{;j+Q#2jj|Lmhj%2t|DUrnou8V9S=uXdZ76kDruVt>qdN2dGZ!t`UPTDn^YCxSgO z123~SOz@>1)c!1F`_fn%R1CL#sjJ6>GUOd&vb1&T7mn1%-*rJHBV~h=A9iW+FzDb% z{nK7vsG&lhS+D}3%*oq%i?c(AA%k%JT{Q5+Q2`D?8{Hhe!g#WrTWY<5dH2{`%z^o& z0V>Qi9UTTaS`jKuzx3~_SeAV_V^xwrtE{IS3In4bwQe$C;g^b}w)l~<(HE&v*`1_j zR*cD=n53Mm3H6&&@A@n5@ZssCAMlA;(gUZkVX{RM1My91GwT9Nrh0J+7D@eU!iuI; zr1?X@zZrG5j>Ov&C|GQ3cwzy4o6%byKlW$(PgZChvISj91QRY?u*puW^5KSF&1n#! zr$-v*`J>-LCK|c~(h5TUfZ$--!|v>bTB^Z=F!x~A1-0}Gg&%@x2x$c;f@zE9=lZd= zpOVRlf#Lec{6uodhgz~6YgtQUWp)Kh5BGyl3+g`n?P<=oKshh-=pTMY*v`p@b@4O8 zHZtbUh;Z8LZTDGT+kxzr$y4)Pz;R|8L`T`kXF@3rn38S)KXjsv?H0V2xjetGnage9 zcqddfFaLn2ooJl;#11ZAzsT18!aty2XIkaDZ@Wn+A2Z9LY@12v4jaA-rMZOOIRRB+ zsCPG=fHqxliU|bFC60uOnRW z>7N0%LU0v*4QIMiuQ01rZof9f)g>2>kz*YKuP`}J##sErSvq{&NFOCGDj20z9`v~fWCw>DXXk$n9A!`*gIoU$U$MG^=xJ6YY&NM-pB+QG{xoD)CD=uR&-JoXXWJdN=*W_@3grrY8f(C_#v z^P3@~VP+57X6Q})5ZpKo3Hq0aV!TcAD@P;&5h-25r-A>b-6j}Mi$H{(#G8xa5Ef96p^Ypbw6&4t|97a2q4VjnoiMW}4QV)JEtk9< zLFaLG;L2>Ma!^Uf@;R3*q&f%TLQmS$|HfD*^zu%CuJUtTPPCT=3coD*Y%j=EX7Y%dI-@!EdEIemCCN1I5 zYWYZ0`fdm4V(ER<5zTtjc#;G;y=kL>58c@^MiV2W7(+%6hsgDPxo`08J*+OLm97zs zw^iUWywe+(+dreAW*^#}Y=_uBRLA6|4?XBQFp6o{M^Z0L<%J)~92GDNS z_DGix;?d)*4I2lbXW$NZ2T)zpjEFCk8Tf1x1hYCj9x4#|MvU~XE%X~m7qvVU&U<>4 zrA*K5!v}NS+wobB(a9=uttl(IMRByDWwPlNgWYk|!FnKnWi1(dz{of{uG9UloO3r= z%9QMR8IVtCjmPnsd(ceBq6dj>??TMn_C}~Zh>mO2i5HPtvlKJB$Qgb9l@Zm#AllLT zb{EzdulqdQ7(~N;ey2>YVY``}Ce6l_pQuj7Cv$vbEOZ-8!)&}*CONu_l^D^69ZX~B z-VyL{F!i+gU)aBi=wJ+?1BqqlP(Jx>VERy;gJ{?}l=i0GTN-K%qw5LU!JCGoF)MC` z9wVqr-K&>S?Q@s6J|vBxv5q&B1y$SC1vtfN<>;X?cbQ%N8A0c!4d{RkX8-<{t>2QY zQcT!?($`yEi1{%paXTkvN!dv3y?o!PS+KC^HM z)~m&L8{4ch6*pMob>*sBoC&Hmeuzxkq)#>+HXqHr zvToR9&cc3}jZt+AGM0~*F-=oF8p zv9(oU>2pwi^hGJtqO#}U0l;yoaWX1G>@#Z3F?6%%-#=P269+@@CSw7$MD7`Rl3Bkm zoq~O1>3F(D3tr=>w(i?MKa)B_>^N$m$6UcOk$R9!@J*zB>f~ivV|<3`nt||LBJG5M zgky;`)T;K;T5{j2GQnm%b*@))EouqeNh+Ah>jSOEQ!gUI;PEuX?eSLhQl`Z-IYuSM zI%c|Z_2LF>ACE>r*-OKj@idc=Ezox&O~tEGrzg^MS|&ozNpz8WAU4G|L}$r+t~EXl z^>Rk*myLO2HoTpLPX4;p(D5regodw%m0zI>OD};#U*W{Xm%#0>aJ0Y8gs91=qdMd= z72W|4+KMGLte#Bg(7TaP|7-f5{%r-WNpu2TUda}%goSx0$I`1!R;MNT4 z?K0lLWeNk;DXbSb!zfeI(Z%4Nif&7?4Gd1j;!9HCn^fAQPW#1N%}92OVOuKNu|J)K z>#4LpUAhqdNk#Wv%!3{?sY~0$dT3;@+L)2pi22LQl1=r?;Z8L|Xx;Ao4kryS**cr8 z?RZ!{le*buay;WR-okKdCJm-|0`qYe?L_B(GIX3x|3~P%QYinHCegQch5>Wv&6?yJ zXpxD8i*PNIjzSZpV;23%>JKNjx6BEZjvAh1(Kte9{sj^9=_Q<8w*?sKduwmlvw&t& zx;_m$WYfl0J#3k%VBEY5Ow7j6%@cpvosAK$`cRpT<_NBV@6kKXhN<6EuaMU7>oFC8 z21H%8Ny4(8*<^Y!W$QP`O5W9+rS#3n>70&fHO)f}fHU9IHne04)Xt$}NG^PpLnB+b zysO8Yl4mwqub7vJc9v0%4}5t@?c=$hk$F@WEw&!t&W49Mv@f2Gwp)ZA6;`u|Y9l)T zWA2k4W}{pkGx{MtI;Yil<#sCLO|-k&wGrut;rt@H zpOSpY$)gR(T*J0J+OAH0Cl?lJ;2!c~yspE-r&DA2J*zDSVKwbS+#Zc*+94Sa&2eF& ze|U%mIPqO8eT4WmbTytyeOg1i(@cQwYpK86uZjOx{!<{XMcpz9j;y5)XqsJKOFe0S zN2ppuoxmoa_M~4ggAw_-OJTruQ9kxl3)}N)F&(lLrme%d4l&;;QdB)Sr%P@z)iR!hFpMAo6wQ>0}&JY?mQH4LI>^DXoG$;olEMie@SGC z#^dVek|Q{8pROw=NkScGpba!4-NmBy6QUQM?Ma(iTkyVMY{{xQBM8YArB;glsm($s!>i znLn3WfYmnIl$KaRn{Bk8cLM$<603~$Pp8lHN=FI7drFM2X0S-w20OQ*R`}ot=eJ>C zyB27+QyT6UMWHUdvfuK0W3POqKqA4EuLtEdDq=+KD^t zMnmmgbbC#_VDg&*Q8&0}pwYC!H3-~`OL#mi*^9iKaTTuYrE8kb=)*!$$!@sAplDgd z;B`2!`$Rs=Hd><;V_e{{4{L7670BO*`*Z`toqaUd3eSU+is@4t{~HWHMmsZC=NNUT zi~oRw$7uKZwSGhHp{~k2X2B$y$21P5vWlMk3XP7_@9jTcV*Q_`mHuWA$gZcC3`dXC zLQ==?B2meg?W9=9IY9%-TEn3e)T5T&**{H1jpWth`UhG`7YcwUf7+#|=y;Ytktr{d}y(;*a}{;8l*xbsh{UrwKu^ zmZlOj@KiuHIM|d-aASRuO=otU4EJ&rb!IrNYXHy6X&P=xUp+v9QX95E!1ENkF99w+ zq<9&>zCrVdS`pkO8cOJZ#KSNN+tR}l2}5wPk_9)$!iVBmr+Bep>_b zjMOo#bvZMac@%i9l(*znIz@5iv0)@ec$8;K9 zO<~FtI?FmXiWPXnc(61A{&_-|&?+ax4^OEDp$`Vbif44Px~59zWl90JnY}^t92Fs6 z8hcKAk)d$pIZkPFsC-UC(K`;Rpgwi)<8Q#>F3RS`2gX#;k@S_T;baBPAP$8cWsHG;qrCvlxk5*7z&}vTb+{tCEj=F#{Lj!wg|x zvzd@UY5Nt(dxhc5?y&n69pHHXYi13w&wBJFQKL$tb6Ot3YikW&qh*gD%DkqdyzE-C zb=}V^&~%vmMp7Zd0_^-`_l*=A0uA2K(e#@T$b3V6Ljo>;?kBPeR}wqw`Q{RWOe~m6 zV6p1)4B#>b4 zVaWtSvaSOO@2N8tU&5^S^6A#H_h@RpJ`5Hg&?bE74?Z90JUa3PZ2LevIRA<)j4Fv_ zUNO6To$^SQ=N&Q2KGFbd>kxSgnauQQ2^~Jtp7!&aBb4pn74#aHa2Xat?Ya6R)!6BR zIRRmb!MaK~{*n6H)i)JDT=u1{D}j8XOVu0Cn0SJnM(F|A_z928I#w9YeWG|Mcm*z3 zp=``r8Z2yZxUvd$8#an_7Ny@JyWYi1jlwJYGb`BwWRcKfd}0D~5MB^r15NdTWmNF7 zorAq%8MKV;7(>M?-BcKiW|yBJJZSLI8_#>3{$f^8MYP_*OL7nTJm7@p(7c9l6$9b5 zY6@|5jUU9<6f*GoO?geBIsKyq>}v@v=zN3;)@S!|Y3H>6@XDSx4|i zi)%+6VGdeH&Fc!m^w~doBHBFa@J>I=W!Hcsdabf7BD&;-+5H z2J^c>OB-xXdJSW3gjRItYgla~G^LrZ;gpR~zjv#nrt%oO$Z>p>s9_<&Z@xln)D0>B z`hrWQmvH)EMt^^#8l7DhVvZ(+sD<`;7cN90v5$`?8_rpBdkaN&LYD^J{=$psMR9|l{FIyV zcADwJM%ZCg&noG_8)#%NMA5QuVY0o@!tO>(=31s`qH<=STDc?r(Gqss3lSt7{;?N+ z@cQ)$_6n7K)_qiLOj_flDc59umwc1I2ET@F4uY1%!k-R;54|!K-Z%&z?O$ItX~mAF zf;#jRY*}qsiSF|ls~(#X^BA8!hTe|C&+J6sQK;|o_Z3q;7qIuNY%KTO>q3x|prb{> zFw03uqU)Z*Gbh1~F1ZU<8exL#^2?@TEa>&GVg(W`(g@*X0$k7t!)VIv?VE@>}*e zSYG4KTkyj|jP{(-Y~}3h;9i{9Rf~Y-@XjswEWv zZy|-Vmas+KG2H}LYJ1C&<0e>9;%Hc29|uf3J%#)Rf(x}D4+k0uz3BNTP}f6f=l@+| zJ=2kBW>?(i*)@X@oC#T?!)LNlFNgHvmE;|ECVgpHK0(YB9>&esdG^R9?VU!^0Hp+{h`HCrpGA3>0 zS(0z@*KtNmxgN~WMLw)>Z2k*&4?n}eL>j*Ydn_Mi*kpc-6361h&N2GRAV;*sn8$JL zZe7ME))VR3H*myLXvPAgo`ScHBw{R5U(3is>e2xT8Z{KM@Eg3J8w$H^lSZ>^{s+C% zvD3J+r#ynM8VSz*4Yo3a_DnW2XzXI9#H+9xsm@HIGIsmyiL(~jut(!@s}8O2r>UHW z&OzscPGS#HeFbgD5&U`wt~V0KIULAiBaxlvEOx+!Ix5c4-%AjQPkDlA%2Jw{`y{DP z$c#+x{TVq^4r*_~BhuPN?ql6a<~|<$0RhukSVzAvx5Uq-%m~iGjg3r`nFd>wlSriT z<&fenG^0;$!Uk`lwWdXhY4uSwXV|>NW3lHOq0(D$v~P2bFZpg)349-o2Z{6SA zKoO8XQ7J=HgMC+;({a^SS@&bGy@}AE&hMCm3H32{*3v}iM{n1HKp&x*L)n$j_uFJE z#zH!C1(JM(p}NpxyepZbP=Vj$l#-hb8-ubXumZIg-L;36O8>+U%n?{AS?`|v&E ztsIVChaac1WwQbte1*nT91iV$QC#uiiZwwbZfr^8=v66(4fmsRZDtQ z$}Cd+Z!&%_kezBFO}+x!WoPQn9xk< zPTzhFdzuLY9nPYjlxxLqhU?i@^ZPCEY%XZ%Pq(05bKxgC`6`q(7uw;6C2sygTbeou z2KWoUG-eRY^%q)G$3d_UQ@hm{aS^j7a8bpfu-v)Zp1j7DHa%x)8oUA#zW*DNk3j;B9rW;V+y?2 zGK0ml_FSYi0&7Erkf<@3+jO#tyQH+|FkcJIBJm?E ztocs1Da>t5?}UBIaU7DN;XaQUAKnSHZ3P#10jo1cu+0z~9DtR{rP<3#74&Z_vpOmzj1|o0ouqm@VtZIh6mGD9ffAL zwPbRug=I{i;b>?m}@JKhByg+|T(iIQ7kx7^MQXA8gFCQFCT0F#11 z$*q8|r9kZWozsS@j>1Ud*kc%z?Do2hBKD0Q|4{=x7VRt?rjPbQn^0jQp51H+6}&VL zh9IvxFkYb~SzurDI-y{8hTEaS7`pEphzJt~(KWRpKTKHXIC1cQtHobM=pwwKXBR=Q zu7V%kun1;#MKK!_1IDhxcDg4TmWK;Zh%aPD2xAF`<0H`aCX2vBCp0FBh6tVTvw+{n zR`d`ild~{9TF~Kl$D5*s;q~Xg$J_fj2wY2brEkh>vM6ApF1sn4NH=I0BQ*9*`5h$% zPZN9@18+;-pG(+ehM-xC8&_hC5QvvtSHuVnnq=k4-48mC!S*Fb`FDLMaZM`bYB*LG7MG5dLCF+n$0qeP)1!o~YU8!jC?yRN{SEL>Pr;MvyI$yL z)PSg7nD^Emn9>WE*seYBV=t73Z28>@uJsb^Y5X2|-V2L#1a&O#A5PFF7Ja@ha3fZj zK;A%PZ=soccf3_^ye6BO7?b5EtIsp#t?z4C)LW=u|L#uN43hroj?=f?Y>?`2;vZ#LzuX+m}^;2KhQ5m1UlLMvMeOsbGrN50jKjRdUhP{TMK0*KnPZIi|i@0w$ zEbSv?&|h1EYhR&3mw^(q06w7zv7^e# z1~f;Sm_I`;ybE*sqS+c@fE9g(CM>MqR~Sxz-(&FXho&2z|Mu)JG{oQIn9^Tx#+#)J z`wM=Ww~_Kh$reVmm&5)>OzZr$1ODhQjHZ8%fS>__3)uxd1_(yF{0_7pi2UpiaRY^m zH2*gE$Kj6j=BA-r9D0Iy4Pfpd;Uyhk04alohJpXfM22ZG+>Mfj-(oVC%lv`oLL}Mj z>1uC$X}X7`mb!^hG8lLJ7r(%>!9qY6EoQ-j=4)k#UZd(m0kY)qzdt^G&HR(kO#~In zS*5ZJ7(PVkL_>dpHAB!F%D4sxhM*@h=9=N!5Mh=;LyRzBgfN7z+6cQx2#@L7i?B9c zXyf?sXWYJI)63uFt|hUft$5)W(R}|9^#gjF%sTx^4rbrMKDCCDkwQ3q(Fd$Y3BH!o z+j2vHGISm#l=n62xz&}Gii!mFbOLr3ce&(bSs_aAR&f(BPTpkM!M5}nVJu_b?`6|X z$~g3nk4Yz1!SvCBXZ;j&#Wku`obo*ijUIj-Ev#TuK1LX2^}aRh(HrTn)^K2qFobv; zG-CxLA{MT=#8p|0+(dEKu8S3O#5R!;88=MQ15{3S5ZtIzC zQjDj}br>H?&<6F4-;F=KWOW zMDhc<8SHS>GUm+SmcUf^k4w0O$4Zo!Nj}G%zgT8nq%VR76NE^z9L7w*5W_#qVd(^n zM%;vR6EJ2nXE~@RqDtw%9NJD4blL+aacDUmw^*5Xg~!`JRT+Q4Rm^O$)hA)yM4`3K zG5i;Vjmu>N4PA$m@NlBg-F+y?URbQY$T$-7=gK#cS z8)hU4F|aw?a<+2nBy_TU=;;(ktWKLyE29e(j4RezP z3rcq%GGtE|dQ%#I5N@ZUZFd;|eK4MP1Y3QWw>hY1;tY0Q2;nn@Rpd`Y*-W9GK<|YZ z+`kpF30Vr8@kfuy3^+aq_XZ0?t2ALeq5ilRr3-HMbJPCqrLdqVUW-h}wKVS?JWUrm zIF?W1BAz)*-rbl%yG{=s=L*y9T^!lza7!S~}qf$L9*G>tDlPq(J8USYeCf zW0P)SQfu+j@CA@QPcYE`&4;!b7}#o*4ihsltTF|@&k&mXUPxoD)v?LEkIRD@WcM(z z!R&8~*P-8H2!0L1%+>e;%oXzO-*3p2`} z%Re>5E}J^GzH7@OFVgNU;P$;Rk5)`Kto>ey7ii8jAh|*#y7`U4J6AYEY@LTPh8^@` zcdyXWxt40Exfu6N($Da-CXVl1{n@c1wjE+@JH83QiiQm+T(VBk6f9)tqytJQdJTTCtP0LLzXT6kFXIMrtkxq|?smstFSl1d>FT>3afAV3O5Zu7ZgDuP= zV|Q6TdFNysBpN>m!^HuDud}!oU4TyikF4(ii}HB>=Pmobpx}W5f`X!A7Ze2*1>y9N zLs7BC-hwTb!~(Gk3aICKwnWF8Xo@waSa|J%s92&B>=iYZL+nW`SonYTJuvzH{yvY~ zyXDT}cYBG@%-A0XEzIQ5QUPq72&}lB$W>1$2Nw40esC zDo1e~#95>4t=95c;G6f&&p4iQSLorhKIqO<3uPe2vC9s`;G?krG~s`s zGz71pesk342mou+6;g`V=b;XbgFbG~Aixp&YJaYft_Wh*bvn38S}jg|MEzDvt^6i+ zD+SilQee&Fz~V327tn93rFxJ8uCA66#c#o@)<|EAZywTxHPDa0TS67rLW7xqgCf>S zHCh#XDq$Sx24AR4eRSoIexkd*6tQ{3c1wc(xulhRw)C9Xu^O#~3@3J5O#8o){Dkw` zm2V`RYfjil@#`SQHPfc9lST^S!>_fw>!tdVcxVY3e#Dx$EzyiWN^aO4wa^kaO0q1B zq@G)){oY%9b88^r%8^SRPVu&&dbu7>_Tg0bC+V8Fw-?FVpt7GyjkigQA=GDWlMai; z$F=mIr30d9&7gL_NsGkdbnX0a(i%~4rSUtZ_TtgQv}dRE9HQmcT~fSX%vTO34}5h{ z->ZlGFg%QWbT(DWgpeCfrc4Nw6=`%P$o`Qm+M5Xp)tW_rWkT~aAd6~f5N8`ucMY{9 znyN`ns^r6Qval64&&IS5q9J1v7CpjWW!d*0q9YnWKI0GxyQQAOMXlFvX{0Q=oucgh zQj=y?LrUlH0OpMYHkJ3~rM+1@&MD-n*o z236egQYX0YLd#g;chv8Y6d{Hkr13Oq>Xy!cR4NZn4tdGF|Ke>w z=rq#4FI<8I^c)NQP&K`;M?r6|{i3g4m_i(b@QnkTV^Vkc=2y>^{KaQYs79Cj>!8`t5|YS)3hB{ZHcHsoepxo&-R{qG|IG?^i&X8q)a8$!Y{>wDwY|t-EYu}cxPKBTAQhO;oJ6_Y#>GT7ooz|J)>?lslO0g*! ziNeqR<_N@fg2SU|@+m2b2mCrEtry_m{JS(tw4bG8ze_Cu{SUumGLA%2mDA|!i7+~P zTIvBxQRR#ziQ>0gsCu3>!t2X>JTBc)$BwO~rUUy^TAe4Eg9|eq)^P5+xZJQB{1IU? zmWJ+en%sJ*z7Ec3>VgLty~iJtZ}|3b-d_xvA5OHiOO8s%)|E*oP0bFupzkRMGIql+ z7a==P;vdpU@$8?}IA7W$9HGK|P_IAlP}Or%6Hj9khkP)Zg9f#`o^W!a!RIBf;NCmA z39TVxjn4cF?DbH>;q@zK(EhgjzX{A{L<{=v95(#VHqe=K;MCVXrN7QevweH*aI}$* zY3B>1?r}$-5DDwNG!y|1|2hx;Je_7;ka~$j2hr6FQcFW|We0cHKQyBz)wl@alNw3` zFG97@q7n7F1jPK%oz`8Fe8lttwD*$Kw$kE;nDy`VSub7Q!DP6MW52CUwPu&4>Vi0R z0QI;NpzY1mFa;kexngFh|>KeAq53(rtn$%J} zP>+P`IJBLtWn7m=AhM|T_=c1PL5P071sz2uy}AXSfe;Y4rAye=8t;IHzw55$-;ur% z#r|Ds!aZrA-@61ptvm7oKdin>-*bd;1X{e4K#%T8b^Z4IPmR~O(XXt=w+YnvzBCqL z!q(o$cGsJ<`=IAfYSFX%(g-o5me%Ki1a|F3_9CgK%WMuofO{2HdL#|xyPQW-!v>94 z1L+)YgEC-?J&qw`J?{)qex$vtz@g5cDp#Z2N7DE@U$4?9FMW$%r*thX^2b8iIM=aI zM%q*TY2agYD1#Nf%d2r({+v9YAeS@u$m=q1*CuqBoDF zs^0Yq912M-$@K%D&)z5F~**lQK0L}ls^iEM5j;-W$EocA*$Z{P~97|?d_V;}-rc#;v z#`P1%w5LMy>l>GEF!yoVOj*tr!PcWyxt16{iiW9jpjc}ZSyg!@%u#DQ%U#RW!P_qk z?vZuIP^z;W20c%vGfJ0Hf{WZq*ht^F$VXhdjdE1#Mx)Eg4a)_WCWA-Ox^i+zIjJ-) zjnb}_lP~zVy_<}Q49`ny0n{2t2WrU^4f|n!Kitsx_#`9#vP>;1P>ymJ+eA`osQk5u z9j=gNu758Keb_Cnc9QF6MIS%EqP*pX~N7Che{K@dE#(sVkA!-Elo`3iQ{@AC0!To{>@0&EfD{k z-h?jwH@*A+q(P?sr~LB&N!yX;R+fCXz}v~fhpnu0HGO1i;5?ppfZV&wK5ciFc5oBV z(@GP&d17yA;<#SBG;x_Hcyk;?cAm)5Ms=6>h$#qMi-SeW#qit-L*lK1<#3E4)79N% zIhplPHm1HgG^wE>Gv5(vs=dt>Mu5k|b0x{Y+Z`u+BV`_xE zQ}TIRg6McUX-kkCPg%AEbc&Z|+7g(_mY^67nV#;k{7?2BA7l0%caxBhd{xiFAK4k1 z&OB2%Y}^gQVyD99pdDo)hioYcLU^$uZ5Zx_dM185WTer}y!zsqy5U#*u(3%bsV^5>y zFJli~=@N1cY8Ur-+t5H)gkH3FMIC-X<7yOgVuTww-L76#)5JBc2+R01El037Mhz62 zr2c`fkoZ_kc+rHL(A)7qdAesv4%g;f;L4n|4}xLNS&^c8W2wE@#`KoI6vQgUbhnQj zEnL=W_mwLN@Q@4dCtIO%I@(X(3=R4h{pItbZyv=AkOv97>Bj+b^-=38S8|$w;Jp3W zH+bSSf&Wg77;dNs6s(sAn&kfja4Uq$an|Xpb?mjg3S#gi8X{j6T5A(Nm1hc~-wAq=C^r%2Q>~%$BAi<67%F!Z z2fAktlczZgOSI`@<;eC$95Q}{(&I7NoiX1bO=Ro)^XY|xnLvY)V%EYsy~!VtPX zUG5@!gla)E|48Opl^!v*gN%*wTEK91I_= zVYATkQCcxe4i%o!=~?nVA(Sk$y6evf5XerK<_F+;N+m~rJv<*Q%}01SHe@OJr=dghC@f7Li^xUa zr^!LWBl;sv_JTk4gEYAo%#X{b%XL!vEqaUE8RK(}Fj(rMcO|bb`)2WpPrJqb zi(-Whm;QhCF^zw}_HuGcs#xN69S_gUX|90|tXZ5IIhGfpPfLORK+x3_kjiCto{N9< zYr5=}a;`LGHpCpq*7G>8V`H=QHzK$2l*Q|N)Im9HT-eAO5a&^@7r4!K6ud@37v#hn zVzT0GZawtEumQZ##_H&)$XKM}ZC=i&@q zP{CYz1V~ZrJlP1L-!e~*5FXI6d2)Rarf2g&049@{MUDhf>28s0xduP1=mb0n$tv-( z(rk-dx4AU;9X!$>8~2y10528t9>+^%?;s71UKpllfr%k~P{dL%Y(`t=%gtcAcyqqozLw8Q z@Eon3XVHb>i$S^EE*Dnh^!vDB?ov!0r{rfS)+!Gd4XN~tRrd0FW`_!8H>QpMODURz zm%JX)6)RW-tg9Eu^Mr5d$pU#ijIamWA6V$wNl-MAPn7MzyHK!f!#^A-FqSVES8s6oNYrvPZ;WC<1oR5^N;b`{>AbG__J$2 zER{D2JZ#?AvPBVAL66ZDnpwF4HcaX=c@ickWtsd4TJtf><*s7&sdQ+$yc`nnCnSG@ z^}3DZnuv*?N8lbm&>NB)`c57JzG=zgO6hJGn%M@uI3iuz2UFw*405Mg=1O1XjPHJmIfWwYNYh!76*%EHgUg)y^*7W{HG(y#P*r5x#-KeeLM zF;if5901DhX}1DimZ|6lwdPe;?>IWU``AA7Nr8Bq}FGh@dQfCORSMX=}Uh7N@@>7mM)**`8kEIm4}3n zD!>{yq?>_Qhj8YD_l_b5TPR&Y>Vj+-9F%xvA=B#huoiei{>d_O$>!FPo$)Xc0h%H^;Q`Pyr0>^d?t#(U;O zJD;{DC0^SdnK?YOe$dx^?2h@|%nQ&4<`iD+*PyH56rq05cwXgWeokq=m05TTX+d!x z`*UT%fFaV4@(-f;IYn%c>x=3b8nFTV5l1f@ z=Ad<-xuvs1x zFy$OjDS0f=*e&SyicY(MJ31wr)P_@`a;LPPHp?Rd+b>Akdg7ZI@z&UMf4t@GFnExhn`vsH-F+6^ezXId7|01syG@A3P+(pRM zF8(U}3Y=>HCilciVEgTISj8pZ;^5QRE6#GZQzF=nzsF$Bwq2ejLIyVM0yn6sP1}Wr zeP4N3#JSBIqvdtB-90Y%Ft7{MBhtx*+Gui9kKdh9Y|x&!M_&`rpX=HzO>QWNEf3Jo zyX81PwqV?Ud%0JxDGCUOeL((+A8j6x?J$P<<)EAhN>=HR+@$iA zC>eV%A;~MXSVXs`wt*Lw%}b)bhvZSB&nP-}2)luG6qzNjs@k*I3)0+Vk7Mopz?}N! zeB?~_ee@y=eDgCXnC0$x-8Zi5EXYOY(!m9pbbAvkU0+962(4Jqn6a%fb?s#rU-NTaaJa zU#APvPX85#9QGv)ao2L>xxk(=N94LYqY zA980LAEo>u7l0fN%7>_fNGti+8@8go`B*&fNH`}~^R@NiSmy3O0Kajz0pLDQvycut zN-fXH9h&en4qW2>!_^wg7{Ic(vC42T@`AhV;$ooRy^_hl7plo&dHb zj~(p;Z1+)OZXML3v@E;57jUOEr-}1CI(wYA_SkzbwxF`o;gJQf0 ziFzkZxhPk4o%hI5{%eWXV_J6+g4G7PbWx6|R6i2JEx&WY@$#q*(C3D1E$>OKF3C%w zsy=-Q1Yj*ay9D_yN%OsoJ&#zSH8r^cT9iv)UIBUDM|ZBsOH%41QaQH4W+8@))t~80 z9IFy>&v1HTFOO1WbAgY;8#9oqRN|$5$Hx|w$8)Wb z*?QsQq$IO7hJ#=a(pI()e<6^xW+@BtWMMzyFBmB>_l_M;d|SR2SvmseAqUeC$A27n zvyeYpSPT5<(45KB4oGz5A1}RWhVytwZkV21U?2N$U{ugt2wq20)}y{P(jOlK&hYAP zC0?%_na;>WkGhtA#@~#GxWpsC@M8~n2{Z8TTG(!+3=608m1ALVktiI8XNU6&0CD0T zYH^MKJIK0)U-F`V)f@Ee8tCRdZSr+l5`}D^=K2QLBSgHM80LlY;)cUsEODLwVZiA8~(2d*j3?X0ZcSnwug@@Yr z_n{OQ?o+NE%pEt370N5S?r!VhRM=3TSx&ClCZ4{4J_2q$y@IC)eJppI$J5vZl$N_q z=4tKU`Ye#G@WTj54 z;gsBlbG_9sc_ptFp3~sh@(WS) zp&oCr?R!u2-pIS1Ju7oY6t9dMM;2Kbb{nl+1GM zJ`*yv2L^UX!hL%iE3t?aXjwloTFyY<3Ms@9ZVRlcUOXb0`M|-+hffWxp6nrQOAyvI z$%A`X8Et-&$re#QCj3E?pV8J&0R664rd#C~ot4dLJP3lxauvGtKzC!>U4t?8o$I7C z(0!D2hl0qEdET6o=(*f1yePTjSWCijz$bYdi2pVnInv$;Uw&)3jHnst6MEEXLNQ#MWJSDTm0(as0iXptDZ9 zRS*$l$bfGn0^+8Wh|s*_(HMTk05cKT)8y%2OS3oJ^xlxMUoZN@kbVFUw(g=XpP9I> zd^SF6$+Mi(YvUvM9RE(z%A#9XU3z!8iXA2@KKnhKibgmFm|9#nX?$vNO+)&3m=q}f z`x`Pg<0&TmgCT7l9!%W7DRP4^j9a*h46TPcMb8TjwC{NL7F66bkQ<-D)EvBS7OJP^ zh>nK!4<5r(wcIe-CJOPwQA1`=?ic_`Bx%0M@>kIf9ika0V4KLRUB(H5Q&5T_J&F(d zGJsaG1RoW$^p<9zilbperaN@%FJ%weknV$APM}d`!h?`&h0aK)y%7y_-g0x6f2Zj^ zdKS^dkZ~8;wsrzK>3}I9-`kLpk6isDXf6e>;nOQV=%3bm`0<0d$7>Tm9{1A_3IYZ|5jORr|syj;Dt7Ffb~UEzrj#4Gr`Gq8et`LXL6P2gKoUGNi*Q&xtEk zQl9f5+c=tkg`J^pG?@{GX1VK0+B7`CvbAVUDTT6J#$Po%*4!A>$dE;~h7K7bF(|Qn!#UBWU~@D90Ekv`s1W)*DIX>x_5kIXa`yJa=?X z{Mf1Wc!Fy+H*(VvKu5vtd=Tf#KoAeb+D9;0+5k3IIS@;>iOthT>VZ`oerZCW5%*Xm zdz4O9+ATv$nq7^MCb^XXCSwY47NaQ)!3Ti=>AYV+qj$KxZa;cjifop@3f=!RqSWH# zB$#T;fvD(`d>c+KX57(*t;bVzh#OBi)xT+ffSH*!Jixx+xmn2u^i#@rv(H2`0ei?VoIo9b*S&)<6 zE$0en;f0SK)*XBc`#Hv7f@TH?=~UPeY2aevC#Z@sa?DLhZ;wPNJPNnq8TiUSl#~oZ zUYnczPA62J?tB3x4Z+(w>J8Oj(!Zi(cHxS$CIv&rE_|l&Dck_k-bjY@`*=W`kfj|p zAEFerP_Xqy)ziIE3iLRJ9|ve*rMO3bL*h6Uo@I7{_81JYVRiOi*s0YIU|E7k8b}-5_uNfj z2Qt9)Cl%LVb==~SU6%DL1=VEpyn9W>LclF~{K8KNIp(yZf?Z0XQ#IM|(1@<6#kPx0 zpK0-d41z-neN&rN<+nE0X7ixWZ&!!a6MmyHby#)xB{k6wuHb9J1=j%kY+7B1`HC%T zP-Yz#B)Zhl?$u%63c_W|sK)~9^jpc9U`bN2W7{S7MA8}=Q<_`4?fO7x>#=S^5!I~E zZU=@x@^I>Dwl&J-TJQK(UQV5?pSOf;W=P)-+~Kx9s$HwwfC+-=SwsyQvPmg6_Ez$6 zN-G(LyDV)i2hX!gWMEoS7?LOTqM=FkqYatpIeVa|{Zf4K+_pCQWAi$XEVEU94Qg&S zm=6E{o9?jNu@#-Hu`mFhBx5lwoQlScy^Np4zyhsjoR-y)B@03qt$7f06RYppfzTr` zmgP4m;$-aKC~YvxV}T~^)5ct8@YF0JY_0$|5RYao-K#RT1OIn=a>x?w4a(Y zFF~u(l0BDj9#|=YMPm2THG&-$-jHV``x#x_6)U&OHef^eG}#j;sYgZv!J8bLt57RyFq^V8nUifM2ht5JP5sM&5X zYNz3rcAmJm33{7<1@qyHDLRh%_!e@1SkQ6Y98!Jwt9G7Fi)Jn>htYq?F!?thrO0uMbEp<^Gf3} ze%kfb52hXjM`m)j04jVZUdwPO~vCsKvAF=w>?bUA;T*`IZAP2a#j6vc0F#5HyOS(9>`4u2>qy2*(uwHd%_xov%f z-jz*0RX`RE8Niwfo9XKT%#091HwHjbe@(RqvM+IHvSuKQhVJjiK-S1KaVSS?eY1w+ z8FTgn+5QX>F}aT4$_D;hh|4M6xfb7wlP3F_Nd4F&-je8E;#I#IbsEHcT`%r*A*3kIDEFSdm;9%B~!iO*)?B%-+VU4LP zp2=kh3sAb-InvUiA(&!Bru~!!RV)1EEzWO_7-!*rj*=*jU;dD8c*t~6uQfE}Q?^bl z--@I})?0M(paF?&j@V~A-AiOKP~|opip3+g@F5xoK;VdN7z-24;p9CW1lBj4VurK+ zQooKKl(56o3lToqXI{kxu!>B4Z5Eyu`5{O>$g{KkKD8LZmQ{U~>+bZ&>+Ufj*Y+8) z{vh)Y{2A2F7S!u0Js81yh{98f9LaW7yXxftuG^uZs8^B~asn0|CUYWgVtI;)cJ7}s zPtj+KR_8O;TByA5IyaubWL^;`=%&We@wSm4fLoJCu@PeAb-FzYsJ)HGjb_O{DzBSp z3XF(P%+oIu(64^5KhxfiW>&#>=+*xePrO{Tm5(X{ z7hkpioK1mxJnM6Y2(|6#!{@9y)_&L*n64kF&lfBJp-88G!LGKi*Zm{57%eyAvhPWp zd3*;V;8ya>hul3H4a#dqaDZ>_WkSMmRQ{yB;fnDptH1aJUbu?>#5TOcB{ss z&RFjG*z16WSlf9@?c7_lNysxS`jO|b)zo<+`@Y7hPN??MkbVxd*xJie>gC?rYX|ZS zi?Vr+*Cnc$#5z~^>!Od*kp4Y#OY(4Cul=*(Wh+AMLMcfsv3`EM`a4_ znU6U315HV0ecFA8-W9gO{OOwq-jmn3BnoR&chcD9} zuYX+g`Vwo;^-6!<0l05vC5@+X5e)YhPGUcZ<@)1<1+xqlPQ5AYs2~nnOHZe=515rF z)7TX;>=B)q&f1D0E6HsJ`vC@_+h<_1KGm+xU@3wyf%>Je2Htaf@WyqM_7on&wwTZT zceFZ%^+ia7mnop8=P5juHE`~8Sii|WpGK#$$u7Q*RJUbtwPNdV+-sY~7K*}K&3`s4 zCyG56Q~h+-UUXYb^&OG?UuK8twf_en(A>tVQY z5aR05p~V>f9~3bMOk)F$n8TWuo9NBwX<8FVjNi`zB`l=7b09v5oyc`ATMA74b}oxU z?1#d+Y`xE6sEoMFWbzOCSpg>lVEFca^xZtbZ6oXfSh!%zw6MS7l@LcS=d-i^lQKS( zSYU|ofiLq_FFv3v$@NT@7d&aDJ64FHKU0?lSXMS|+yeGc5Sw<_`Y&W_1RjrP5gUf$ zL5o>a=V`9IrvsuLqv%Py7qi-kqf7;hv0islpCxRO7+79=xP}Q(#6~LB9r@vy;n@V2*H!|CK6n*Ew8H^>t3Q7mL%H&Wy8VBSIUySpO zH^1p~b(p4o%`OUWsoOHvNDQ7&sms`CFt10;z+ir+>dRSuoRq{ZXRTm3mA;$}a!I&o zz#?_)mO_t~vwk=LL@cLqqUU|uOKfk2ci8@?POapWTnTli(d-p$so1g?d9P#%e1cYD zo<`HsmFz1RThv*_2KnTU#1cyibS+x67`^lX5OF|U=#fEdSFun;ozu>(V$Yogvv%}* zR#_68ywq-PU@K%8WKY@(JQ+*twz77W>p%bS?-mMen5|=-?4Hl5cqs#)b~@K;MdXGs}I-n?RELDJ|x)gL9fI&bM-(A>_EX^ zS)l(F{{DZ;Q&HxW_LQIJ4Xi-7er0*(_D=+=A+{GwLugFa2e)N-Zf9-8Dif*4b~Z@3 zLOZv!12{LDumj4pcl6s1Hczb7g<9`q9mKk$Y3@$UbX#LVl@{Ln7nH#N z+`<7is<9jASqU0z=Iw$~9M}QbfMdA*k`syx3uvXrVrlShkc)1#Z#O%H_`1{fuu)>K z{`6oEJ5akG*YcO{*P$d-xqk6$C@cO|y)NAALBb0;m|pE=O{;&8y&67HR@Jktsux#7 zR@h7CeQb)@5SK3RV`dS!?6#kc;09v**)%b}553rr?ciy8c7T0?Q@q%NEYjf9(xG~J z37%l@*Nwh92omv(ZX9GW!Nmu#P@oKOM;YiiPDG)_vJXX{`6eF`I^nqk1ryh3SlMYx zIK+Z0S96r6XW|w6kgniu^~{NE9xXeBN&K0f9s&n`MRl@(eYnvsiv@~}o6{FrY-a7o z`|&mX3qOYOFC_D0TgiAVCO|5D>p)KXHL94+8i>xjs7*HOP{|V&3uj<&UaIV|cke>0 zv$5ehLRYduoPQ&~!z|FgYjH3sJ1F5WixOtg;=@?Jt{x=juqUFQyY?anOO2JOCeB`L!iw@@;Sr$V}p=<28BOt_%C?A*+9F` zV7cHp>MUC()>}(%dCcTIe~>#?h8vbm9yWK*n`urSNOtrf+Lj01MAk;Sna5g)Ejm)= zKiE)QpE3OpRt02_{$Q=e4&TxFKcFDLMD6ogfY|&Dg1E98a4?vk&$bC7jtIifv#H$d z^gP=qtkuR{Uypp&wQUS9zj zxkxRpvT;IfZPQh7WzGYyLC9WDuGiTGXdLcbXEQ{%*EHk?I=`3FZm^m@BVKYBqiimI zRNU*73gcH@K1|gP++aNgu|X(#7Jw6*wVnm6izuwne!LCz1ZDd34sdNHh5pGpi>+2s z`k!np;Pc{7)?5s{Nbm2l%4EC?4u69N-^GsOCFR~_TR6SDhjwZ$q?~&|u&(EM%^08J zMsG1%*TBMjtcAsnD>WfaeouYxvoT_wAL#gfmW16>&F?Kh!?LVG)ffhNO{1SBhCEKvLl? zD{^@`SFaOMg~WF(0%CpCI~3X|=^cv^+wG!#@7QKoKn{D)LVz{&o-Gr`X+a-wr;2c3 zS*p@c7_#fSQd_8KMF1poVmnWqvc}mW6njGhRT7n7VDytCD!qg|T2)CY&#i3h$_gSi zQ>?6Ha1n&3U@Rvqy}2C@Q@RSfXaz%yxN(3fU0^|2K~Xx33BEWhQcPkwiGEO&-JrAs zR5bgVcBzV~rSvICV7Pm78?&`H95Nl}$i@<{t;xtwn-&dq&9s0d7fzF%0o5|a%Nh!C zR(h6ilj!bb>s;o3k=fbTLlS<(7Ko$-BJLtHL+aa7);JZXpd;2Pvq$ z5)WDCczLC9mARkkHQSWq8ZtSlx$yx1PQ0!5-{j${EOLJ0XbGVQT$N8;sxQ!Mw{RiV zO&NhT`GuR}&5e`Xl!WpZW}q-FSGD^qblXkw0(QJ|QzFC~<0-6yVifDnpve`Kjxg&u zQb9=;#9CFg*6zw0!6nQWOUmYTW)t1=Q2fQ}zEt9&eCbR$ctCa&no&`S76LQgkKt?Jfo%gTgKIuan7v@b z;;-x%UEHX4HKm5Tw@?ml`#eej1SlJ9@jj`hG;oesz+ZB!P4lWL32y1IgXjE->%e-` zy=qDwm}0wDSJvTJcUyIR60yS{E&Q&H4^SEiuwq$LLkSRs1nodg^h9hlMY~fABds{B zH^MW%cQwpC2_+Z$5)@0H)mHpm=y@?l=oS%63u`Mj&b;aT)GsBmd2A@}KOk|7H*VPj;&w zT10*2jv#zP)f*~Z#s1y22@N@>e@inPDdR=A40_&38SWkfQd?9Xn=t)uR{I#d zzZlk%u7oOy5NjjDlu%(cO$bwFiheEVMHpu3Z}M%fq{DLfo90Rst!=KjQektYvgq2J z#1_gXDA2dIP|jiCDJ_*gVrVE`ZK*WFDy|TYRlJP`hbv=XF?%{(nT*BUz7^*3dm7bB zSs;2hrPr;Lja(9MjodixNNZ)dAl#vbk;;!^L}SX2R9ZtzRH2O$CY;brZ4?&)grIYj zvRU*BqBl|K++zxeMy21Vf3y+}yQQ_!N(-@NBf1!^G!vypRNknxAs3_KPJN6@6o}qR zBW9;&LwaOX%;Mz+G$dT9L~(6_aVsgQtr98rE6qFBR@n{*%qi`ZZ-jry$AlT!PW?>E zbTO=+ykZR6??HQFl(wQrU3wp*{ERjGQ+s6=D0*(KVOv23)oSy@@0e5%V_3oO>j?Eq2uzv`9p7Iml$_Ri|C^q5JZXSZC_=gaF@R52TaJP z@B1lBh4EVR{)$-;t9`Ad4p8a|h&@VM1}gXA-MVCuvQ3Q1qv*lPJm2YF9^6)XT*HvZ zy5$>RlS!Z%uj%$+#UyB2ogvDf0yMnk5`pN|D^iO@rFx1|39hX#0l?Q^M!hg$8?X!q zIh}&YzbRkhO7+3tyTlvQgj<*82hTwl+6YTx}_p7(?Rj)j)_E6=9;8kUt zyHiJ-{3WD}$%agm5vNUF8xX%p@fAe*E;SvYBm^`#Yk+KfkMlCVHFSy)VtliVX<2f5 z7J%jTioP46tZ|uHo`dCD5E$)9rJC~yB(DW6aiOszm4JXlZag)`1t@g#+VdM%46_4o z^SuDJo0m`AVC!hxNTtfCwWx*8H_kH5DFD;s;PeW2<;{KsuUiPxi}?t%`Ja;-la8TKs;J( zq}Z`akZ8!EFUKnHaKQp4eXg_+K4?FEu2c}P&i8$xB=~&h2G(Kq3$z?HTE@a|tRUXv z7icg4omOic__6S}7Cv5qcBhv@jVCH=g=p>cMCHB&YtfyPlrd7ElZRGovJxwb6<5)i zsmd+)Uk|?L`?8;Sh$Luy)>Hp!pn~!tdN@t7V27SG9h7nn-JY%t;s$dwlmp_z*UM+3 zgVD?B!%Q%LaWO@tDEpyTd6NRXmaRHY_{6_=_cKxkW)s@xKrHl*pZl#eDKG#scXEE5CBeOL8g_?V{ZL5q9OXOgr8dq{ZVFJd z%$bJ{&DZ{#r??7Yq=kg}kcwWD*L(+jstm34N5*@u_p%Mut?&4L;wjCvDlOvYItsYl@W8(1#d|1)^+?n_xf)4x+6-r> zkwxldo-d314tGMKt+z{g~un!tbhOd+#;hMGU zD`lM6E0yYg4REH>$*+~F!U*mD*9rnH2ehFl%aoyFgPGK0Ipmual)PN&EjGSSXO}DW zMNfr_mn)+{w}+8ZS9qq`2$C`6vu!IN8$zN#vJ!1VAGS*QLTnyRmscsaij}7nm$W@* zYG~#HF2pmpV>D?sn9@2ry;{kJLDr%*V6zvs7HgHk*e=kDZj?H6U5sLs-2e^myF6^GY=*!Go9$NA-XHkP67 z-mYvBu@g<)rC7v(YTA=s*pJ{QmW`U?E_2o3K4p$LaE}(fUuh%22tVb3@>ra_i#|UH zsr?-7J*e~$K9J#%GD1{((&R%B5OQeCAxPo(scx1s0nlBQrL-1%b)`#LN=q@Q8+l|a zZM<(J6qoRWz$i0(j&+gyf!((|4a)|)U|XN9)bXC!v-n?~CU<3c4M==VCs4)NkKZ+D zV?S!Ivmv11V0UAV5>c-HmG_wK2lg6Qw8uG+ki}+~v};Ep-oVhVVlK#Q4{c8_00E-s zds68pxUGj7RMGK6+*FP$MNfeuWWdf`Y0t;>yE0e!lIV93#mN+Q8bTeg=(O?!r)p;a zjRTZ=2Es}{Z9St*5$sg^EVg}%Xy#dEme^?ssI`*rxzSksQL|{95dx~{?Cz4U#JR{h@U}&4n}M`GU-5BHJf21iiBWlZ5#ntfR@@^yL{D{mvsxuUFdt~1rZH-Yyl_^Pr< ztnvvRx(bmTZYNijNKc`!!KrAW&UN*8kr>1|&3FyMB-C)Tt^-HywEntM89ZzcPmQ4~ z*Oj`W-!CNI0Dv#hx*Lig4p9%>KsS6|(#splZ`d+yx`~C+j!xdhQm+LB|RK z$p#2(yZ{S;OtFU*DpSvX9%PY?davN}VCe-tm{ zxLHtrgV3)-J;*g|B+~Y;N)uaK7+{EicV_ce7Q+zH+nS7kc{7~t(eHS>z1U_*U9gL5eC*p%r zhw_n!?aN;ul%|z)q3^RCE!q$HR(HzbCPelZ!>KI9JF_e^buSUw?&8ZB7035trF_L@GV-&OT(m$1zSShYr_Mu>8fD?W%V zb2^s`KK6g4y)C$oe#U}H!!fk|J6xw?O!6|JSWNbW4rqC#7O--CY66D^{r@Fo`vJ(Wru6zr9Bg1-CuO$qp^jP z?t*EywgNXsh$a{H5jf4fa_UA9kS68TaUg~3%d1UrIG0~u?F65O09Q3a0K;=tAGr3G z-CY2f;t>GvD~bno`VLaq1W!X5m4Pob3N3Noa}h0uf&)VDy)c4j?n5$r<-6*WZcgJA21Q?R-`x8)am%M0$8oATo0cv-V z^`f{MYFAK))iu;WC~C86s4YQ(-_%g6<4D!FrutY^lE}Fh2HEIunqNzOBlfvQ8G-6( z%;obybuc$qsjc?(2Q`cNN9t5Zts?rX^jRIXCiLP9>Ztr8 z!o77c4a@0O9kqc=(NYM#u!nG`gmUF-!8A}+sYhKkmm4eAL+x$Up`LnIIIcCWuPzeB zHgjMPr@D$_1BuQAsXt(2FfmwdCmhqXU^P~NtX|SsO?8`*&0C$}%)_K1plA~{vev{q zZ@}!YNGn^`*uPw74TdSQP;vOETAcH2%!|3s-MG_ z@pV(c>KXYr!`CKj!O_DCLK$OHgTO7+%Su(_w0#su!U=jr%I$z=yj8xE`*Ob)35)Gr`;5Y9D>wTy4~5K^u3zsXjib zvA)}9=}1q?1-)*RRiuFQn622DroC=FX$Sn2Y+kl7Fn4R{;i4Zf)zQWDp*fH-_!iY{ zp)P@akG89YS|W(OZ)%z0>NZiZYeOScMdYVHZPfOlIosQ)O$D*ybGjd;ZU*!hM*}HL zbRt?k56#{;MzyurtRG!7s(qo`YTi~I>pVopz2ml^JG8Z}Iv++#&D*KBm4cIs6D z$Cs^R)MtGr7FKXd`!Fo2J5GdJ<9XHx-Gb7DWLv#xXi`g9P#!~i5Kq7MOF!ePD9ZkJhwJp9mIu`5mHhqXyW5l?< z6k}GKL&-MXtZFzj3XM}gLpQ&PQ>(hPgXuZo)VDkxj>9^fPk+U!Z7TZ)yF0bBjcG0! zEl-BGwU}VFuQ4zHa|bM&7SCyI2X!vwyxJYHdQxdpNA*k5Gjib; zYSsm_$FHVWtl^|wSIwp9JmnFJGc=BChxJ% zcFUW0C6>|7dN37Bfz&+|0f6kDIIrKM@TM|(iK-0%seD0c1Jq+;vrMhyKy`&A zx^&R)4N+qR=|#Uv)TL_$FRg8&dPoqf_SK|e>H|q^yO|!1RDC?>twewdjLTD3-#ByO z<*4TKnYu^-o!>M{J%|IG5u?=*XdYIMR-?u48|d0-HJB^q#;7|%n-7gqI}2ZG6~?Lv zh=w@TU#OL;nZebDbCo%avvbWh&uBz`f&E;MV;E^z5{ctfqZpe_G2_%6gfMX#uQsXj z%^`#(wYGQeU^o5e6X(bQoX^>L|>NHX9$aMr0)i1;z*R^sP$Vv9Yv zqgai1{xuJ++Pq%U&y!UIubiTGaNY?+2adv&H(Bju7=+Y+7{0b(iYf`Bs?n0EYE{qY znH8Ld!McL_344qRxaP!hQwvPs44PZW8+t!gO@>r9 zahiJAuwoa#o#G@mW{?ETyT~+Mt>HakX9Xv~!*itBk~ci9Sciw(PMS7dwTHQ^#?jQP zEGH)sg0QR334M;fUOEe< zZEX>?Oo#=@zi701Dn^@YYfN3JQOFBFYe-9hHKEy-9!RaNYGew(;wBnAJT%U#m@V;v zgUyyxT!|fkuHZ8497KqLU%0_&YxgEXGR);ZQT*~5v*iqrC!cc?i`*1AhJSi4ii8|| z_iKC?(Z3=r{R5i_IVkqT)5!25L)y^Nw-flNUfDBFzBBUI$62y@1Fnrd&GLwYM z!g2hDh95P|ZiFJEH8vET?QgPNflXX*6iqhSLYq+Z0@X8Wu_^p7LmD@ojI$anmtlP2 z2X%w%|Ma~^>DPT6FfBg8VG5%-xN_6_1*-P|Pr-y%U1P#u7}DJPFZX~yV4KP_A$5<}B zlof*^qZ(OkYSk3sp-H%7KaQ=6F*T(z77p$)ae_KNA{?`Bn0*q<$b?s?ce1>Xu?|3V ze?-4;h$=>FjH}T)048%Bm-uMcU>Lwv{=@$nEiuma#m70E%4%61l}y4_d*xI3pb!(< zuCM@g9jAc6So>hSpvR>}qp0pc!%)Ru4;_qyzhS&^i+hmWd6st4b)I`60y&i|rg00^ z&=ib)*^>AA*b9&9lrh>7OQ0wdwAZml^vUC&Ih70dYs*7N=OqWa|7V@S+IBN)7~vCU zxq?ciHP9zq?E^g?EVzuRGXSl0euk-s%1hBN7%CG{Ot2^c$gvd4mL=SG&?z9FCxAOf zc#CD4ZpF}n>`ACMj^BBqcc(-+YOx7M74pIhscf>?%SWIzbPp+@Q=mwKJ*BThGh_N(3l$=$|uI2g@%D18EbhR ztOTPF8(Mf16Rr0F-b{{u*yp|Zh!j=HV=*N9+36ItSgq?DSK2}yv|tnlg%*y++kEUa zX0ci=1t&9x^s#(BS3C~nj(Kvttpm24ZG}$4lL&ZL#-LJqR?zF7hf7?-WTlm18YpB#_d;k9_sEgz%hDz}sXT5}Sslu}XdDqY$GtOp1_ zd=&@4xR<|!=#ek&t&YBfISo$$%mFdBKn3uONHGbwjNwN>4jLKKBEg$M!s=Oa_*+R6r^?9ea89JrOL$A@>Xy=G67*)!J@hWd77CZxn})R3$c(ckF(>rjc{isv z@rLi=>A5tUTa)uZ)iLRCDGkH}M&@n|2in8}EZq3h2W!DP>y3^|%{Ztm&p0dstSK0- zV_ba5h`y!|?him$@0C6{skB%7IJN1)JM{t_hC^)jCSDN@Idfcxw;`_|FPyY5<{aIU zYmEs7O>4k0gAcFVNvP8N%GO>{G?$HOVNxtuxE#o0{prq*QcB=^%}IJaD@SFyn9mXVt$Za-ZoE^gm*NA!88w zhAEOcFl~O$!qxC|hBO;SXS7@Z(N3;e=#Q~+l}ZXYEn;Uzm^fF(1!o8(gS7xbijPJ= zursC=3HI2-9Q~5dVXJ98gvLt>S7MRsIvKO&ImZ|D4u0Ra1sxgenw4vm;IjxQ6<)%h ze^;_~QcJrT0m6B4{D%~DlusUne!i&e1=;UPV3iVq^%7w@Y{-mh7J+*{wxT}}8q)po zQM0vEv#G(@+@`V79=iyP2GP+X!IIPUJkW{<*^6@ODf{zK$7Xc%`phPSv<8v_4*wCI4W5 zd>Ve7`kJ=)naLS1R=2(gaOUXXzZjKs;Zj`_XyQ2dFg)d|VK(lm!M5X?A%i=Trp{;v z--&y8;)oG%!_5R}7=w+odCKtbv2*`cV1C-`cZNCpF=1T(8T}jQb)^hhM6bY)!Hzjp zqw%Uvw?NaP(UKE5F{f6Ovw%N60%M{b44KygCzf)st%?aPJOozC=i2s(5OP9CgLnuA z487u?!RK`}!FI{YIYuC~e#Yjel$xoZBJPT(vJb>}b9dUUZNLPzN1OrtqPB zx$|Z1fWRN%H<({YJ~2LAI}H$*0VCuD2eNb8F@#WiWvHJXxDLaLx1@md@>s%~km9-g zqx|>R(%&rnn!(re@XP<%cRs@)Gt&bPA;Eitx1T!4GzOsIxY?gW?xsB&5au0p2D~xs zFO&F&tLPVgZ1l?hCw>cOV>)%>k^)V!i?M!zNhrqcmb%=+y`zED*PjDLd!wFpr!JK8 zyq3u0OCSi7&t+^bto}c`z5_0*qwAZ!vfdd57L=uffG9;!P*E%>2sP8aXgJ% zD0?@oH{J@03}0aoWJ6p+Uj0BrsR?$9KeBQr)U?x0xo7P}MWUS#qStdsPUbc$*s3d667l&Lca^(=J1s^G-9`*LX(o;Iw>^+_muI9SBtcp=`{g~iO?5lu9g*I^sIIPBF$*@!ok8o*I29A0Q+T~E;1%aw&3r1<7nbLni{~c@6 zf*<63-`C#@rqrT1kF*|g-{L5b&r8x`9KNGz#E;+}ubQ|1D7$HVtCO|p;t|%O^8_x* zOA_WRzhu(GpX6lU+xNshI2NU*t;mnywroY>GbweM+ySDcRm*!QW<&vH%ar$`$1vmE1?6#2PenGv-0 zXGjEw)5o773Xd61uUE)5y{xhY`G-m^(7(FuqkVZyx=t*I?2 z{;lcMukwJmc!;MH|-1 zRfHGsIvJ(}A=KbEIo<8etB)`Nxi1(9mSGlm3;})oLpy(iv{`?aJl8|`;8;NM>mi(l zcjyKzexM7bY>-2cP8ifRK_?P`9Uf43J!Y4}qzwt)~{h z%bi^3!J$QLYu%oSwQ>p&qS69;pFe+x{^u(7*&^403B`|Fu;d?U?-uz9-ZpHND?{&k zajX0YDw@52$Uabj{q=_&;#tuBEtU!Nc(M_!YrFye4;5g}J-jFRZIi1=32Ug?HaP?; zq73o#oPH2L2uQn4_K#XU^COOtes;RtS?Yn(A5XBk!E!uP>i!9zo1=we@G4HY4iE-W z2DzIdw?)_`vwToW?ST7vfD3fF^$g3|a2pg<2O07Chs2Ko>eIPbuw{*7AglszHt8?+PR zrcShSC*(_&8qv|6fC9vw+a>$KTGxM<>?`SpP{Uo2+NX4+bGzj3($bDp{ZF}rYeGk8 zGE5FZhTeyakAO-b2;NIS{0YJ9ZQA`Ogxi-Wc(+_h8ty^OcgykB%p(O-3JL<_7gP?z z7Wbp9Z6l6hw2^bLBRo;Rgb^tGiSl>L2FF@|z}#VpsHW62QTcp1jr(O-g^n=r&6nNz zGc+r98{#?S|ynZDAz0l6&QvbbjTGWRNM_S&Fp6r!- zm0makS-5~M_#p6QyW4}DWttx0k z0SF_KLE+dS;o2?oKP>Ah`GD*m{GlCGaOMptWwj8``7DzUyd{+7Rx^@IH0=PCE?IQy zfc#VWhJSqo7e4_u`cE>h3LvWb7p^pt!%Hh|(bypR{UF4}p7-h1LAe3;RLw*3Dc`2( zBH2_w2!qj0`Ac2f&jadC6%NaxHSNVHME1J>%=WnfkTp6dgKSd2zz7EdqXBwC?S_ps z{xEjqzqIJE99v_mBVc)mfMx5bM~QcL@h%3r9r1Yz;SwfxlsXciy_LiZpw32wumago zu1_E#9YJUNNd|v8XBYevd3>h2J zrwM&?3ZE0)ht8jpw=zR-6*OnktkbevILqok69}$gMptE1zKOC2q7nBLu}44aQ?YL{Z&o$Qc|9)x+q-8G!m; zdU8e%4Xo7wCM7xJgA!GVt4C&XGUP6K(PR*$fw-CM0mYn^!-AWh0a$)EJ&Awa#Hpul zN-iJ3ouw>I(!3XZVY;yXmyOUkMpaoDpz7eHf z0A*;`2$vqo(X3aJx+z=J@e6X8Ll3-JKgRb5(p;2BmEYOT2~1-~sH*S&9WTmUnsE`w zS#~#Ce^LHZDqo)lU6ND0=0o$&8>s`@3D#Ilg?eeZvr+|8Q}GH;23ilGTEka( z*6A3{z9RdFEk#wpCbS+{jUH+PqA<46ekc*YYV81ByCV0OyxvpdRk?)}x{u~xm9t?o z;C2lMc3nisz9wf?AB)S2t=*x8KS8||b`_`JLR_(nr99pcQ?>85y`fYR28D>RN+{8* zYcM*QLZR2?<{r_zfM!#I9O@j=A~xKV+d8sZLRtwtCk9AoZ(=WP zrMEYMUEwZp3wUQ4O}GVc{{|*o(A&bv{g&Jg6CHCKMe^yV+p?Q9`V5(GLk-vNFulEv zqq6ZC^0*_n(nk(;g6r7z6yv#6+Z@C z{@F``3G(#Mm*GdqvJAS!GpO?*Mjdfw`1#$HPYXl8dvY<(<-Pa8Uag6uzwd+M*lN~2 zfNo8y9!XvQmgAiIgQ>tuTIY2n{rb1OOVh!e{!n(5eDqD7giu_tdZ735?N%lg7>F;Y zS%u(!z6+t3g>tplT|#VnSXE>jbu_=8TK*PlY{!$*OuaT2@&$46^er`4SUJ?RC5L=T zR#h;H_dFW;NbVxezDFRxmePwya;Voga|M`)xPhNru@;AZyhvWx& zgLM$__J3IfwB~)D+B}vkdzJ4b&MX;02o2B@va$Rw>J;w4ZuZ$Ry zpilOa;}exkiFks|*kCWUd;%IcW(TD|0dyez^f#=~@Ci_7q@-_$eC%iSs0*ocgK`U4&`v zK{sE@t)eE3|7aObYej#) zmXp1L5j7*(Sp4~nQSbP`CdsNz6^i9CWj*VQ)Abp?YaIPtEGJax=l%)I{~tAhKw(~^ zZtSgV1>c1DKhKo4Wd8={Fw4wC-pKJVOQwx)rcZ=gqp4O5kI=bBPbc5rbN#SD4FiW(V$&t3X?>b**LnW*?N2Y zpgovKJ6?)W+dHndcOEa;h9b>?do+qj|6bO!G&BaA!y>BwUe18-|Cjf26u;rGVujdI zbmzUC6i|Ay*dqsu4$n>oB^@tBMe4L*=|`fZ0x`x1xdOkE16DXsTfvKleUS5HsWy%y z?@TK7QSK)NdeY#Ja$U!aS^|BFJ;V@;W6MWa=9Rsywr&7*mz@QEX37d|!DRI`0T^kO zB`d|&0}Uad%1IPcp-8Ftvq-NAlJGSgKas5TY9h8t{UAX~w4<0$Fm$<313t-v+HY@+ z^Faj1*b^sE%h-!T8+M>5NAPhfdsG`7j};ECV2;*?3tiZy_;!N$xUK4_lZ_`Zq1n|w zSky$J^FL2v7MS16rrj2Ko#y`h0j!eFZ@HDWRq=?jY5osvq*ULD%4t}T^QdKC=dqF0 zSi^?HD$T56k>w8kWX%)-mjLR2D>y1NEP`$GQkMdLW)e#fUd|G00(X#|5*sF!KTcIj zvC6`ms}zfn92?Q3QcT=$zoZmPhQHtgk@{%tRX0QWQ!@o_&1VkMLJq8J>Apc)d zGkfNl{PTM7PNo_uc}b<eA+eOFMQ}SXD!}^mAkSb?W|I#d0(~nk{ zW@(arGjkc4oz}n$@)~1*I68)iHM#{wz5+LwrJOZz|GAw&1+GCVD%kExn^QPOK{o#Wp#yUQ)fjR9?sG zpy5;<>#OTbA1$gWk_Z=D_$Tetp}kHAN$br1l7980`_8O#`B5q2%*ISyR0*(RrI&_$ zU6}BWj&)(7QhF)s@4|v{`PFO}Ru5do2^UsVO35av9P1(t^QRu=SY!8JvH&Q800nMr zia8KuTmgJJ{w&8lq%{`0RE~upgqfurOLAw^5fs=I4zn`E{qsU$fu<^2s7ra~CzY>m z9#@_<(zxxxJ<{rIVlDGAsbbo(InTSY?ozX+R6`Hg@@YzGde)-au0db`j7p;MErQ$R z_rj8j!ha+~x(^n`_}o~C5MB8*Z0UJ)ThEMA#o;u_ja`*u4Aj`2HAIw)sqQRDI0?A3 z7{uPY@6MXShN_we+a#rSr8^$XO^WVHZ#`K3h$f9OICW5Y`t6;CtgRS}{sN{zLPY*9 z$#^@z4tf)$xKCqB^JI}BkCGrw#)%J{0TY2cC?aw%AT`6!ayuo z;fSYiEQN#dr$mxyi#%aGiE|?pHfgYUIuQ5zuz#i_5=J2bFZLPnDj)ZYuvr5W4+q~+ zR)@F2E5J3fteHZYuZYq8M-?V+DpRVkM*6=PazQ_q0yQpZ5Ww9vDMgIDGmml_D2 z?PArKDeoY863z~eg4>J}bG+Srs4fc-o^lWCu{}aCJmfieWr&%|6zUB2f~|_SaIBpr)9AM)19R%4cI95&oy;sGiYrCHdq>c zncN$)hThj+Iof43K5=|`=5gMb;iSIZ(M9}XeVc?x)rIW158$~i00J#3a=voz7JX98I zF$)Dr4Bw-g+P56#0>X+1wGT)D5_cRqxUJ}50S!~k6 zWZX>oSynDw{17V5LAghd8nG5qscuv+fkjFI^=L=}8&}2wQzG_icvX6tzyiUC=o49b z>42-)K}%^;BI_Jk}5d#DS$NOWdR$&}gr|}YqE+0Wl#?Yz8tVhU92}3Ux4?zL~(H8bXDHvEq$D@|GX#%eZY?T)s@|4;&0Z3e@ zolTe@EK#pEVeMg58)?A#sjEXh3@iz9)l~*oy=*kcE^Ht$#TL42V8f*_H)@;A0-dJz zgD^<7ZpBnxHBU*#$tYD#qccsJukcW9${I_o7u9M8lnjTAuFXJ5)$Tcyk>uAP? z_)f)*C?aaHf0FS{qOlMsp+~;2`pwUjcQi5udl`X1Q$QiMr{Gl3G8sK+Mk@1jyWnD* zIB~Q)+G^~f{8ZM?aRBmQRV5a%dlm9;&U|_85#ll&eaHxE+?*v#sV?+=b5Jh_X-9MB z4ad!k&6$%%^6W+rTHu&{Le4E&RjGlF;#y*>Kc!hMSpz6XPPN2QvwJ}+kZx&a?^d7= zq(DdN+L~oZfpK)MHTxAb)`T{!gB0_LF12B|%Z2U6YUIVfj&TGE04o9~#UpLm3iz=O zZpYHWT%T{pMoBfQQnU7KI()A$v}Y4t!!Ri-uZ^=&#Os20$W2P`0Bm!YmULhhq?mg2 zX9wmRwL(@8%#MH{6vZ`9?YieT!CWXaL`Ha!3Rx;#AsdEuu#4`N%_8X3G80W zced7m$YUH*LG~u%B=e6t8n12x)oD(AOz+!DvylHFZF&n9rgl2j?!>~od!p`tAN3Is zTp0DmeZ~4|75o@mGT{~mCFWvrwUMe)jCwuL4p21y^C*>53|nROE(kALjU0wQ+Xt3|~&&3CaC zU5hmI*j7yOx%_6f&p)7iPmen@kH$Y;bF@<_PSHPTP^G|60Q&eK+ghQjbAA?Tfk0E5 zp)E0Auv&xlTCqADW1&*ho|<+6G5?xIcfpBtgO+yz{SA7(3v1;uu#~k9!(8JF1fCEp z)`r5mvS57`J&ulukcpyZv` z7uc`DcCz#ZoqCF@r89TQZ73PiS-w;&npi)U=Uco%oL3Ndf@dm9&K|>bqk?tY;)G+u z(i-%8Kh{P!`qwv>)V%RRFJVyz{z|U>S+F$tB;xt9jH>Zr>Y3CQ);wabLiP{E&H|x8 zv9iy*Zh(gr(g{&{1KsM+wmJR6#pl`59?=R22H^R9bO5XA(hymNgd@XXLNLtexUJ+g z5UB4Ug$`tGq=vU>;y@N!PLD;ksuYbcRg&-k?HI^9LlNvch*htr>%Ei6~N46;y5cz!JVpNSI1j2f^cr3x8}zvdk~8NWwl|D+Ue0j>?(w4D+aS( zk#B;85Y0XN+kSSLxPW($klLEtS7czYb-Ur45Ja+)y@8nrlz};r)UQw|N-zt+(OlH~0== zs#^(1VZ*$Rz#dAn7U3Oscwv7~fbTnNW&LZK=EstQeAslWv0{jFB))B0&*c_)vus+q2 z=iy#XbCT;CrkgSm%sG5xl3-KYL3?|bqX^)WB!C#!i?0Brio;S$`vwQc-$dWwy!(;% ze1lK?SOBAmMYMG!J`eJN2O}XG(N3h~4Cd`L{gQw+gqnv!!RM^`n+(=mL_OFyirx1t zhB`!8_zAIq2&61L@W5Kku1oo&aUdg@KpwzSAnR+E@*|5UqDKn2E^bKv-4PnU;_BcZ&^DykLbs--=(p|=A+}7M``egcP9b68#j`E zGI+t)M3Y%3>9-B^ax!}e+UHsh4#kY;=65;ljlI{v3J|MJx(9nR`%E}VjBwWNd86C& zT4`N@9E>d3;VKi`3b)+eRPxOYjcg`jY?)8ZV0jv;7dLnN4gxTI?(#fr^RD-4XC9j^ z&8bK!GuZ-2XYS2pL!|l=wVuVENU2jPem2|gv|^bEyLxLngzO3}Gt1wz?=^_8wP+3o z>jZr)Rvl)m*c*-)DP$gtk-{gN)8?_o8pLljf11yJL99dbYGNz2Qo>ksvmY2-sv2E1 zJNyJrSa((yO4>b;GT=K9(QENCP$`3C^FPbjdP(wmNk6Y(qp-C-SF-w2zZd2XE7>58 z2$#2t{U-SiF^^b{O<1s9Ak$$+2K$X ztXbF*`gbk+PWrAcP5zaQ*0iB_zp_r6wdS_#SYM6iAM?)N*h!5vdYaj|0hkhzJoj#7 z6{Ucw^k5_F)1?cvMwkxtbrg=Fh4%$qZj+LYw_Z2WO1j)U&;_9ArbCVk0WvI6^linX zO(3mrg%@BMk!H{(3GLB1v>>&u1=DJig;M*oi8 zf-twgvx>ku2Yv^s2gYy<_QD9NzlHtgFmGVV=)&^p-z}gL2U5aT7OtB$Npu{&p^wUn zz$#-a8&YH6V_0C}%#SO4B5-qFv@)Qiy4!AiToepBk=prlqjtN^et)oUNxM+}B;znwRLRqK z>P&we0#5xvpANBraV^C7U|@tCqn;E;~kTkFfaK4;P3Qgjv0~+~*dEF;}os z`D4+DavXWMrBgQr(sZDkFPzlRuj#}Q5c&t`(-Bq$U>kOnRq&`GiVMO+6&hxv1vIGm zE}&jVSq@mG2S?dBtX8jM5Nf}qamUz2DSRHaJ`MmXrcuWsBRx*P9|u&eplipOPw-Ue z`U?LA7M*QsCq6E}jIGHb$PnkTXuj8a@;$*)r1EoV&w$FO1Z!CK+c`Gssr?voJPEG0;T&ps5)|YG8h}^LJz9K{HT5-^(N+eQ7qgOr&LDck z$Ej46GM+T2*nDZ!6l!gX!3ox(uVGt}T^}+AQ^b^)xF5)PBD00CSb!N5Zu2<%n~0aD{q-e% zf0lVtx3jEF*dIu<-r5}BEx!9_*Hnzd6tVm{%I7}G{1uhDsg=ULazY&Kc2w$ySl76| z3$5v!^-*_pvp#hBEE@@pMYD5QM)*da0}hUAPV3KsEkB$J8vV`u+l29o7zwCKuQX!2#-FRo(=lOiOP>xXjZ(==r6Mz0~U>BWVhv zI$dOe-XC!vmwI6~s(7FZN|!-tboPj9Ut$>`_J6wsalTJ7-Mz%VDg8JQ%`)nInbr6C zRXjU-*#&XbSZ6Rh)j(su(J~#)7hHR6xmTC|MYa&5CvcMZy@7;9*U05eZX8f^1E&6A7(E z!fWgoRC(rygfx-xz?yJVBzz+hgq1N$oD>OtMZy6j{D({Jb+$yR>FI;~e8gvtuXApq zchtF}jyC5J)cxp^rPdMALR92Y$C4fhF6B>rz zRG})%i^F=o`KX&Fbf1XUWN1aZ9)J&@a)BN_U;$FfI&%D*c~-fJ!3s8U=IoL%H`cZ+ z`Wwg*O0-(vO&uW@ShB_TuPS63t5!hbY zh4RV3>M=W-LP3sCAJu~9J!G{5dwqw=H&sf*k7*)!gS)EyFcAi=BJwD1X-4qnhd8oy z-%$kxQ{3|$HBeZ)MvF{>oJutIfjJADX#7T5bLnOwka&fe;vmB~)o}Xo`>``RK!IPV;HvaT5NawE{fIU2TszkV zZd+J@pHZS{o7Gsyq@9^Z-#x-NB{9D4SMdAZf7Eanc@ zW+pphg1))b#3p9=YLO%XT*u!@l|O4<6DRrLx}d(H3yx{2AbVJS{xTR&#{@R$YF zT527khqw?n^exJOCeN+kZ&vRD~jI7g@{|=rHtE{Mulyn_D@){{~s3wB30)! zZ8jbecm}V!DNisYi@wEd+VccL!lc=B^$GLwbr(fIhgE~e$mgPW)uIlwsoYamrBcBx zQRJE8jtijFqAE2RYlnV-f~`I6qO_-Mk~H8vJ$MR@VAOf?ea32J1)Z=0Zg9>$O$HcX zC?wEQ)OCwK5IMm14aB^Q%U#vDRd&j*fH#(1W!&M{79(Zc6PYl&-f?}sm?4mlU9c46 znmF2ZD?A4uy!6=sA_s*~N33~flz6r1n;cV{UbW+43)K6vhL_f24VR!^k?FIVWXA&( zK^J?=G`dYEVAxeABDmoM(**drhN9lVsB9&Q7zdmP4Qn%yu;yK{{1-ZV!VR)Nj zUodYE``-jFoZz3Rd6KI6P)EtSsY1aM8vcR>M;}^;T&szDiG8;)bT}~EqVIe}9h+CO zseQ~2&(&W5>mi+Z!5T^sG&;UyRTBfy1dJiE&6DD=*d+jS%p?FN_Pu~&>%y)yP6<0Ijx9CDz%OW5x#lajpOi5lr|P-V zIP;RkzS@g$BVxYwn-bJBZ($=$`{^4H>56Qt5zFcX`tcvOLaKO#68>e4ymo0(yBV@e z>MlVgELl!G{q!$$i^QFJpbY<`^#Rrrt>V%8^y_F{WLsPB+lU_g%Qi@B57PWstfyBq zd(@u&RqIty39XlpBi(Bj6yYfHXCNPgei?^j-AVm`=!*@}w!<}S9^*Aze)LP~`I-%c zZ^!Z1>?djH1R7inGneR1w6>V}_>7a#(%vpM@-n@_7n(4>0o^HPah^*e-dl3s%epCn zrL4lQBSKcx5;BdtZ$N4-(x8D3wEhj`7%M!f=nXq68OqSMw`{U-#d^oWT;Ae>Q|#s= zYE+q)%8ZSa@eV`bp0F|loAe_!e9z2~b``$|=e>v$Kd^p2^FKO(?ClELP!C*?f*u7W zlqFKDP{9W%aVl)3h94n}ojKav|0B$Jq$E9E{lq$X{<`Kpn9#vNK82%!p2RlyFywu! zfm*(qg|$SKnxz(S@OS3B@DRGoD8d?q4*|7g!|OGCXWTg&Tvv>XFS zh8_BFm~|Y)idkI=W}Ko6T0ROUF9_Z3uYa-Ny(N2GKf4SdA&@`tcDe-(Pnb~t0PI{V1Q0X*lI&anA;64AlpVYJ;D&sUO%*_)UuVRr}hyM94p$nUsNW2 zwx~xn8ShsiAiEU0RfYVhIZy!Zg{opKEkW{5$)=r*2k2hpVJ`Bbw;%&L?%wo>@k!;D zXCTq|)cOVZ?kGQ+zi^IjQVUj)-D%QL;! zJ;kcb*)NsQy84lj(xa!5VYIOLcie1CNq)BS`1SD@aZq zDbkTQDz|v}e-0(gi>5g8aB$0;9l5^zs1ES(#pP`fxLQ$D(r~)!$Xol(onq@5(*lSs z{n$Zl(kqxJ4FIEhxz>1HZTH4(8~h_#d?7ovU0OvF>TF8uM48lF1#Zg&d#{-1yZ_1{mb!+ zet$efg)XR2cpT^F7q;pLkzSeBmgC!{aT4_|&)Z8CCE8Vo4>Ak1qf$zpNEMp2Uk{zg^u5P?|k25$0eT<6w_^6ZgU7X^-4NBjGgBgNs`a z|M1`<(qDilU+GtHiD$wZ*t08z=0?rpKkRDvvVF&IM( zIR~JI6?~;2PmIE@@){lR=70Dc`3oI2D-jTE@%%DjGd*dZ53gN1Qsj-?-ORE-N2I+r7pYzV z5Apfy3JSIkwk`e<*DoVl;YwKnJW`lg2JpG1KVC+`?&jn`K0>28XWmtja}BIU4h8W= z`nwm9cZRD2Iqj?tWTUfrWF;Q0fzi?0%DgHrnYmJ#hf3@Ip;E#8J44Al?g6{-y={!;4I zDs>;7JB?9>qwp7AePLO3lncw!j4LHPoO^)3N(u*RT-}Psg!5@-pZI3IZqMKx_z9x9ABt8x$ht6E|r>Ir0-RWcR(sB2ZeLQ1_$nrb{ksAsEj zkHAbgw!tkEMruWPG9JM5S9Q$IUF>MmV~x8xyBc@WRGFEI>BNrsd`sbM#pLk{uv#XDkM`r*0QTTGYhe!y7nJDMELn@BYd)A4A4(`|Z%pGH}rH?b@g z9)FpfDvQ;P!45izeOSi24(Bc6;EfhP*45IY6u!vqG4-s)z2m=c^7$j1CpdidktZ$s zT;%<)kF11(nd?mnpkpE)(4Vz<%`AsQkf#H-A=I9Y3`~1O5y;1!H+?g*@w^4kvG$N$ zz_ZRuF`3oeKDsI0@s5yWD0Eg$^3ly|rWVnMc!@~}$L*|;Y1Fn>TaPk@RYVo57%4l; zO{2>lNyBRM0vH(8j^QEF+|JZ1h9|H$g{oP?2>LCC`@mY_Xbg@>|9Vul4)>7U29co- z50nx=(cn5fKyqnFv+D4AfwvG@T$cy<`FF$`OnTfO-!B4+v=qwQ1)v55Njvj0J+I4C zE0x-Vz4I?5H`rBHE=GUny}EQq0T+the2WEleWcan;nKvbG`k*m<31nM{0a|fV?Ev? zvHes`mz4-B)d*6Tn-_3$;@ET(mj>kNFSbW%Aw~nDZKKK+VuNfobYhXabhA{tPL1mG zB==VrQB$xQ$*Lk;H{~u^9tAG@^|_Da_MZN%58`vxMY>v_*OuznrgE`7OloQB3U54KdWY=cuS5Hg8l-@{I#* zq@JhvINlr7&#E~76MmB7kxS7uI-WOmDO(L=hfol-heuCWPxh7^5^jwbNgQVntG z5`P4w)i{ZV`>e(}4Bt)TEumfX!M;B8(gAlo3+(ZdW+w4r!ka6JcazG!q;8G5uQcZd zjc?3HNh@BM|830gNK%WdbUB$EhwW5ray!Bik&h!m2R})k71a3v?Z@le&v3# z%vm*sPo$b(V+Or%$-Sfw;b!+%T-HbvH=~QdpR|4Z4-G*%l4rHUM)EvGyW8=KQqU>7+m7c- zm7bdiwC58fsd62&(h+o$!?W5Tg{_e`E|^0*^A?g6)RMmK3X*#U9q7t?NOhZ0P&eR} zvi@Z3#^DZae$kDW)##T^x0%@pW0UXkr6z49J-PJY;&Pi2J$Mj8k1y!KlW-AKEBdP^ z2G{ius@{utm8yQA*}Zr$J5g4Et|NH9UOb*R@KXUfcPsHU-W>rJ`lkVF)p$>)Gz|0u z?Mvg8Tsry+*n3psDNS3bIE~j2=(NQVVr6?xjJ=C47q*U;EAuX3c2C$#QMZJ7k&b>jFZ_``XjCB&FlKuqm&Rlo_lL61=lmokx(?eq))wh4Zj1y zD3MdZl*uJU+I}w5!JAt20nCgFrm=l^RmtE>Yy0qO+(*;_I=n%5`e5hP*+AO9JYK5& zkqmu#eaYE_ruOAQF7v!ZvBLQ6!WSIImFH+zU!EY%+_WH__bmHiH_k-WbOSCC>D(`- zVtX}QnRBvf1a|2&rM&u{A)MaZIjS9EXAVU~p`x9F^FcA-m&;J{?@Py4Lg@W|pmI0S zgnpRfN3^9M50cu=p{xCPQz@b|RqD?Jz`8Z*4^UdGr_BC5zEqf-3$6R4@uKtnd5q-Z zK#l{rho|@VK<;C9eBs6Koj~t-(f6pq0Nx;KxT}lZKe}NCXI-dchV{9nzb;fi#`@eb zQWxqw9?w{mID=6;$(7a*P`f@ofCob{Ts#1PxxkeS19?m5AW^W+8H29Hew1}`MZjWS z8J-ZQ2ZGY~aiw*pBZG>w@x>0+RwhRK#wv8?i;t{zNQywtGH0#!91jVdE85u^R}99S{9BcXf3p* zU1-^09vWE@89EpLbltFs5cRRYGoGWv)#u?NJvLH(9usLW>7!lf?O-0=U;&bH-k~`K z=d{VyC1)@Ee2gOT4HC8J!=O1Lx*3Z!j0=_spM#pjUZKH5c*Q2GoJG%(nA+H1)yFZ; zc-C%EpX2=T?D)I-Y!GGi+tlZlad`IKsXljvwX=Q?T^hoxXU)*5{luUjRj`cdZdF>H z?xEHkKQ#w?Ep`kNKwBNa0VA{@A_9CX1LEhwsR0^~VU;=|-!>!N)ko`$q^Zx=8A(^4 z$6)0P55E&Vnx_rrej4b0RuAJ*?oXUt>`bkhQU4eZg$N~pvoG52GCdu}-J~^_sq}Ch zD)XFRYsjl+1v{$4>4rIjSWsvT^6iY)3bZNsE6zqWnp^=M z@JTI@hOB5?mTpP~vC7&gydx;NQ5%8>s5{|ejvlb$Z6%jVixS!^Y62PzE@|+lgGk?t^c)2}n(+W^J`?(3Ylo+h z53KU=#5>D$Z9Tl$_?axBII$h@Ik7Rwz}g%`t?XEx_2nX7_TYOkyn$-H*f2DXR<&hY zyVzwoPl~O8cMHagYj1nPN9a-6qPO6RIBVSD!#KFpby-kxg=+V= z!kUL_kK;$3C*j(w&XcFwqm^SkV2VA5SIk!KBh&>UVZs2wK0w=Jb+RbXu15i}ItJtA ze+=uO+Ee^MUjAc#Z^_q*&1~J79HT}0QC+SJW=lydM?1gazI}6h;oK2)Db7_RDkvEc zt1GkM(`TK6ztl$VVM@e5^$fFVLL*KgQNTbs6p4Cb3l=Fr<}5M<#N_S-T$>_Rm!O|c7YrKa4$yG8$f8B{9JiaQ3?o{l5+GtZr9(#Ikr3F5I?;h5OM zawU!b!EP?n+04Y0mJx52nDHo8s2OofSXQ-MT zJ71&&a^B$$*U$;R0)x)|O?^NpLUqkQqR?(xOh|RKFC^+F$IYmaB<8meMGJ8SmPp60 z?seYTZjZg49kt2ek=6I1raIXoZYYMo7Vnlb>Rjh`6kk@XRl&Rg>QnJ<(qBe{n5NuHXdjG|dnOO4?us0xLUZ^g zig4Pwo6v#wjwu__LW)V-AN5R*L&e|NKAZ+-@>=2ZPz1ro5)nV;s8O4Sw-h6Y zer;Dg6=+A{ulSd)yQFQ9LMJkTs;Y}J8XT2+4?I0L*vz#sMKP}VuVS2Y@gkfMBo%3Mrqcf0^Pl&3UoG>?-IFlX~< zz5rL27{>4*{W7h!k5p5Z&{Yd_fFHCpX$<$$-&q7+F3*5~DjkzWjCW?zRxfSdG={g- z_;js^EuDgxv)W7c>U!l0l#4?4${q6g77|{U&XoEs|4zyYr0d`EdKDT63ejniU;1p@ zWWp!Ndg4V{l+Zwm9>-&KLrb}+dS6UQm@ip|ZGr%y?iDngwF!Jxm%_Ek z{k(tL8H}%NdSi^X99lz5b(Kn-u8xCrpnzVF3HtldR1en1`lWqlMb!H^yj>{&pebJd%zB$kddlNP@!4Z zU^4S!zxh*8o!Y@k0PkmW#U#e2Ta#P_PQ4+Lj9N!O;uH80so8TnKY=d^nAk`C5b$HF z6^KdO3vFZgBN8#KuF9~|G;1PsC2#5AM9|K)UXU`8H+9-zaW0v$y3m}(WpURm)(*%M zGJ&d4jKWF-PVtrJ6!l`8@N0DoyEhQPJLASIFEreQvM?U zNuW|Hx1pFxym3Gp@{rzI$tz?bjU=Dt<5)?&SsuGV55_w;Az zwRtOY&f(d*mZBWcp}6!w>7k*Ya(E@FC*j=A^%ZyoW>=60 zMt|B|!dLa6q0@M|E4qqW9h*UsZ9wF5AvRGJtB~B(M%rg(=fGbuf=LHE z;smm)eM_`ch#K(;R_oT&+^Sa1iypd7?N5P`@pN7-^e7Chu=&B(g()8_g@PVZ5nxI2 zJBO{s$J4&)yaEJtcc$~1(uh|y!pI|}?(b=tk=OCA_e70SC!kB+a*@JpxIQLy@t-u_ z#KXvM25(T_*#V5>ng7@n^vuNdmAn2cmPMDFEtYW5J9TOLDf=I&OVfQ%q)6VHOkv+a zjAoujO}^t3Dlh%#t2*o6+UiLEQRiQSwNCL=QD-2Hn8CqcIAcEZrUdoGBAE08UaDWB zYyU>Hpi_;!l(qM0y^)7|*Ld{*`K&oR#Ao$)U~sv`7pXHw!}GYlY?l`*gpE{&7Sn7b zAi~({JU*n=-w(=SW)fJ@AA)885!`V~vBj9+T(k=B?Y>5}E1s(@)Kj*-RzE6GalETe zgr`a^!vYYO6&AjwJ~N?^I!1G6LeKb#EHil>DJY5R&JqBZOXFtYJ^UGMo5jaSKTe^@ z*$^=0dYO}F^QjssuPmMYo>vPqX>UFTq^p2lMS1#C?a)g}x~X>Pl6!rkqoMcvE`>E4 z(at$MAZtEKV^6eG)>wY0x|D z7uY7|B0;rrge3K=lPEj()+02OX%+|VSro=ecg+Sf!V%LhefH-o2TfY7Iv`!HQGkf6 zbx{44LDoU_0QI#g66XjG;|UhMR*b+Du|cGmVoA-oKBfYQleyyA=sQnM+MA&@)VVTI zM#4BXK|RT@U{D51p35V%YFJZY4`GU^tv+8LJNs*~zm>EDx<`k&h{kr1CYt*BWA4T% z2`|)X?x8Hcq0U|V(v$bdR>r<6#b;3bDS(*DKD?>FGS~l{HNf z>(t7&PJiRg#%DHA*Xe;sFvX^a<9H2a7!be>Aifl&JKt z{2m8nf!6O@LlBp> zt=}8sqL`@*!xO6@4- zRZI9hjWl;O)%$^GA*|r8A9yRNB?3tQ$eT;UM^X15p*cFX7^g&@_CBrs5%g+CdAjx^ zuV1D!Qj7G0$fQj_;ydiiQ`4WgFX-j|KS5IR4^8_CTH<-&Q-6YJc0_CX>nG^zCRmeQ z%Te8B5Zb+|+lBIxEDdQzcb1`c-B#qf97J62g%qe`B*Q4=V8 z1$S^fg98noJevf-9Hd1ncr2VvMR{Ce+vOLYExmY6fBgdKeZAK-cMWeXJ$z+;xCX`y z&NwvG{eVcSMVoQ9(DN01k92Y{ZC(j^=G}kj#!4uiB8Qkit%T`=G-RJyvl=q?ZNGvS zk;V_8*6VnUx?RB03V_uKqG;e%0V-fB#b9*^wqe zSDwzTgN7t4oh<9H7J)CQ{%?G0IlprP9VQz;v}=PK2`eaJSLniTAR@X1Q>pbpS-cM= zt>+=SS#C4fW5A`7cjniVV7RwT2-*A&y<#p=+j0X;`w)NK?NQvYzU-a zB?kn6h|r%6H}Ms|opBAw7fcCIYv&e^>wbmpDws*jCIEE!LJHi>Tj|Cw5;m=Hs)ZUw zahOMwH^X?WJ8j&|4OvOJQRnxfa>x?HNLktGva8*u2;HvftI1$9Rzi!GmC@n16 z{l&K#_oq*~D@o~--bs>fN?l}$z&@^`yXqL5P?~1>TfcIZL0kcXOwo>qu(I^97S>G> zR~d<-){^nN@oJ~^#X!{Z!f^*Rthdu(CjAY)5q}$Tp%Uv{&uW=IJ1Hg@H(Q}jLS9Ba z+@g0_lbqK?V|S9{fQan zRN3(Yw5p0fRACi}_KN;!Ru%aEXZOOVP*umK8=H_zLK(L#U3OM~yG*W3$rnHwhtv5< zM#c2vB#bswHnsE5Jtyveex|s>E)}4Po%>W-Gg~}kk+5#MDb=xA#PG4tzkESqhMTQD zFi0UH;sJI71XNfdxZCrR&FlPFeXd)-99`d_kLZt3%{5Vd~&?;eBo-5t%4)) ziO^kV)B&<@@?WrVA73lL;yHfNj|vmk&W0eoqdIG7Pn}93@SK9H6kyYiR5t5WcC#~rB zqR}*meps^Kh@Wd;UM{7Q!T(VMP~07tJ6L zek6+-Xr;5Fp z4(#+036hqq(4<^TW)N6$r|gn8+EC{m=;9WQ-ND;KcYJ0C?+Z(VT08kle$d*Ja*Xcn zce{B40%$bI=M50hY(hS-;276ZHJcF|=z(Njo6ofx$Eq!0M~A2_ zi1URbYu6s0sd1pFy*wLk<-hOchav44yN}P2T-uW3e%O1LgN6HkuzQ;3^y~ol!Ywpq z4)TVY1ZsMaFO~ab!c1mgZ+dc&dpg|BaIk|TT+~rzX>Tfbh%b~Kk)nJ|qs@n4$#H{P z9p>)bbEF{i90Nwuh{HUrbS=Cp4(8>Dc~gxho*ozQahg@;{zrJR1`gjnkMW;1VN~ik zU#yvB{_!{jZqmD|bm0VVq4A`klYBB8@>5x1`iT1lPU0gbQngb&g{|8KPB||YzU`;@ zXztfXbQ$a2gi4*}V>K;l!f8HS+H-@Ro#y)yNAUMEFy!7wwa@Z}jwj(AX!9RbTC;)PWMA?<$Jdpv-wz{3e5iAvX~U@Zd7ST&@YLmlOJD4ZoF7SdfgjQ_VF#I~ z9f6>jI6q+}egVt#Hw9nBmw40ui@Z4^Mz~yp0U}%wE^$xX@Z9MVzaX8yPSq~MS^{x1 zFY|hizRjUs$MNBTHAWcUD|~3+qZAkwzfO`hnNG<$6P)cb76a`1!V#mS94v3I@M`ji zUKq{&g>>u+kMyaIN`-F(ey}!Xb^Y)`s)C@uS9x)T;-+|BOv3Ui5tmZL1!)RZZH6hy z-(ZTKMB&$<_TE8luknC{;^21{I8<1#cf!@!+QzLN>_%t4)OFGZA)NP1+>DJ&C&RI8 zjSKGlSD)oYKd%?i_G_TDkHY1b-(vR>`yP|^md;$~A#A)sH6dHS;06!m2Vlkp5LYHs zl^d`~DLzQg4`8+s#`OkwuLvy`&W!6BFs#rAiszEA6QR~~kf4;KB{z8ctR-l(@U6I? zIcHp?UFN02bZpDG_a_zRpwctuh$r1t|gvne^YG znkaQ!#Yxd8Ygk|3SYJ1&uk(V0A_9f`EplwCmUb5J7?+xDojh=yQEFTBf&{if=|;Au zg)9+;E7+Qjv%Wgipq+p5KgyllFL3$DNL%c@XNcoI=_c>(H?M zOI3q_j|@RIwafo3P=@B-;xWvasIJ>JI)95-WNX^0BiTrwZgFo-26^2E+PzANw_!DX zlD6IEOX}8Jq4JM&lsPk1{?V9XR4U;_X_%7NA2E-fDc?dEgM(c?=!JtTq6GpN9szNg z?(onu9V5Z@3i-tr%D)5apvENMa!;lmB=CiHFnzoWhGrHuzsCnU_JMaz3c|WMp*X zN`VtXNGuTX?aKfehDXxN`@DhV@R+JU;Ax1Y`Tyv86ZjgB?|(e^$s(B%HzbjeAV?5| zAVDO^m4q9D*!OCM*wvD#Js}BhuZz}lT1#tbQCd}Pg=&c{u`61%YOC$JO-XGLl>Fc4 zd2T{K|L@Q1CC{CG=FFKhXU?2CXT@z0h%xW;JvT7FyuC$%0G-0@ffGTra4M~@*s2^CpfaSTf`F6g1LziXEzo``6Az&P(2 zumOwL)1=27HO{|_7_N%*twur3wY}NmY<2zB3e~r`26k6qpDrP>c^cP{tLibVt!**R z1oM^v<+-*62%-L?#(A@~m;tVl@fDrQYMq2sy9qO>F?lx6r}UW$67E5dRZxMW6k^A& z)t`pjp=I?G9kOFGb8;*G1z~a2gHTVWVi!L{dUQ-!`bF0Li^sB9-5q+aFI>|qXT5Ms zhgeIGwIG&BKoF=U9E}uuw1#^4+Cp44rO*$B5N1}ZM^6epVjAoP+kjs84(`t~9sH`X z{(Y_g2j6q&P$Ltlj?FiR2K?<2S+yGw3IdOFk4#3d&J~Oe4!{6Y!v*x&-yUuKFSoDg zl$e5B9EgT+0`Ss&JJ@`0(X+oj%-+#P7<`$En?Ie0z*G;S-uFC)7@}$CJ&%-tyDjxM zPoF|LGV@2x$*xm6G%N4o?kM~|-oF%k(!%>5Eqn~e`794hA<##8nGI^gFg$Y~x^F9} zRT0>Ry)>rCqhWae1&(Q$&;AUVAa`qv3B|;o=C2u)*?#d+`8*t=!$lrr<$=yX)P-P` z)s58VAILaf(Byx>XVf}IXa2#7KRB44|Kkx{^&aZreBox>w2I({a6oK;Z7Je`M|#a= z*PermWaA!|`6qnVdd+rCurz+-sJ8?~M~42iJ%DO~u@g;ctih)z7smAj+GR~?-xDCkhjjUg#|4kQ{;Y3!7d+Gt z#U8!DuvK~rRmQ$VPd!F@Pw?YwKz4zMH`CWZuHkU1a*2l@ZZSejJi;ovO)KZIw$ZQ> zRNkJpmq4Ia>j0f8!CHpZoM#?me3Rkp7aF&0XFM!^HgE)%K9u;vV~=~=4jQd{N#b9R-Wfl(Lx^3! zM=s}IdK303*i0h8J2<*z<}M)_LqL}zxJwAV(Iw9Bg8ZBzDY!LfV%9lwnx0Mlh%?+| zG8AuY49}R3e9d4C{a=p?8C@LNCUQ1-Ljf8$hA&OzLLJqRs1KkAC$B-W-Vew=BmV_{ z>WLAY2;PemdHQrMU|ZxZxQPl8CTAptTp8ou8vI59Zt4Ix^ji}&l*Xmm!KdEo#wcB@ymUWK z+@L42u5mb^*SJ|8;K!}pi_yBSHlxO`@TksAIj=nGxDQ4w=A$Ql{R#r0hJESWE9eBm z65%Uwxti**-<7I&{SZ(at-s zlBQ13z_jPo$&)8jjT2n|`hLHds3@$iOK*#C?BGfCQM&K8s-jg7I<{F zhtga`G7eftT*Op3tch_IKUdmO51Rp`0b16S-0E(^)nM?XpbFxc|M?xy*)Ea4-Wqbb zhH;Zy;C?_1Wy5Okc!)-L9c1$mX2ov@UGxwUur*Rqh{c8uv|5N-7~x(aI{V$-&Qvl$ zqv_fVduf2DKq^xSAHcG2av{{N_N}Hx6D~iB2w_PD%=Xbh}2dCG{sZyh2_=tjJ zZ{t#Jvj9g_7z)t<_6G(3J<+dU9SYHTB>9kliLDk9J)HS&3> zS{ZpD$Uy_PWCN@+3vbb>ee@)4k9|-5aInS;PB7cX@N+i)hfHJCQu>biptc%yEA3sc^^s+WbXdW(okqoMVz zj(AVgpGLtTAJMwn@`cY!3xC4HC1xJ5)7HRaJ-fRu%CE+e$yt+R&S#{6u%p;W^kf z*~#rSHL(eAAyx4pRkSq(lig3e<#ps)FwUOMWl7g+fV^VHQi`bb+Nc|RYaol^60Or zLV$S7xVc!*3p**u+kw&oL~opIj|GSToM>+ch=#_OPu|S(5!DP7{i+Zm_3HGJ;k9T% zps3X_)r^M`)v%Q;O|p)4XG1sHDPTqUY|!OD_1vMK1I5`YV;`5*qxaUOCVg8&EX;^} zTfd7qfH_j*Q+4SQjE&&*3umG%U1B~KH*}Xi=w zUwI2L`dgMeIBS)vUw%V>))Y;fG}7}Jb9!lKp0K)F__EP50O7&{)Z*c&WpAnP1ZrPP zG>oe|LR&wLuxd*~s-k8cudJ^3@f*x*Rn?&9@KF0F^N`biW$i6p??@|jgTAaKy49PC z{9R#B8fBWRIm5MDo2h?v*H$G?h|IXDVH6Z3MjC#lg+byoc4JywJgWTn+q|_L=GBL% zBn5a@(5w!q#;4S+4(KDC7Ss_da23+4u4qzy^}T1M&T;O#H=UGUq10ebDKR@os|Rye z*Amzw=}-tAPr4s|`d}_1$18p@cLAu4tv&s-o)4b`j?1;i01qG z=xQ}Lb>d4udt#XRh;N^YmGBEH_+zm8+t(bvty8nE9<&BYm|PZ!pZY2ZVg)S-u7awi8?#L$2iBD{J) z-2X#vJA*d15d94X`nQEhYwXln?*bo4Rb#SVQ7%_BEL!ivRs`7Bk_vB;5#qGsmPq3w zMMRGuuVQDix&$X$4%mlc9a&xXnQ@n>U3oclXP6E|a>aSw^osfNM)hu^SNsAMC#Bp= zJaF5Em%zXDAX50%y;YT`tw61Kg~{4XfAu`5OA;P0W=0zCb9@mH0LzPKpv zn`k+WJ2tqCwE3n|{Z^u_;{H9Qwi2V1`yJ`$Rw7h6)RA7a0=eu+eyzpf`jxQ)SsH_F zy+CzAz#8Ymit%wS=0*f#s@_I~;Qe}R z8_@x4DyxlXj63ojZLo^A(YZEaAcUe}(O{&)scSU0o6l)fw1^Mh-4=U8qhG-xeu0J@ zI~64P?f?ad@O{wuFX`uK(ZqNa8qzF6x$`y%_Gho?RB(m5#+9Wgz8NX@bS_S3f-BT^ zo6V7sW5Fr+B8yq*ogt2K0!@vq0yNU@wT)8AMDy)Q*Z@Z4D%^_V?+%+C;cr( z42^1yV&($O4Q3kR6@Q+$44$fJtr}g&R$Yv%Ax`Oml>IDDvR4uWKGgqMmA^ z4ShP88uh@3j8z)9Gny}fAL{hfWWw}~rfic)tv5f0w;Eh#CRyKh*EGtL!PBeO4tkYw z+`X$|e^9MV=ax2BGC{--*gnA0rj6~jN6MC zT`|MCFN3!Tf?u_So^%vpO;-g0Zx`}vN`W-VXI|C;L%gLS^Pd)@`c)rrhu;>&c`=K} ztmGQ%(FvQ=1)@$Odf+E59V%Kcp(JI@VK2YxrWk!1-sixx`Z|`dWGu67%}6hPQoy9p zp+7YpF^-M12PV4IcN!wh)*2>iY!)GPttX0kaolAOY#wO7)HjjS*%$|$nuBMp@r=^U zBG|Yff@{`H0U{DE^UPvH)e9{UX*p!fUWnVa{p`V`)VFB_4NVk&_3EKO_GM$veOzu^ zYxqwGfbkT^10mxsUkiee;3(5+O`@pPxi$y+K93puSpF5n8uQPmc|qOkF#durcnMUG zr%zfKU(YWQ5B+)&JcMfOen19%nx@oBkbTab1K+ema$%o7h?W z!9H{9C5gJQPSiO`)b|@ZmBEq}++bnlEwBnb7x<2TuAqfUA~3!+tlU5g>p?p5U>dUb z0!^&GRhnZ=Q0#R@UeMf|NZr>Mon$a4kFwTy$k}bKd-1W;<~wNLcImXPtLSR@ zn(lWM39cj3&ZsXD z&$@{SpSY&l%8XX~Mrtdwj`~#)nYxQ_YpZo(0-aCk*i^uWr}@ELh^C&xGI4*^;}H2K zgEh;eA;~yvKcO#^g{k8FTM`0rcr;Q!_oipbIMlivrs_R#Abu{XcMt47L{oc+piXoC zLPpy}L$f^1>~dQ0IQ0=8?=V>5ANz=!3PNGZdgVMd)7o}>WAqV^EzSYf>QBw}bv6P! zy6Qz&dWg3H;C4O5DMMwd*h`q9#MP%4$nki}>?PVMfqzh5FA-<3kV|iITe(?-3VUN` zg#W!hqIX~}grd}cd^%0#> z{6Qb=sQamAUoperLm&4QEtQw?bhfX!Xo#RM`iYM2VV{ELz>_9D?T7XiitaC3SAEup zPh)*_*#k?^Ecxo~K4j@H>U;cqh$*q}innM_e{s^#kLC{$1$Hu;XgbsouA0&QMigr@bAThOStD)M#6s}v? zd?d0msO!+o!J+|7p?x-3SOb4L1sRCVb0v{bP(WJ z%;HjvdCyTA@fMiATD0#i(H$FhrJv)geqj=Wmc21R@LN~U;i#))(PWuQft$qcSN4SiMkFG4PtT?##t

    {bb8TXLy=I)=F?7R5D_J2+64sxQB!Z-zlw(f>E#7sA&o z(dl8Lnq1vf3q$CzmmUs-JS~_;r-*^dZ7H5@PBg85gAkIh?{aSatpbG`Om>Ov8lqb4q zwodX_w_W<*q=&pq;%&FO^b%DXDcUtU?+Z$nR&77qxq=Pesvt+&ogF`3ia-bw@30n3 z!)i>R_eP3(kQ{w7QZ%m7=Rf7XL+Ew6e7ZXlgnui^QKF_y3Dl@jRrQAo6fsIPX!hVd zgXIp4{;Hp!hNGBFY^~`{vhEq+aU6(@EwW_~rewyPb{L2iN~N|@BFuXi+JIK@Tk5d@ ztwMh_h)#_Xqci4T=QAX$06UZmq4vfbh?BYqk|9(G)W+lPORPCK1G-8GrX^^q(@tDv zUV5zRtyk%-j=^Jp#0W@Uzzr_C#-dgHhIh5QL!hY8r3KW{kHPHRyd#j@FV*&N`hK)X z2%G8ySXn3Z*WZl1tIn&gb+WJeo2yo1*Tj^^IC+>4+;PQiU;QzVHlCy&V?ci<(V8)s zTU>*V5!FM!tESV$Z0>&rz3fbrEutn9gOp;FSK!U&opt8? z>COZ(2sb<(-WA`3&8`GC(30MON7)#B7WTa$HQNWP9zQsepSWw0XG&jD&_v;*_>Z8L z6U7Xr;uYFCQEX8>PtZH>2_Kp`NqEDORrVxNPYJ6pClS95ce7;V?!H7 zjVFU`?@s+E0}(FMyvd?Y)oDF-nFhC){Rv>opgxZ`yqM2!R5)2Q_gj+852o-K4V!t; z?h%~F=GpQX<;@j-)MbhYR;szuq$%LWA>ElG>O?egtq3+N&z#~i&usX)^g3Q7o3ZBy zsdktY;db7GT?oClcl6pu|ESmYWD1%+N%hje#2=-1(nK&Ay7_6?2QJZ`G>mP0Pr8u? zIQXrlr)i>_Qmug2r3+sgoGyHz+C3>9l9v(mX}XA0LJP<=3!o`Uhjgd|iK!w;sndfR zPt`%wi@z=Nb?_~o3c0*@K5d)|$oxa6rUG22sAMW6RvqZ=_prO!$?_f|i|M=f#1Lig zVZB`aX#o326g>?|Qz&(s7^Iv%q$geEq%WzEljc*^>G-TA6FxpB+}2^s%Dc6_fmY8H4V9n+R4@~y^A+8nDOv{p@=`kHWG?I@lwMD?+~21^@pj!!v9pkI zAdQ?Q>igF0q|ec0kip%f_33#|8)u2ezE|*olBe$&?w-q%_Ry_aqK)rjN79VfNxoyK z#caV2ipI|d|F$`iHqXY!^PJAi7S)yNhpBKjE?4R&QvEq%4vd9vnuGmt?_{`dDeTL}dw=zM`*cL~VB&?^_ zyx_m-L~Aq9_=--nCqo1TT#C~(O+;<>`nX0b$JBjPlp*|;Rficb{i${)PWik*?1*{ZS9RU;qrne~XFgP$swt&sN} zxeLp457Vch?{+P>=NjbRt*;uW3=Eqq;;L70l&MqvKP{MO|6Eb8dI5MR?!g(%jot%& z;yss8DW@-Rq~C$*=Krk96ly*HIvi0johgRfo!_ z^i38<@N0X$`IhAsI;hkrdVutR6^``B3~H_XyLx%$iax)cvqjB-ct@_G<*hinb$FYe zYjw7$2m>=)vawpO(wS@^2=4S4K`Q-&H>c&}gF+wBK-u%PUd)sue5?0ur+2Y#dF2iW zU7(3Mkm*jL4{|V)CvEj?UgbS?^dX(j=73;%NGiz@>jS(U`K~`G8<7J~u5Hm9Jvm<_ zHXezqe)C6W!;!90kJE2keY-q0YG>Ob1NPT}FP~{ksRIYTQpvOcV!RJ%@B&DTuF|Iq za3}c#onHWg_%^*<0GUuM)mSJ(0=8m+`PtbMm)*g{SwAjr`C}f5n(&-MkLzV56q0J)ZN((ub&9Zfo3rZ*$5M z=Ex4*aZ#U8|Mx+K)>7vCVosCEk5I)v7WJ8aiq(sEQKvuCig#6ihF2-n6VH4FM2fJ| zZ54HtI*%yXDt@ci>7mv<9)a{Sr(9)`!Fq;dQi%>$9}awale#a0;A|m{SR^JW9wX@2 zMWPq`$g_!HVcCdN0YB}SPyK9wdJ9@*gV3Up5m%n6>ls|L%Vh)h+jPmMZQIIXv9QgZ zB6z7!86U{Bkj)3E51#1FYPL4wZ*a$rIkS)gvrsVVP^1f?@2eI%yjaB5ye%1DSxC&w zwirWCvcPaMu2>7ys2mDef>ZHDn!f~~f_BOh(W-INSe5YTk)lv@8H!VzWHFw=@3(CQ@xf-XDniO3Qn>F&}^p!9F$WLtF(p zk>@h8Qt`;l{d}1ipctA^=?buvv2@L+u^}(GG z3xj-kuq@Npqv3U)a9wVrJQAIiKNYI@k(k7i9M*;@S{AkF>Vtx0?x3HGb>;wqOG^wh^ zCs>{S*E4o+>KMK;=bbkbfBY4|c_T3%iCG6@%_$F6?A={giBxz$`)(D`1)R+B)gm8n zjXqd|g?Ey^Sp)h04m!04BJGD%xJIl~YX3sEwW1{yBoD6@ui#(o&?n*!I=S^z5$e3> z)-$TSP6X1!Peq_|^$dBf6D<^vNJ>~Iu5|5og)ukL^0<%XSLivO(1yWC)Z?a(L^}XV z^)nokIAtRO`&oXkehATtexuHBu9$^$?RSpeT@TKWX#RRou{7GeUc@LKFX;Aq(L|}b zntV5i{XuIk8=b68tu=Y}7J;W#H{Z}38p*9bKS_@_KrV2es&5pLf%j6LmpYV9?l9rF zf-syz^M0^_#%{!ghyQt6xlwF0Y|HKN8NdT}df4aU{W?M8_}t+VY;~P+NuQg=+-u8K zZEn-m>&K|lCgJB>5T+d@(t7e%pgAimfKEZ1O@Nf!1nR#@Osn!Y^f?QIUSGzkGwIJw zVu_)UCT|vtT1~#7*Z&reW$qvPSl9rN`b&Whw37(L*&^z_ae%58Mv+?}&~kUDzFVN_ z5jln|Tf{_=%ja9fm#|Q_`3td45pL9bE7m#OXKob@n;$)Ibb`pG!RoAGrJG+e97t(F0aUDT0E*;@qLz0J6~3vmhMSre+J$mF+k2t-XdhA!deO9hj19Q)A7v~Lz z&vHNC0mdB?rwiX;Z}g&<{7IzXo!AF(hq4n4-dg%+r^ejZ{#Nv;kblhRqyhrdzZEHp z)Aw}sTj7UC>&4%St`#2~)HG4^zy~g-?%#>+m7At;qiI8d4zM+#ULQ@Bz6XqOx%<8N z90cm>_hOXyrcwH|dZuQXBect}!!%$Q=oqy0c0v2ZP7%4#K6#&}6aaXN%h0g33v!R02HBW3cgyfdw;j~?8iua4su2J{X zS(62}OX?p4ct%s&LD2sBlzR{~t0Ub#2x?eVoiYxIB4yt@H1V()0Ta#_4ujFhP4y9+ zx?512BjSCWJB}Oy+rOF~9)VsH#EtplV{|;A0Q295rWAa1_cn#{rl; z3Og=pS1?V%;pJmj>T_H~!o#igxUfRo*zbgx5;yGZvr_vUP4WYgtlEo%{Di1k>0Z7R zQ9E$NTZqtvD3FXc;|LaDm*s$@<%CGAbs^|QX{>SAk=V?acpZ{eBGM}8MwAahr0CI; zB2NNOC(*2vA_kJvJtwgnjid`Fq4m;@jHiUJPi!#=J%)it+!zRN0QT>x^(pW-1vKsy zfR20LQzDTS#qOTM00z>O)1tf5{A)UV8erZ|-OoV&x|Nol5$_~6h$}9&&j9jc4}omv zRH$^?@@Xwf$Li_X^sCi=qpT zds3_GF$Bn=<~7cOi5XHKl}`OnrE!|JS7cp$Oh2-OPVG$}pTjkT8{Itz z-Gv?0_PnSGFBF5%i!Od4b%0XVoFLFUbJjF}Cs=I+vOrz-Jl5J#dU+lT@LhWA7m;c_ zS`RD@E0DlPkQ(}lAZji=2egnyi&Ld;TY)ORWV33io`}_ojp%T@T%;_ISSO<4`o;nwK2>G?;!wHZE-k1FWqbqHI0 zeaYj7Xk2TxKk}Y#_&RTvo;QW_uDVaXZ;0B-xh(-JXpvyWFVBNaMtfUg)s6KzZcSDq7u!=csn zGS&H0M1;=pL%s7+ue~)^3K|;C5eXcDi%ktST6L!><4=t{Uh$_G56OV@O<}6As4DV4 z_oXg3L6N4?=9?m>{yksB-SgF~$a9C#+w(m%$b5^B`d8u0(t-phNrsJXKJ{XGwS2`T zN>Kt?SLs=2;G>NXvhl5j6n{&6TKk?4vi%L~!mrow`DDFfeAK`G%5}LdJekF)az{*U z@Jm=R-eLCghkqgX#474yi-@uLB(opqACSVrLY7tRi=-WQFjHHK=)xVy(5L+bYzjtZ0E4NOEUE$fl` z7a-r2yb48V0#!n{`?YdR+`P`OCvFIStIKae1fO+yls0*DQtc1Enw)AvQ6+FuFO?pj-idPfb8Gw>;g`gKa`DFf;4BH;mcZ%mP>D~lR(n^2-u zbLgWYQB!FdO1q1MRf%dy3IB*%p1WOHn-z9uQT1|~^bfW((1U+Oy~Nh-$={+o}@u&sw(6KCoP^0~%rhiaD2)Jv-~PQc1Cr3Y1jiCwkM&uy#{LKmP{76!dOM3z#eDJ^;=QVe1A&m&w%xlrO`5toq%L!jE$iuPK&qWY2g1caDgqlFWGtF10O z*0Y`8@049n!}Oqa+C+5*YJn!a&Gm^3s#uLG9JIjqN~|{apYTy1<1wy=Rd%)~tPx+5 zPk`ftsmBwrRRihJ6Wk~DqpHQ?I8JXjibarlbt8?*G_xEI55hW5%$nBPkhV~(9}VtM zSk+?BHYid7(yQBPtlU+ zN7$vF;#@kOc9e*KdalT@$F=dB>$@;U%X|VKy!piT_VNNfC=nBz?EUu{MEMniyW&-G zHa|T|v`(L>evVjs3yo?em_gN(n-yD=BhAH53+wB>~u(6~KvInXP~0^fl)*PmXpJksEs+`-t|u5dT&Zi9?;yZID_l-x%Knah0oHfPzK zj{wecGVra3i+qN0b#ayT43Z|h%7##JTkDE6P);}5g*gm2`P`77+pmILYA~eds_xRP z)LVBSm4?Gg1HZn54xaDAh8iG7;Zp{Pj}B8`DeD@h2;4S+$SmE|e zBS%J9mhrM&g~5afb*>hdF%jq7WXt_jOTP$pLaxzAUN9*2J#+8+$_ol;={|o<&Mr?< z{pC2t|6l4`P4;DN+G=tk+?TYhF1-!P`Tf)-KsJD?YFdCChGWXb09oJd+!b{6G`R%I zQNF|ZcM8OCI72=ODSO_3BHAs-TmIh1j%F{V06O=VtrMQr&No zoiC!bGX-zOUNpY8j913~LN$YBEjm|Q7UG@PzB;l;bbYs7AY-+D(?cxA6A6LI=DSx>%;PfUGzO7T8TvVm;gZP{7$q<++E zDm>Fu8#Is%f*9D|)2MLaYHSf2)lT93L2u;mqUUeK`EjmmAa^RIUr_r{*~O#hLR1Cd zbf#sYvbI|c;HcK6A3|ljYRk{!Zi?SSz|L1FvA~%Dsf89j34Z3w4HMM|aC_5PAGUZlVQgD2;bF6^@^`WM6 zbfvquo&aHzpxp(739u*7RL;c;a1EF3+-%2C!Foyzm%#?uT@05UaPaviT>4iz^cGl| znXzWeOf!tKRaU(>(&cd3l_kZ^oZEYsstM=m1 z|DBA(O> z#9Py0`~im-DMNh*+stTAgB+Se9Pzg{Yt$}U_JfFKWwfjXLwLLRQ=cwG%ihqdX%r)?VfqtdWcT3wvf7g@ zfxNjl{z)SbHJ@n>y~1XwM$+yWStI%h`rA-=8NTS4pFV|nCLL3jFYXvQU4VugKFh}k2XIV^199K541KHqiogS(RP5#=KC?Y2Mvj6Cz|>`lxa=m zSVU?>MqRrQ+P`wK^71>n(Fs_QOD)ZExaZ`rbVVtDXvcJf>aDD&oXMp#W?8@X?>kV> zSgju4g1@;ip|V}Yx{T=}j^=$cXSh2Vv#khmpL-XMWoku1eWj_}*ezHb$by9QDsbZ6 zJ3B9ZYreBV(`y+7<62rJcrTG^;d%^C>Em>p)jE%0wswBoY{&yThP;B^e_9gcQLW!{ z7$ZS-+gZA3UjTNwtVcjvoM1TZLyRQGkTxG9$$@@Vsl5=3m%Ew1xLICiis1p8>uBGP z$k$J7sHmH4ri^<@b-K&<+;X=9)CKfucbTBLkEA=@!KD36ZIfj`-ygpK$l=b**1O6p z$RdonK9%>>p)ZnwA$U8OESoF!wo`*1vIYd69ec>zK_OdES8kd3!0VO+Ie;jIH-TPt zs7p^-+pv_z_XN@2N*j9uHG5s96Fub|NYgv_k~5+%LEeK+IEH0E{4g7aDLNVKg*Z8< zE(KzY--H(O(1JYrBvNO3wwh%ROx#}V}ac1 zEkl$^C&;sp^b5H(7v|sewz4BxRb$TU^FG@0{2Xl^ro=vSRP4-9BOINK?aT7s4*S=D zA1M79KU?9^XRy9RXMcv=)!z`CjkvBMYyv)b@A06IoTx;vqm;g~9j<#e^p!0t_dBZ1 z?;f6CmL3z`=_|WYed<$+F;9iE0L&$oVzUVLC$Am=;kjE5bODY{8H`UzsDT?B#udiN^nq^>~QE&=A z@ZouApo~3}~%jUH%Z!TeP zfA()##VO^98L!6LW3clRFl2S#X1YEagkdvP9V4UtN|&Hfr5cucUBDmf@jge~r%_|T z!Q~T;kpta^a?~YyI!4w64XQd;4s*M-7*W5{oU!2S@sJcBr9~cH9xH1q-g)$5tc=Ga zq}XvXq~_-R<y$N49#Mun=XM@1oehwwb(qmj8xpiN zp&Jtb8dDPrdlysC$3O$#m1p~Xc(#&LAE0W|X;Ee@$V;s;jMaA_QNxn}?&2Xh7+G7% zs5uzXEtzif(VJg}fvB%=F~kIPJ_5QG`oC%JL>ZXu%qAK68~{H)N&02H%e*f3!%x@fSJr<5SIVrt4|1esInvN2;892)MC(~B z*VruSa7Qxpy>BWABst=jyiui>qsnkcT7xM_%t{C{px&^X0ITMn56Bwc4(A`spBQn2 z+aP~uY0+dEU~)w)qVAkP)E7fFm8_hF*yXqep4;-`f3$rDv(q+Tm(!J;hM>eAl)w&= zPU>V?v-4k4*AwW5yH@pCWqsyrb0F!ZKJz{Z>`&$?Z1WCJ7C+!KX1~HghackoAY%|@H+Cysr z{uyQNU0_a z)MvqavWC)nEp2*Fc2Im8(O>V${e~jiI!#7b8TlQKArN{rJvya68#5_*MNg;6VV*Zv zm0(HM;O?3w`$XI}KyAh|T4Bly6QN_UZK(Gu=)+F{^Qgu? z(udy~fo8?fJ{WqE+Rw(ZcsuQ%E#FG)-WSqT-7Y{k(Kl_r8=mM-FKi#${l5-o$G^Mk|xxmkAQ zjV$dGvZ#YG!^u7pCdnMk z4m#rN=s*oe2SOYj2;&YQJ+guRZ5yuD;R_qMXt|dj>Dx$)tP!CPs)pX7kVphAu1oOO z7#h}E`$U?wPg}3f+Sj+2_Ng)0L?6zD)OhSmIy6_dS7tmTmw7T&=@dsz=gAOb|CJ?} zRIFB$B~R_Ll2Yb@B`>Az^JG)8q&n04yXu1Kba$StZFK1cMgfoaig>f@S3TD+OWF*| zv}d#_TP{+jlu$&DjDVG!(K)ic$6-IcFwAh}$RRCL+oQ*dy&qJ19iV~gSvxH*4sp$n z@%u`=kYfFp=8mEb{V0CE3<b;|_Op z#GZ{nqHR`SWi`BW?puU&oHEiv^pQNR&_WvdvHVck_yfK8ShiDAexT@8(x!a2f{w3( zWG`+H4O$I`*Lx3HSIY?HR3$pF8mE^mG##7(o7Bh_bU0Luw*+7fmm(4Raa=UoV3ESfCfCliKWJl;yXDtk-zlj~$?b zia1)?QYEcw@!<@ww943kUR4C`kBSS2PdW6}>iO_qC8q@IoS<^s$1fl0Q}sD&RFkji zQ}q!7iBMq8D)3Na;+UA}MlmzF*#am0MRMODnB{{>m8o9p!mKCA)6pw2rDG68eihuE zOtjA`WyXxg@S0Up0XL#3V=6uZ5sZpoUGb_5fXuOiuiDQ*RL^$cRx}9aEJmy*qr}a( zlgZjCIIF~9oS)0^RPnaEQ?R`P62O?_HrUIY6UC)r}X@H`WqY{$ z0`F94r2&g&&5RHho3Xko)L>s>omNZ&Q>7MVK0yzm@T!?KNSmTrd)LR7o^SsETia3= zjYD@dI|S{S@;f#$VBYKj8W1zlgj41mhPMy0CRyjWYuZ8jJiyAjF=rSus$X1t-VhgM zTA5flUihBx8DoO&O%ap2l%ck073Rxc2bH8QrG-nd%NNh39ZRH7t8qw3u)d4y;zDiN z;TDEh8?&X6ct8oJ0ggvB>q(q5(b@`ot-3msS}c)uGe#kE8M?ec^6N`3gukxK# zrzvn&iJYkSTB5~GeS4I)+}ur?!+`8>w0hk%w%QfHjl2A_ZW=RRR5UJFi6FKKNR1ow zBCK#wTSnO#hz8giXBd7qMIAEcuy>Wr7s`8@?s*CVrYx`**<-ZQT(H(-{eYmkS=<1O zfRzKtj(NY2)E$1zgstxO$56PL<{83)#YNnJJ*hTPeaBn#g1zu{{2Qa^l+ zQu7@NU%ipAo)dm#Y(PhrYYB7EPO-WW355$dcFr5IlR5iYp7+;t1C;1v%3%LPco$(g z5AL^r)+;3~+H7r(bCMwtQv2MFx?2brCB`K!Rks))<7&*|-3zO!zvFO^C6kR9UXU}~ z)q+7xUcjlxV#SqIGA_8UrL;h$Uj|601k3F=>a7w3ntcjb5#yS+-IR69IX#{NKa_2% zHu)Au0u96YeC0T-7E#`(GO(s9!Q<#mpH3Pwr!{p-pPo6b36{cUTK$2nUF`}Q#TVB%ehX-*?R#~6} z=(%7YLQC57X1g!qfT^@-nXJ|N^9lTVG+JAK@Vm%FNg0lp`h1bNhZm*gAfV)~j@K^H zXETqo{E&UmOEQLg_|oHL(pPaVCb?YJ_ZE9AIb~f3FC2032lNdtC0A0ya+#>K8%9f) z^GTqXb}W~{Aq%w;!6ysEKzLoPBa40VHcaeNjF>m`+cW9ea@o?W>PJ`w>Qt-(ff|jq zsA!oCpn)sETWtM_vR6Qq-r{RIu|hTtJ@+>6+=tm>$|_T43d*HTntF1?$x1)=Jd8E1gI0Y}~~ikCE_=idLBMgn6YOOG@ok5!8{5qmH77Z13s6 z{oeTneYq0E&U41A(!v#QtRr@;Qs#2Z-|BndPjGnW(rc@~s7$8d0i)3`ywj)oqCS7e ziea47E$n2rZGWQ@-q=rf7>xM@A;)rAa?w&TeiZP?A!B&}FF46miLX&ZG-E1HK=mHbOfN;A9EHsJK(y5?8f`HAeOEc=Dz zr!ui}|E)UK7cMi~W|XJ{UeSn8l(rpAZ!q36)w4rRb%~) zp^$&5NiQHnnHAjBDQyJvY~_|C{MDVGbJYP@1o}cxkDzaMc=*SqOU+Sy21Y$9~;nw+HVPMUMI)bvNH7?U0N^Gl;pG2ZG()ePzzF5HRxShyg>#i&YNl5 z2HB+Ezlbb=t$wYN*6LxbVEbilO=lts^tZ@e-T$0QH^{p3_eCsMfMv9I=2F;385(j2 zrvk^iR#zdB$%0yYE^wVUKeKI4i5mBuW^R-%Am{#iqio`PMuQJV2m1(x@Jc=i7CV#JrQ^T1X?TBFRFL7?&d zkYKj<0?ay;V6!t!eLbj{{}~jdR<8%OzWDz=D1DsqPW0|(X;Mx$q@A1Penmc|DO+SC z<;Y4}w?(c~VnV6I7jlI1{aE_q3)vnzBla(#Gm=4XZI!{w?_(%?D+Kk89?`d3ab5S4 zu5Xo9mDDj*vQ^gf>1sJ*>TSZaGKcYee>H6_HQWaN)ok0AhsotV7w5bA(1A5p&f*vd zvSaZjFPpWXv+mEDN3C`Y55$L5I99AkYTN|l01q*W%Akx03PF~G)$r%qh_=Nf$7sKYV z8!eT;L&fn%_voW7csTsA57(Ll&Z{jTY0k;ZNL$V@*I{jN%z!29C@N9s4Fu>d+RSU^ zbo!TQ>uZ2TAr1T!Z!-ISIIHAekm17t84`2TrhT8rH5jmZtEdbbC4V{Sl~2K)p5)|A;U z*qCEOK4yV`q8(pBDAx*0&(RYd1GtNP*gArGFoVe^%f&>SOM7#4oO$vr#vJCPSy$b@ zk^6xuGCRk`<~u<>DK6Py=L-f0o3Dd-02)ZLzUOWqfgc)KDVxQLMJ1&fs7;$fOy_qt zprYCRRjD0n2@DebHQ=2P@aOBfH_kI-q1eUkcSyyd(J(XF9)x(S_B;r@Gxl;LP|w=S z2ZN}nnS+nFq&UJ-d$sWfZ^Ar&BK7)O&VX3$^w+pCKfRJ-cSt|w^IU@@OJyIfeKe9wrfljg^E9KrRNqOKaV*I;l^pwWtb1#aIxecc;%LL$6$*nHv9urFdGgq z%*;{GjoDvg^u}Gy&6a;m#V+CQ#_UyyFk4QW58RJQ+i%i1j>5C(8$=@i>E1bXEvAVv z`zgL!&k~~U8nfh%}X zkB87TWjPnOz z3Sb|ZF;BZpQgfdGp;TQdC&#iE3GM@5Ke(%}G`lDG6(9A;n6(=P z5)Efep;zs#pN}lt1JU0ta8zXv#UOcETaKHZXG6q@TDXd&A-evxyV=myzi>AiOz<~l z-3Mt(c8orPmkm0}9gKB!a6TGN1OnS5>3XiLnxQQ%#~=b6d3qv`9adBHy%^8|&*_FP zGK2u;lc*LADX2!VcSJUQ1{jLQ`K)K`0Fz_!Ugcgm7VmfSbuj&-nR7|-Pt33lRbF>^ zZFz@v%Yes`4K2AOTCUllw&Z9CK-2&*>kc+{K*GLO2av;jX_1JH))!1()?KOtM5qvfYZlui6M@d z437B%2rJWoJR#<$Y#SKnma#NfC1}6Y8=OE_5jlQ>I^uvF0QFxo~Cm@ z%H|cCO$Ar!+=t{(GP&;hU3jVfrDM@^uIqSxsmZf+8Jzv+g*4|US+&+~EnfG$`sG3} zpp!N3H4|`iQU@)fZ-2t|pYJ)c{{#iMM~^9BpX{piZbxJG$&JdV?Z~(v@w3|!UO7c7 zsmEyAeu(S7Tu2-C%bvlP5_QR>7l;u{wOhj;n8varz)%cQSGFbpJeg3ZXaUq86SUiw z1#mNf)FSmV;ut%C>*|>t%E*(wD^33yM-s?5OpvLLUqCnVWR$YA4+S2O-INb^(zpY% zR`nZ4^*rkC`4~?HpaIhz*xP?apC7=v_+~Ws+K>J`Agd_{+R)1bxY0b6PXPyIq~AE0 z357$I*S&O_~j4Ai=`|tf-xWL0&0(M=&OUWmooSWDTicul zYL&`?N{5jbF8P=MW%K;P_InNspCOhWgh4UP2SS&o4CdYDt~?^6y;`mSwS%usSQr4c zsr!)rIfAD^tCP?(O{UA)1la$2YRvME^ihq zxk&Z$asB+!F-pys$%$)@m9GrqIRHa0~I-NdKIMZ%{q*IivS&HMrx8^7s=~TL4nKR7f!$d2K17UronDjj#2vGmBSzs*?=+* z+m#n0MR(p%kONFfO1*{^MAkK(()>I2IN;Zy7$97UKdw?dM zg+fbXPl}rAv4X8Dz^;l~z*s~kXT-(^{#Q7(u7GLh!%k;*8;wTt`s z>Hxzg=_GSca0EAvb1R*bwm1Q9FsKj5DFkI^nw`rpE56!+ui`2{!{0V(iTKQ#1Vs4I zVKP#Ae)xdBcU8R<+HdE^=F$p-Sza!i%UtlGMo;bVSH)!hGn1@u-;~qhANAqhP1mz7 zG9fsb{~5slOkoScm2c_#kATtPdq72my5=&cDd;UH>?f$ z@S|$^=bluwF0|I;=4VG^2wbVk|J!9%YjZ5`;)n7g8yK@Dm-E+jKmk+t)dj0|8gs)$K3_yGd09V>}40FdatW@J8j8?nx9?WIb2}1$gh|BX@^*0pOz#v)JT-%%jCWvFzRyn1tZe z#;7BPIdfHHIbUhhIJV6Zp0ZbYjLDVtqYh8(#9u~QRrNUtnWmoh=DlJb?4W8JRJy?* zMPO!KVYPY#hp#jqZ~mV^t*)=ENPYZ);;A5Ks(N1OdX{GXtdB&9_dP%B>v)~p&$=nV z|9{3{txYd})_2OCdJ}u}3$>wGC^RvqlQx<{2eYec&BvR6siLu{yJ}Y8Q}n_Q;8a~P z;AH*?6g5a&K31ZtKmnkP*2w_=f4)z>YK5Edhe1c2MizFxSKTBugKu1t5X_Nppt4>Y zcAUm2{+|`McBHCT^$k05u$BL`3R2diVrfE?vBv|Is2KL+!e0!((7nU4qxgl2edzeKrw5{p}( z%71}LvFrwUUel*J4NrHnVZ*BZFEsC(zLsCL!PuU#rdKc~*0z@bTh)Z>5J4xd>BrZy zZN!wYL?w$x6C6^82Xg^jxG_vj%0Wq`e%JMlsx_&ldVEw=EK#Zl)5`0(x_y^^xULVX zRuc5TuMgFt$JZgbj%r15h_-+M48Ctj~Q>Z9at0}#GP+iu7|}eXgWLw96ef_v&O5j{;Ggsa^h z?m+TgeSmWB=!2cQexi+I{3kq)&AKDh|2KWZ-1viVBv`Uo#V|(FCj7i}v1-szDPEH4 z_tMW6_e?Uq?QSd@90_MNue@9@_+Ku;!k9CKYRokj9V*5nxHr}62;ITP9PBVST_zMI z*xIB(n}pYer?X?ATf%A5EV(I8xjk-n9xsnb+4W54;ewhBQ;0W~r~ox7;I2Nf-;RMQ zCPNo-o1@ZN+u-cb*3jJE&uH$A&3F4y0IKuJP*gP*|33ohF`GX#8{ss2%uD^w?!$LQ zQ=u|+A2yJd-_-|skAusE=@Me_FHz&YSFl1#e+yl{tFLG8&>7p(u@Twc15VdUp;q_w zzSRZ`L%|WI+2*A@r3BM88hH;(bejtA!LQ_58oj-zPq9Ckf^QEspw7R;$7b$sTK~Jg zZKDa0!>w*WL=_JKMUi0U_B1n`3L=coFUuKs81_{4BJcaS?-<;XTHZ&zlQ$d^A54xi zJBG&I*Zb;!t}N&uLrd@L^9Qv%sZ%%bIg=o@)|3OU@`0)44jesO-OQjyXygzo&IubKP7 zF>Ch8VzdvW2~9BUS=|SlGr_zy89!{!2fC=^G87y|r8xFDE!fV7Z6$2M+CRc~!B{lT zhtwH^7G?|1W)9-aj}$Pvc8-N52H!!zyEfy&_(kGDKoTU@@y~`Tk&0R~#E1 zfhf2~<<>2!$n9cjP4Eu%gb0E&Xs7w7IW(;K&%2iF#sNj zpBhjZ5L7)Xls)5kWyhcxGNePC?zrk%ry6|!&-!!K`tpB2s6{ocdf)m}{z5E+iaU}B za#L(5_!UE85HnC<@eTyR3{@}ZBfq6p?@`|m%Hey4g!%owtc0q}SJ#4KH*b1hUKvBd z8x(3STA$JmtNtVDjsvy%Qy(j>a-h6F^?`mapR(tkq0kQ-OR2F^^MFgoLMRjF(tgyC zy8KDE|I{}Kd~E_1OEQeR3YjB%znMvz+n@OVOJqHFv0ZDXdZqd%E(a&R0-*@K14xG+ zQMOH_aiw~r$DRc2pnSfWs7dUc33%8J`mq$Zg*VTmp?|^EvYj1G`3s(uA$GK!f9>pO z?_UUW6F-n{{-s~tp!vs|!yR9nR}!IUXZO4z;7*n0;H>zeJ06mXW;rSI9?-WBaZmln zzBJ*H{tL-}E4e<_-<4KOqZg0$W2GCtY4{Ta9{8p=Eq?;f!g0On!V@@#x9d%>p5V&P zi%k^ux4yl!zZcEh@G`^qtc~omPcQuk9WT{n>b3w^Y7qz4Un0q3gD6KVAexJeCJPv>6f!$S{7I@#cwPu*h9dcK_> z41*3UBLiMw9UnhTGAAPGxJ&euND6t0TTQ=wOTAwL6!Rl#(o21E=A-%Sy7?l`^fRx3 zx;AACwV?`Ls1DP#wSmZPb107oA9UHD^{&~02kpE{F7o#< zlI<(~yT)7QG6unM^zZ_0gnW)FZd0@o^5K`L`yG1-QKpesHeBgS3b1xJps) z^)apMPt)Veg5de+-E3PI?J)31@JCSI5X)WZ%kgQF3gLNjm)jpOLud)#>Rn?-HQ^*yE9yJ$tZK37Wc{M1MI zN=@5*+Cq@epf9kN=KaBW+;&$yV4_g#D($}bR1p`YDl_N@od}f>W&6HPgiFHq&01;B3erq(&04XTLT=X*<~&@NEXM`EOe(b% z4W(L{$3fVo1Z-Id8 z-?EJI?8RIuZ4x;+i0#s|O!~n=td#bQr9O_Lad^liXQ;?CbiAw{yp1AeXo#_v0bP); zEh}G@O-g;IWS_Ns?AsAICvE5DXvd^i==%$nd@aVX~D6QGPoHhr!a z-g?hz>cldXaU-Z$FFd85r|G(0Yz+;asNocEXeftVlqOTbRN@aF(Td8#S;J|Y5CPJl zQZuXzLqI@ESfF#=&;rv3sN{EpQg&{hyC? z1P285^@l3al~tNnB_D%m;~(q;{<_BccbXv$2cV1f8a6i!=eDQQDaRmoN#>DM&qa)B zkmB!Tlb-_BfoW!}bryK6ILAxbJwd%}tB=GT3}#HGU>&&NO*$QO5p4t0@QM1OR>h0^ ze!v%xiicMtD8yCFmgIEW;3{fV`x-ADFBl4jVF299Uul*bt|DLO)TlRXHLTS7h|;Tz zwvFt^VExR2ysuC3@>QRpE#FywNE@gvA9EZ@ssAXw4%4;j!q3mx6g-w$A9ff?QHq+{ z8&fZ`Ob7+PvQTGnaT5_bQ92(hiUkf=ew$Az?&5xfS);h8tnftcs{;-|j^3pdfK5s^ z`vvoA`BWC3??;0@grBtiAkFj;{iJ4N>AHs)Eu9`?N%RzsI%!Kfb@39h(m!44V=rvG zVTJUg7q)L?A-(hxH6+hM^7Iz%#kqpYQ5-9v(cYq|w6K7_^cDl9Mg>&vE&L^y0t)aE zUee2aiu3`3T+OFGK4@uEKF#qFGo*lP%Y3l|KmLtc`-%i9`8S&5D?0nVRc~EEd1iz* zjFoExROQ;tKqcZAdgv$TDC*fSK(Icg{0Y^lDMG3jbZ7Mt#&2D!>JMxu zcBeiyg++=^AlD$#U%C@d&dZY@za@YUnzprEgf=3VMg zlZ&Dkp@QiMY(S{x^a*9x63O1pP^Qd7RaNg|#Y@u>yk57IuGbQS>Kyc98Eg!I2+`d^ zt!70{wVL%OU@n(Gc|?PP#VVg|{%QcIj(j7BZTv6^CInYirXq{GM{UtrDtk!jwZ*8A zJAE~JkPQf`8F{Lr zd{Dwl=|zYLl59JXcOB8&zBS5~Z~vspbwsB0$4FA@h;->z4s{I`N2NX!$Ri98bN-WJ z!$boq9_te(e0<^usFZ84@>zS8B=>^%D4WVkH__TK(a3PSCk702&Qs7Ib;T@zo^DLA#BydYt4Gd=i2CSGLXgO}oK|Kh%B9u+NDX5`n zpu0s~8j3J!=Qoz=4MmPl+H{|uHo~zq%8S;8i>MY2y+Hh-X)gV|(kNuMJ=lpynA2Rj z*h5{3XeBgOU5TbJ_az~t&eV0}9)V4Mz>~U00F^%Xu&jv?E;^~@UE0-H%#yzAK~0;8 zJTYaoMot2iaigiYiD((Mrz5U@o9h;y&KbqW#?h{ju%OOFcbyYVNMutjny0T8v`I>R ziVoG{{%fd7Q}L0s=r$c{D#C*gchG>ij&a~Z7j>A~N}bl~Ff*7Z^Zk;lHxrGdGu0`f znTT;IF*@56fM&9oY__d|5Twn(aojDT{mn$n`rjv^JuG7+)0)$rwe?{6Q1NS}k@Nw0 z;C97o3TiIeO0P;RY0X7bop|Tqq}@(!R-p0nx24c0HN~|J5W;XVv zCN0G(`&qUiE#J(bYc0hH*S2`jT7VuOzWp;Somz?ZI;rEXmE_E zC$0IE7Q~1s>6a@A2PuX~%`Q<`tjKNb5W}CM|1&%(k3{WLzPzD~3fESVH;e8jsEIN4 znX>Cs%Z*r357WM2v2QCz>!gf2G%;R`m0ViU-FU28Km>J35T2enEfItT`T-YQqf@<7 zB8to1pG=}z31EHOw4`kbB2j8TiOLdizC52qEfYn15A%=D%kv|vBE=>K59Oojak=}U z9HK-qL_V8>cMR zo?!ymJ#ybsu%3_$WCR{=FT4WM;l5XC!0e^o24tTTqnVX_z8O@-C`L#`*aB$3#pN^@=J zrSl3`YpqTBPhPVTb+jqp!h@O}s7%cVyJZ30NfKQp^G<5g0X+WZg*3E-m?+JEOIJIH zw!Q_JmKv45Vh-xKczfOah?;a1>CHTvqDKIE4R=zzrPkv+2J)2JT8~fgpqhs(GjRB|pnMwBT?~`#M$v`tn6&>VG_;2ZYaCLKC!Nz&iHhKla+)ZM{TR+U zb@@~+V4e+PmcM#9^TE945bf_Fq6Yj>w_-bAAMhCe>^?xqB>)?+KB2NEj{T-zH(Sk;`j^ z(b=9N+g@n}fH*9ocD+Q`kafdZZF3Ss&4@eX1XTo&{?2E}H4mn13aB5t95sdx^b);7 zqV_*Wz#a_xP1^gOc0uHo- zL=>R~#`y z_Lxd7q0-)%-J~1j&_^_pW)G+6KElhhGbW^YQkl+SE?VVki)loca}FRa{;T2VE41y&aAQ;Qf>mmR#bYM8OUYqD7k<%cn2q_ z@OB?XuKh$e$-0+D^aE*IKaJ-01H03#Hf`^R{h8!KSNe(C(IaZ1M?=9)bgRZBEO#$P ziMlq7d)m$916-79`$xLEM;EekI@#Q;B%NCH7eO9J_dREvEn#*VK8z|JW!9q1{y3=9 zYSH}uBCvM0fg4TKTqf%BvbaZ}QELtS#ad(d6LvMwPyI!U#83#`mGql$%OTZ98a_5h zm*J-<3tRzbzpkPTff$b=!aTwtOLf11*Q{1Enrwecqoe^MGB*`n#IcJH_9ApgY#=tx z2#z&1o4_q14fvbAz(!jKRKo#i-(XMxmX5b&YRUCJFKnpUrI7YL_@ zi$7P&Y7Av>A38Be)TrGaXDz!l7GA(Kt(=3S!e+*J8r}70AZT_UavCfKNyp$ZJXl0~ z7PismjoT#1E`kFFLpyBaOa}*xTAsBKoDR)@(i;K0dFVizP^EbrdNo+YNCkH&YKUl( zvJDAMH5|zPQZ*Da^}D$fWFS?&fm&ER%hPDysQ}=xvm9r@GY9&57ZVDt7{Ur& zecCrfw5ro*2NRw>0le@KZJ6+kVwe^OYXJV6kGbkD4mM?%_|L4--D#9r0r=C+Lw9JlQiLJf3Y!^DE0z5 zrwebNo@ZZ`Gq1lJQ)d@FP?I&+@&49kic1$^)jqZbva_d)H}nkHlx?fh416bfP9aJc z1Ejti=|#F2jvQV6M&i`Z+CZyDg5UJ-M%PD*=CNI%jZ`TULT^K6fvWZK5{97rbxaL? z9sUV@y-H_#<`%q2 zOieV8ErDxw*lp$RXWa0ZA1$F2RB=Bu#X_HpEgip88Lv@eS9T6Ie@I9zl)9Kw;*3 zn^MMzK&kvKWsVWS0ZV$RfMO=0O*I6n03`urE@0<@Yv@GV$AGWy*^5q(5slr$xUMO~ zMFs41Xobq%Z@ZGqSmE2S5Z^Md^px47PatCRrV%{#2UWDyEXNxy{^pf*>N{36aJlZn zt5L{6$I8v`Nz2B9sT$Ff_Kg*FW8$FnU_fJF?@`elz26mGV0$xjsGRlGx^U(G0xG(w z%3Uz$qlk108Yde16kY-(=fm|S0juSOQ{9ans~wczPtoXcSheZNv~e8Nhb?l*J`+rQ zKFsr(fKo~dLeGlU-uB;s@_^dKwmnf$pMiq;gWON)NLw;R_elL3$hLbqj;qBgqA80toTuPP747?fNjdo{26B$2|-e!r`X(P5m zQ_bogUK4hyVx`#~FgF#}RCa_@H|_s!@iiuOi!V5#Zt?8nz^jde|96XTlq$FQ_KEbx zcmOaZjxLTDo!mEnRB?I!6X1Yh4~~om-wmav6Cj=ay4Esh0*H(B!if%K3(v4uF4|h! z@xpfehr57$&4Yao$g=3Fiq;WGj-3t6&Ha*U$VyF~2pH}6Fo?W9tp@f)P z!FZV6w>SbmMKf$%)SUDQU=Zr_cD%=(Y%yp(9^nVwTP-BqZagHVf-7XHtBTTL2qjEH zcghk4ChpwJ@{nb)8^}gkhyB zxPCUP_^zV-$>M^v?=AJ50%!!7Y4H?s!+Q-fY9nM3uECUR@nx*nfELQi3zR<O5O?3Rr|g zL`_`6UX9&OW0;&iMe}`(KTSW(hDh*77G0Yy0zyu}2P7@Q5PHgr(DEv)s!8*YPVu5? z!RM>_k>4EA)8j433pU`SgV+e*6-~!Mm^~lUyg4E`cOVL%wKeohca6b(NCujXbW9y!>Q*8Q+N2!!aS4Odz-mFnk;gMW)lwZ za33o#AHtkdWSjYhw&sh*-8$kVg8T-}iRxDl8M_cAC^vISm4{>jaMJK zt~9&BFj~5oo7Y#TCIzB}BuO-;0II5``)LJ!n_v6uHPXJ=1TnPa_q>Gxx!1EOI zPUOj_h=`lYMpVWagJ08|0#U!AowqthaPt2%#>Y5Tl)4*%N9eecp}OHkJqkr|$hsd` z`g@=(=#I1^d=;Tmp#v{r|Ef8K{O(IvT2(08yUfFVkPq{;MtRYTLMS0qu2IBXktFT# zq#1L8c5{x>=W|6)*y>lZs`y*Wdwt9MG8T$DD7LuKh(F>EGON!5agWZ_avqx5>p_#| zVLuG|i?+=Ze@TnoY1Mo&Npd($9wyP%#TFML{_Wi2Mw3lqWJu9Bm8EF!}erT9gn-YcQ)*eX%(O5yIi9Fx?t9#{{6 zb&AVBQ(n4=cTlcm*}76J(@FDgTH1dhj_D+%;geUxsNnho6|EK{f)17d10kvn1An6d z_SF3kfX!*3_*^8nFTpz1`HotADSFk&?+2LN)c>2xB4e2fk&gIL=7iIxFGY&?d}}!K zlrYaNRxucH1=tEUW;|8wJ&f7kZ`N|K5u zk5n_*YhUbNPiwvsxstgJ)mkGuNSRY8a}6X)!xTEd21oZ84{E#?Mvmt<>EK$hT~B|b zU)KULB7UNGYoSSb9Zt=@7EdMH*A%u6$o69?bz3KTNeC45-8vARw;6PAowy@i-$}>6 z5xb?vKhunFg|X(yYHEu0Jq+GW!*D&fxOC442B}D1F`4dvD_VQrG-;=JPiz5|p0Z%s z+<_w31LcNXrCIAmmh}D#Jz0;waz3T74bZSe45O3{FzOk%)1D3Rw7AlmtQ*8AsqRpu zlLz{gBvbBpsCRR)W$kxjjZXSDo!V~_8FAlN(cZuR47sY$tO5GkCkR#r14u|QCQiNE^ooCr1R8z zE3o#)IU2rId?EW@1}QGGb?69;YCz80K;b9aQ>$$_78m%zOC4zyK2Rz&8=6JmY!eOI zM0Y^_YC&pxjJk7G&LS(J0Z6PYQ)IjF{V(O+Y;xU>{rGDfwcRe} z)EF7^9!`L+HraOh8E(4l`k;s|YKS-HKFrcoW7;~i*h74*?NLEM+lqKuvJo4GuSR_+u5t(Q(h0QI9F)(Gw8Cw7u~}M? zZb{rP>~vDiA(V0eo+bJys&WtrYU4r;4~i$!?U@vKNVrMMhf?!HV6WztQJrEqG)V(# zOfgucobhBT77L{p&B*&OK>SEh>|u=LNHtv5252*z(dxtE2d_(d;K455{N`y{;M8GO z&J0yPZ%Px6Kv#F^RvE`4FqzrE3z7JsAi$l>rb=BW)?9̗}FaxR6ZC-2toXbjxH zOX=EuZvrX^*axM9Pb7oPU1U3I39q#5oM0$^n+PC!IkT47E!b)WO2NzYmFc+kwj=)L zcK>mr#z)0GDSj&ba8!(!E=-|@$6&8G`jkqK0Wa3?qvpp&Gim%j%h=$Hcy zJcXsG;YyuPLyqo!pVCibiN4rn`RX*R$JM4|!>g&=3IH5nv%VJ{JtKxoh0YXqR`iiJ z3d%o=LvDQ}y5szN*dEDu)eRGhKf4M*9-=-Nx(CYdJ?PJ~BC4ME4jFLn=3t)I)Ow3& z&x2PcB5$|)7w!g8aEf+6| z+B#`cG`+ekB0?U7U@w)xCG+1bPd^P)chhG4#O(*&v{7zT=buG;>1u0Q{xiIEyiSwH z6|qTrw1JLY5zP&kwrXei0@yW_+AGQNs)+D<3hs`jwFABrte_NasM}RBuGRnt z&KAM;kUp#z>;oJd9-PUrOfWr6hRo6NB;C7;9Ts@f;{1yU(@C~#De9WoDRo&xkFJSn zQq@QreO>$+G+-SLbTANgaG+~i#k7rOmCDAPy2{>VH0cId&{LVT>;@2NdvnWy8{)Pk zEh)BqaZ4c4@0ljF>$d0^*WeJJ$pdf#g>SCY1BbFULx*G)eh69JLvH2J-U2H)biPK56GlZBo36Pgd6~XK<5Jvkjrlv z;KE`G{|#2T&gC467H<%q4fiu?%x^%b*LP{%Z#Xap?59h=iL8K+AfV^XtZq{gh}4`2 z*QiLFY`CC5RvxvdA$Nt3;|>*1ZEM}7{JSEi>G#~9xllVRrx?rKO`l^x`7B*lT$i@C z|DmiB9l4=bt?1=l5#Z+a3R`BVxzI6ym336FyT61w(-{ zdC|8&0}pE`0Pt)Mv7A=!9<@@29#6YD{tzXq_NOTd&50w~*3zjI^`eW?tM!31lN$Zt0{bmOvHTNxl)(n_5LN`-GuB0A zgyvpHdC#AyYZ>^TU;0pb85rwxooI0xT>XZ8L+8pw&1Pde0WGcYwr1%*{F}0J>s8<= z9@Nvb1`3${W?dz00VQf-%T5&hO7wQyz7DlH=4|C#<$MY)dIiZRri32z@774_{2HD1 zszXy=i?$w({UHCFck)VexENR!A1e!!>B4ILb<0irNHJom10YYlaMi|ufD z4UK(^)%a=+6}<(coVA7yz6I-XVh(xzBbwK40|SM&)hZ&bZbktvb6_)9+8n3Pp^5*% z%nodR@*VvhK0GHtO^8U)z70|4wHxe9Ejm1Fo~h#C)tBXGkwutf;j zt&*eUqAIrg#*zDb%q=v8+Pw$HtXoB+-UIl*uBVUR!{c{Zdph-Ag!;B#4cb)rFz0cl zQuOWDtcO9$?$x9(hfmKjIA?K%!<7}*eog($;U+rkYsxDZP5n+G46Pc%4qxSutB=3| z9Mp@Ktj!m6p*OF8 zmss9Opp}OhAmC>*b#kze$pwfq`xtZ6S_p=t$eI4^ZUkz;jPq}p( zW1{JPGA^nVxqtD$6W0@ak{IQwd$P?Z#B(I`o-Bh}wTA4_r@$!`W- zlH_Q~zYV!o!GP<>Q{yV~ENRAi+EGOgG5p?vA{$*BwBiZnVnqQ>*vWh=0QZg)H>%X4(o3wQ@FkCE!|s29r5dZ zY8iIbWvxnSF<%uK!nT0z%XlU}MD`fbyk$Im9~bLKz(1}M&Q%63<3YEPewswC4w(F^ zNfhfKcd0#~#d~mXso{`|p#2?@J(znQmS9Tn!m%l*V8NT9zoH zGdMS8q*zAkOfrTNRhtUkR`A3^2a+EfZ<;H$9$AhMFD8$>!QwUf8p=J}u({x!L(x5BI zKgTg;CAPxvl^Bc%f4C^k`40@JA$}Q+LOPLyvpiO^ETYNIa>Hu#7L|b@vA(~=;My@% znY@TB&T^1%cdfiQ&fwb40VJfXQi=x385ZvhFK9rLmE+lJw_%Fk5cPZyEXu()d0gq4lXjd! zUFAJNgJ9Ba$=pTa1Wh87`C<7$&8B99heJb{{>?p1>#NHXJeOtQo0mD`lnvvx z`m_1%KNR66SC@=Oknu#0)3sYSm*>g13ANB2ary6Xx7&7$f&mn{r~ASQ+ccKroFNR~ zz(BT+s<3>lBroAL1-JHCiCaQHxywGTDZn*sqlTH> z1Rw6p?E(zS9&yzj`_(gYn~ga zwO$*>2Bl^X4T-$)aA=AnN(_6chQF+|>bV19k@mRR!wKjk{F$J;i)`Krk@Y>1l1%lG z@xQ#CYgDb$x|?Ax7bO&BZ3gCy*-mW(K*+uwimNqpgm-;Z!!3KaaMV4ERhofkG&*7j z?F*2bN{8yu;{f@h^w&!|QbQgg6^2k)pj@;1unoASGr)}@C6XTUWe)f@l8j zPQ@?pY<^$Ai=}aGIl77%>#d?X2EBFwO%Ii))LS9JXQ}O zs+iY9QwV(n;3$jwX*kSr1(dr;qRI6XJZOoFFKn<3swcPC1wMGMidtEH02@!%^cC$7 z&O^0>k@!a$l}X3zgE839jULvQQ|eCY#$DvhQcQig`J86Top^Qg)i0U|;`f2d*WEzF z8-VHiDvOF5fXU0tqAd;NKxt4GU1$J&sFg+fhO%!xyDZiw*xKZr!Z{zRlx5>s_pP}e z#1qK|_$q@2KB z!?L8Y+)XDXji&oe z{FP2}jis+*WRF_z?X-DVc^)H?(SUK`S3D%AK0|l_2c^fSbR!0*&hjf{7b}~kw_&t2 zR&FnK8%V##%D1I8muP>S+($BAvUs$Wb9IvCZwtlC0Xm7EkR<^Wy>}IQkRT^l88x(w zo_tfyi#jFB-CfMUl7y%cez^!r^H`bL$Fe<94%AgSJNVy9{^ZzRj&v#Q_1~JedQsQ* z@(O)hlwx7~Tcdi>i}vzdX?staX~ZIYjFkZzAl};JVuNe^5M?{!>M#mS#S5C8DA#rA zh`;{rJGv+RZIqMZpY~vk+8@ke0G0a{55@d&O?|*EOXXa}UwxEg6@MWTmwkB`Aov4i zdk>nKBquwi;uSyl??IQ7+sPb%(EzV1%VI>?=+_1$T12f204(cLj@ z$Tqil2rPXm^ABqrejYz`>`wPO$Xmizc2lRVEXA+&DNC#sTVh7=5M>q$c~6W~vb)ju z9U=92cO&;?IX!4wSN;sqw)q#m++)Y%P&BNHC9%rluCyvyPL=9)r79`%Xz5TF%1n{J z4&}WJmNZat>7q5@z`ua5Qr?*hG)IH0W-JNM_CwV|XZ|3K3G)3x-5_rHCL_ygE*m(gjY!*W` z5)nd)-DN~+oJtwp<$l$Fsp*73Oc4?SF-00&+XpIkC+S*u`75c`_cXnS>{rMA498N+ zcR&N!!@rz)Sq^T~GcIqsulfupJ+J}c)97Fi2%agM=!9F)89l-y6AC%l6zhtxTqO8Nn5aiS#j zmw)sSki@Os&~OFw!NXgBj6w#;p`N$n%F5#o!RlgT{S7B0WE0HRF^xtH0Bsxl9W5Ck z@0HeOQpbUE{ZJ)Pg>E_ERROd3nheVeTn?AJYZ&Z_34+Oyp#5<__HVo$lC`mRo zTaCYvfHkY!-MuDV9|&d{#=dt0!TZdxP|zTB*u_Gf2FVc({4D?mgSYL;s*w#Q4;`bd zjL~o{)Y=Jg_Khd22J;TUSdXOAra^M-02_?K$Xxb^b$(Q%0w8gRs-vzFz)fK49{9Dw zrl$3v*jE&nw?T3D3Ug?+UC&_DnWDn{j~p@%mi?Vt>_HjUpkyay4wieh@3<23Zf$TR z|6Vf*yM|p@)Xeo42e?*`e_M_Xk)S%qsHoB$J#dWJ1ZzvArO?nPs14zgUW7Dw3&jkP z6Kg9&fp4Z}zu|{LW$mTvQr$1&8KJilUGeVtP}(p=&X@8`)NrWmS@&eM4`D#nNUf^J zpr(|=SZ1H8WPx&BDRU^!of6oOhssNx>cXu=#nd=zJxul=G%5n4UNwgG2XF)ZpsV@o zo>r{@w=W`!tu0kNO5jb}%-f4e!eelbyVRc08kdRbINg zQtOC*W}kA@B7|c1U?e`sPYiT}b6adna7JeB96-H@%6bvS5jXi5dP4GWhz5V|uw)OH z-|M75H&b?+TqtF4r?+Wxn(xs1>I8T`2;IpSo^hKSaWs_)dN}cev@K{(YtkVRbZ$;1 z>2eFH-6o6INcp8ss(+1KMnijW%E1ycTGqiH*@VI}3Xnn#w|a|F>5W?CXIO+RkNi>BKLlXthEQp?CCBJh2AGbY z>?v-HZ1Qb;7(_hLKcYCzlvoY_8j#995J4uu7tsANU`l6)kvtaEYLzpEkCok`lyESU zBmCZ5`vcFo;vw8IRY)&SuMQx zGbZ{_HU}~`y;RPvwJgq(uj+zM48swr)hUF@UfnZ%$0EeRfi(l^Hm_;^1bLIBd``_L z%HyQv_LgrZLf;pD?MlVj3Yk^OxPXU~1-J5mWc(j%m*QBxw7cTIeTNI=Hc8&jwEE;E zdAxJM&rDpkAo^bCsoi8&5}&iAPlk9VjlV^=rh;Q0z0%Tj8ZU18XVhZ4Y;qmb0G7f- zIpBkFfvi{=*nlohmp!Br6UjPV{zH2A-g0q8QO{bVVxtX+n z5lzaI&q=R}sNHP&faGXPwsYh!q%<>p6JVZ>7|H`4=f@DYY(;%cK* zM~2t4bqB$^-E+QyMZk0nKuwK)i*R9muo~fUCMe*r1rKJSW97|tj!%LZ5Ra7_v)O7= zU45xKz4nknJ6==vT)C|@H;VSom9I(%uhHUp$iG=wjLS!65sWJ(jLrw)CCF{uZiPUJ ze9I4LGa-_GoF}i8)*Yl#^W|<*#C|$3A3JQipnLP>E)A_5goY3C3Id<33JbMXr!?g%XTPWAEyS@`Zy-kZ2%3Hh)7qwv92sIaR2|mnx-ab}dU!b0g zjV~N}@Cf!+wdklcT z>988Srah=Pd%c0q8I=y7zvS?bD#zFmFMtg$2h+4(<4hNn@6OTJOMsyz3Y}jf_j0at z4#VS91B3EasL99jFt=|X<4k~csXRLaW>_ehlo39(;bYm~F!v|Cna|V=4*6lv=*q`( zpuzqb3eAwpx$w__#_scjLWFqGI@ZmAFW*m zfo9S@y0%QdCDC275I|o3kje?V!Zvx-YPmd7O0&|o zx=(O#O+JkBnGbbb2Xox9@9Cp;XxHWnZCNKbbaU~3qpAt)fZ5hS{G&MEp(pF)1Sxd9 zrTI6qlO&0~)OJ0D9#ah6UoQ`9P3D)!F&v7BPVzvp zQuYQpTv~q7^34X>UZ+MA`VI@ZmFOn_7L6wRjnK`wM^oR8@)&RXL2p1{KT(C|Wb=aH zJQc?7dq&aijS!jA=90rExvWkK@`W?u5P*X-8E+!F`mu3~gh`!kvymBN~|VXHjYBm1f5fWwDPtdTGAoKUv) zrGRa64SRA4+94M3Rmvoh3STd102$pm+?HxFfR|aH{5)^1~;8h zZF)b`if!^v$!05c+71Y=xGKnUXYhs9UOqf1HC8%q`lpyC zx+E3-&<7tT;6tccd;v1Q;3ULW=2{~Y=V!#?!3*+S!cm&BQx457216y6)JE*U zyH&Y74(Sp{Dno}r&NBN2e_x+p!31fxJ#h>?gYITh(e#nYrq9*5RusBRHh3_n8{c#< z#%+T?5SQKdGgPJIU2@0Vvsc()`jDG46khT`vI%T5`#7^*-2C{sxUyrc2sae|1Ko%LeP^7rfYXL$$0wR+>O~L4}Er zxONKcu6{}RxkGH)B5yfR)~M!O0ji93=k4eR9tK(xb8I*kbODCVdd0SkAw_bl$uEIi zp9F`hkG5hy_1i7`=5mM@ZBd{iuNs_Ux>XwUvRzdvTdywQ%h-h29Pc=D&!*}$_VH<_ ztc0^_T3mkTYE?fp$R^c(eujmw7^>zDfrz$z3xC=e!>%C}=;64R?W;*S*D>^PK45ar zgEd_NJ3(tI+bzfCb^#N>xQcLHum-E{HEH?#gE^EJgqHz$Yi)pk*b&WKiK#ln!lBTm z!ACBmIICzmqa|FBM_Sjwb2i0Pstz~K93Po%x}9d4cZbIU9bX=Pl`paB6Oq_w_A%Z) z$)?uV{>^)F6yH`XUpAmwpnmZ(c8H6iAk351(1;s5JGFKB`@G-Zb8fLN^v@pH*Ih%& z&mz|ih)gPKk8PF^JS3^89g-hhGvo&Xk(2UIWEqQg(Qpe4$;e~@LY!iHlw!IcXZp)% zdO_6!fR37CFQ=cm1%O>Eypx_8npg98r6mz zjTVBzt5-2=fQdSf_FgPbWUKi1a*?~ zr*j(S>i{eA?8Udk7l=qakt_y#pxR>$Kx@O7ikYJuCWS2;SkObLCB*cU@uK1k^4+C|`Sgt7 zo?#3#_9m8-a?VV2l3Npf$AfH^G?pM5y-N)Y7=TZ(dXzc32^M#+mp(|Q&9!$`S)7;&p+~I#tlVu`s||QCkPdoKlpX4{zA2UG!tV+S5>x z?DjyIed9dUsXc0-ke-^B(FvXNI;AF@eH3GE9fH*3hQdR(Ao&P< zD?DUKvoG9N5_vd$5cGCp(me$jHt8e(i?askuJ915pq#}YfXoc!s_y`E+tfU&nQlzzo;lmmvR zf7F~5#wWyE0Xebd`s>!Cx2Ps>T!?6Yr&8cfwH?yR#ALlgq<}+xay+P3_pOi*X+PU{ zA->0GPu}`;^+n?$@N}0@w}Wbg=T8?g?!1=&W425G)@SQ^An5;Zws%74)&k2^ z<#Pj^B_*1kW2U^aMl(vz2d^WqLuyUeqhZ#iSb$%B30RkHnNF#PuzkaGX#)SY%caGK zRPVZf0Y~E?m-G1b6MyZ2!ZGG%As|Jzz+nX-vnpC<=YpxB9#?z=AD~($J;jFi)5Tx#y_mfsSILcIBp^UAo13a_{UtW91h{ z#=C2jdRVRGS_%g57<2si1oKj+kuj!1Y|bnL%{#1;GGaFc9#IRFzwzNCYPHJg5Y7`3 z+6A#G-Nj-L&}Rvvr8&bNcVu>3IM9wFzHt4WLYC|OQTi==Ze<#LRBZxqUw2duuh?lD z6S8Dbrtm3abdAMo#u_o6J{(nD8%8c**&SOJW4aV?dS1tE`Dkcxz^A5-gh+J)k}{J;kSj5(7@Ib`ER%kYORH^njQw`_RCOmY7JW7aW4 zLcPm!a?WE&R>$zqKZ3;WpCLX$d|<+Uj~}0)5yw?mH_#qqZVJj5^zlvQa#WF=fWfWb zY+80)-J$GXMO}Y`?Ey7lcK(J)44Z3gQY+viV$d#M=dZ(XH1lh$2Q**s0W8sLqiLTu z8n;5v6vleGnMeA_c?jD&jN2T~jnd}Y^g%4LLdvyPS2CT@2JED|zpLSW@pTM{OX#Iq zx}lbFu{+ku*JQy~MfG4KAY%KqPAg&0U*D2<_M^tr+~u38fBm|)ZZteH7X7A`6X-%- z&I=^8j46mkMOuyC{;qnpjm4rta?q*|FD$au#RV^NbXFvyfEh*^><5@fgR><08+(^R zuA@%I+*ZhpVGAY}w$ErbK$1vze^~#Y7#B)Cp;k0pqH!nGN`}p}=mcz$dyKT_gxbpR z9f^|&T{WRtEWdXU$?c=fQLW6j&j7JA-&2c|YO>)GEkCI?bgYhvvjoFC0T@T5mlLX= z!3bPLrB1;>0TVP#LD@=8gla~O+2Og2VO7yZC69v#onNojnB&cHmX2c3Q1ts70Ml!wY=#3avX08F+XjI&oU9s4jv3 zi4hId-7=Y8orVMWE_t0%YdKb#sVm9tN9d@8{RvH@ZfC%0pX5^J88zI{fwrDOOh$XM zKdbsTyNu8vop)Qx>+7D#TpXppAXQ+>soLP3a4gmYfE&%Ve6406b3Aq=Qainz;m?|- zqalqx3**8MGwAqP)vJEi44n5WY!;F!b1s2CnA@hX{sM#NCq`{Li|4==1#(r%F?&=vz0FCd56cdi7 z0FqdLt4(102o%yNXc}X0q367d*c08J086AS?&B+*mOrPuHtmMK63j9NsYG~axg{Gs zEN7EBroT>O~|J%+^%uOty!avl?QSs$j zP-tfaN&TPlAq0gB_`YtEw=@NO71LRZ?F-s?PIWFb0p#Z|IWfHM4|M9B+BmSAUaS}d zlH;H-*~C=4;w-YghreSFr30urh%iW`Up)Lp(@q5phh~D zG3lVOb}%m%yV~4`QThe7f%{IBK*sC5z_~39`OWmzd9AIOM#nC|oO1s7qab$LRm z7ZI(~gmN#c?F{qi)I!xiO=EweeM3fKT^gLT_O&v5WKbc0p~ z(6uD}3&=vK6Il~H;3!#)iS--EMtu&xd;SG-QP_e^V2S;Kb=e`KK~u zgZDHxqg__RD@6eQGw=Gy?2g6cAESrTft@H>YbkZUtd22y!3F_p0VBCp%84nAZvdA5 zr2}^e?p7ELkk4+a_m4}XIR&S)ucTM7w6Df3y7)6Q$==bBJg%r=p_NdE815LhxHqX~ zHQTvinX(G>H8Ks4w0s1d@F0MVC$vUADD#Ti%FW{zF9o=Rv3JuXu#lOvFbkvkD=KwW z4R#vNW}&S8PR4r2(vrC3Z^>}v+`Nh~#S+DQ|;7Ek-0 zT&}?#&~PWkTvJ^{UxZ6rl3*)CMx74V>C_d_o~du>*>$yI+ymY79tUP+j&`$78Ra8v zFi!t^<9){iy!8PMz}z3FyIEF2C@R*q%|oyP5b9pmr?uBqk0z~779uXa0J0M*mt0}K zhcj4L8EDXVJZgE3Ol>0boKpKS2#kRgWi+?2LrMZ?^p}l~*w`$%uGUh0Cc}T87vDXu z-c6)9s&`%WvbziI2t%JjJ+7?03Ej5X)Mja>SE|$3 z8Ey_Jysr@qiwfi*{4s}{h46=iXF%-u07mDohq-lH!nRA?iZ>S9oku>Cn+S0f0vSND@%K^5PpuwB2J}l4R z&;n0%<@h08zo9N~yyOzL9Ed&~mVzQyiC^%IV(rQtoocy&>jd*KeZ?IunUJGr8$T`f z`3PEjQ?2Td!O(`2Bu};M>cFli#D3wm>+}k+k`%5#Lj65RM#;quObb)qgD+pf}Y5VO}MV5ve7nop05KW3T^yu z1}5w{5D@$4phcz7jyq~d=yueX)v4?kpt8(nj`W64;7VF~MmaaRwJB4dDc>_%H zCXYYW8Z8>_;QnIKz#;S9hICuGHA%^Qw^3%VF9pNFJB;Cb{2{lN$kOU^x+3>0t3Jr= z#povM&d00+poIEZo@jkL((FIgPStiGyp?$#Jh*YDcWjh@jg;KrQoW}zi(0w z%p~V8EOl`))9ocO8T7Oleb_+R#R4VCoEtZ>7r1+q@5-FVH)+*vHQZ?**0^Qwqs%_^ zO+~)45%m1F>eV9wT^DPUjKACYeN58_cG{pT904KCQ+Y1TXJz(qjL+1>&N2zj%+U^@ zu&eOQ^4nFs#o%}xf{LX&LWi^we`}20P2jxVZa)&zeRaw{f66)XuOQM zR_><98Fb4<0F~Wo01mJy5|3;wmjGlf&9Ekq^3VDkczVp4w%=7fe3zaF8+j3WRQHp| zO~bUb8aN-y)T5Yqj5|;J?x}v|e}mBt!Y*rnd=w+fKyUBC<#lxih1^H%NVjs-^uAg( z;~i#@XgbRE8`$;Eev(M6DD0CMu~rpsVRoWN{xgZ`Pjq*!bvYUFF6B?aH?#p`co@w> zEZ2YmI`p-}2#W0k0BRdc;1!-e;8X`EbJNH;a|D&Sr+S9GVbtI!F}eg6qf7hdrg2zi z-U2=a-84?;DyF9XmLD$By8EE`M@G|$`w$)Ho9X#|I7wbPQ5j7Qua-QTNr1kU;T5~+ zE8GjdD$5RhKQO8SZee?lk{_8eTeY5d?+MYt%_o z10Cm%ddn57SwrTU4+|ug<_D>bMRf|k1K@;}ByQ-(!q^a>^b`GZ_Kvyq@Fu88d2F+8<%6Zq zjDQ{J%q`y1J&Rh!wkKTJL>9HON29Oa7GZslV1@WUy&fobEy?14g$Cb;JM$&cjQg`*mU%=7ZowOb zG%5EW9ahmBZ1K&+CkvbQMqVff+|iwxmNzIl%)~GBG030(p@-Pn&P?@k{Pj;h)TJ6r zdyqvd*9BntvyjLTg0mO~%Lagt%-f<93Lc1q(NLiM_!AEH$gMMUtYi7+CYoDTou@w^ zA-L^Y8o54J+g5PTXV(D;DW4=U?bl3~Y20I|R#_Km`D4}H$JmjHCd||<-H*Ef`P)3o zi6zq%P=J|%4s`i3JkZs4Q;#QVz0zYk03KGJr|+I1u&L!CI{XAa-NIaY@&t0_`7g=q zsrr@2N0zyIPl?9x6U?oU4=b&*(HsgIf>i$NpQ2&>7P|3NZKG~FT@ED-b=&t+TWa`B zZItrUX14gi0Shsx3mzNI!o1)U$w?PRIJF?!8%s=?hRK?eY<0G#%dF<%?1I+nLN7qP z6sqpMczxO2EUrW|qnuU+31yzCjcYvP@NIZ|m`>?Oy)Wo6^~tIPg0878pwR9;PYs@{ zU$wann#{n>Ocg9Le=6Q%Ztst>w7U2R6!B=P$F*1$m|(;XT9rzZCG;r1#6!;yE`IIS z*Hq#KtZ}~$BmWmb)+Hy&h+oG~M*D+_g}Ul$$v;XZAF6&XRkB%Ov+@LZ6LkUO+9hi8 z5J6E<7TWeu&B)jRW&M+;gz$^Y`G^bE*mVa_Nr0^{R#h$<&td-4KF(q~1`!3b zONE8N3M5Z7mwbTHdr-98B*U~0-lio}G`wL+dACVOjh~bKUux}){lFJCyd8p8 zF7u!lW!>CkiV5kr??DMD%()HD;WIYT(;%u?zDE-)5KLwufN?|@dvzo-o#tuy6z>;M zS$p&ah*tZjRs{CZ)nV---x~s51w<4zn=oqH@j@+Iu^QNovG+WyIn-+C=Py`BKc`K9 zsSWG-!fx^}uF~cRvxytJ__^Jd6DYI41`7&Rb6hm6)%>#QjpeIH&izpxl+MHnSUBn*k(5T0QLfUnB)voMa4hRK-7 zu+lPTH9dN%){oi>k_h^n+#Q}cOFBLxx4OmU#&(LCbkjPjYG@EO8YA$;AN{gMhuBC{ zdHiWD@NilDx(Af{my}~!e1hjudW@X z2v$YY_^6@&a%M+pcX%fy-ZT`#XVY4irf;ay8`V`E{n0urvyG+UN2>cqjjDaJf3X~( zv-iyAAm>+GS~XcrUbi03)8!+pvD9d8O+UPWnft|I`sp3mXMBG;@=mQ*DNLsU)~zw^ zgMFqMkJ1jkTOL2Ar|(qv3O9fr#jF^MVq-aZggoCu_+5RJBHn_1tUXFS-m2aiFW>Pf zt%vRY!{1wDlm6XBBCh}4)NJ$cf<9`Q_v!tPc1F3!sR^pr!ahFD8+H~jZ8zY!t+7NC zyTWKY86)TIvn(y(oD8b^mUla;(mR|(Uz*3f@wK+3FBUB~ ze2h`Qgt22Sb$JJbZVAf?Ll%qdIy+Gwu!gCN`<4nY6SIgroLx|$;WN<4SPup|nbR_# zKMrp5DNbQUB9zy?|509>g;{FtM8m9YHrQ&=gNGMEv4UV>y^TMN=7|}|VAv5#{~x$4 z_DK{TRFFw{FXpfkCw6#0*`$wBHEjOU6``qnaG?{R4j@3gth9YC?lIVFD2T1*K&l9Ws?lQ|QCrYVF7se`A#IKI*G%KF9;r ztx8D_#@?AM5-@&G#DuV~jNklUXrblxa|(U0I%Q;F)#9Lnu!tVd%Hppuw^^ca7wsAM z8IAR z<5<7ZCjFkwYuCMB*1Hm;uF{G3s!zmx{dF8*4t>moR2Q-n*p+e9gsN?bG=8jgnQApf zJ3b6&qb@_qHmddk%)PZj%|EC^%XuRlWT#CgM&Exo?f9TJsPZ0SDrg`>%p=UAn6Jwm zD55s;Tt|5$xqVav9F}K63$yyDcruNt%}2GW=R~~yNmrCJA49E*$&K?Zg|Os4n^`-o zQ`#HvSt9S!ZCogK_mXQ7?21zl(q#O09snLJ8}Up(e@WtpZc$M40 zXbnb-%yBWXdTr<_fKGmF4N2z5iFlk~t{Y>Olp#6S+(uRH#66{5M=EPCJUr@l}?FH@CFKAR28Z2UT=dZf~M5RI#jr4fIjV6lh9(Pzr;3Hj2E2 zm{MZ^G*C--gq;-MPr)_UgRtO?-zR#=?W0H02_Y&exBAm#A(ki|?a3@fTO}ijZb;Ec z3I3A29fX@}wIuYH1Qj)An~t_4(T!!E9kp^0Un&jO(S8R}Q)%3Xo;nC$< zb<2;SvmAa5B5wyiqIq=8`^#CBFepur(;F8Nri3I=kgJGLniW!iR}m+Jx|O!chgppc z_FCLew8ItSJ@ASix{B4xs-t-e+<GR#JTk%D5^m`Ev-umjC4XN*lRU(JWncx0_Y@5}U2(vf^shQ# z=ziB9)?O>fw!LEr_Ot-TE!xc|F)9(dRC8^G6ULtwTGuLmMIBQ>AN)V;D8WdE2CtmZac`if3h z76lbvjb~juN_T64m1=zl(CR9}r%~0ZOlc7Z%{}1tIw;x6-?HNXuq-D7S09gYRfLSQOOQR^}(8ZDHfq12Ba06+Krv<@V;)rs_b`y{9=hTVHhc;X0Aa$5 zhWiVg4Tzvzf8p!CHbOV(h9HE21L`x2U!NC2$GF+32)getdMGXtWDF2BD{Rz?H@qTL z9Q40YqnrS-P}!3}-ZezDG9iI_)({;%R)iN1Nta!~f0h+@Y!0WhHAFSXK4@SBDt*SJ z*!fhprYNe|HtgRIFz`%%Gq+@odE{FQwB=nL>QhThP{!4vJGDTr>(rr|fdW~+=TL`0 z5#)BUwmzW&`mq&oUj5vPw!bzl2^67adb#NASfjdhAyABSEQ8jJGB~Of{<||U&E1Xq z28mv9TOSD$t(CrM+kKt)+hD{C*rxDW@)A)1=bf03?FHIh-jenoJEiE zTeD7ZaWDT6sWTNY!YIW1G7W`o8CDyt%)6P?K2(e=x3r)T0^)hltvVTWB~)xy@-Nfu z+9FO#xkl$}3vXqVBfYLI&MB!ebfS)k^sJ7fm#jv!1}(EUdSIc^Cx~y52YsIt9ZrT}U)p4+ijYvS%3F~6Y7kHSSC<+q#EwyvnI#KqCry29+(F`(GN(HJMbupe4KNp2AsbF~1f z7a=?q(Bh5}BH3_?eu;pbG5HF4Mv8=*Bg)#@WM4@`1ZOi_P6(8OYom-iqT@1_;u5Yo z^jhP39Fd}h5|c*PBE|R0(rYxS9w6K&hQ6&Q23Egs&jw=_(S~#8#8j<)jsMS1owe6@ zN{Kbm;QA1PUOuNC^@YDOwi^9eU-Wcp)}K!Y{&UFnwdP!wIz@?Ditku@5Cze!!4hIl zOiS?_{zGMKAs-ggQ4YfWJjPsX<#arNfBh&cCCL#C*raCPq+_$5_47OGh~PszbYNlXN} zh1_BWJ$fRYj}gt423}O9iD(q?GdQee96}{{MZe<&!FSq*7okxZ^cXniMM>l_Q?CAQtk{`6hHE77}A)Px6iv z&W`?`7*%d~eH$IJ0gDj|HH!lQ-}s6q#6hr{cpUXtAuKPxPfqb-uyU;;O^O#&l`UaZ zrYTlFvLaP)Dp0%{2ZWjm&&IFZi;>0gV`&{(Y;E9fO2lyrotA;z?#0sQM=?kp{nWPb zgSG9&A|0W;7k_$ivG~DiNaZZuqyUYEjGA!+yH>*C$Xz1pSARoq%bj0y z7=o7bf!-QLRIP<5k;T1Q4MCU| z!x(oi^*6A^+yAzX*y{tOCV(^Cb)hi{fbVX1XnBI@u5@!DLvx^Tbr*_kj*VWOPAi*> zd3CEgTW4tPIR;&S(u(ZyXJczE8+E)B%xJRYiiLJ`4AllPT1l1f??jNxJyx^U2GjnGh z*ePJ-LZu&Mi%<{vkXw6*J_QFUrM;MJctKa%i(tc-R5lsP$?6M~oD9~&x#g3wz5UD3 z>txYSDYB;?9l$`Z+f!x-@M~i*6?A~0wEG-A?;v6w{p~TMI&3}74Yz-c@w=|2W*tSU zGJiU)?g-_gjvduZ5f$B@KjLtGaD!54Wev`Sa@A%qbxRRV1GblDPb$K;(9KD-)Q(`( z2{;##3V?}{*_9y`gP=6>qQ{+u2ha~VsAW{ArzxVk+l3@u3Qsh>)eqp^$PZ)G?m3tO zJBeyumyy+v z=7AuIEu+oJae(Phq)4k)it2TSD1Ch_rFIs50v4A1XY`96VDvvd{P*Z{Zoo)@(Z2}e z(R(`e_JtgOG~deDZm^AJ#6YUlMO3ZmiH^WK=eUHmQ0Fef%igIO zjF>1GQbb=z*t*f8E+WG|?G#H+&bz;(%3UEo-rStms;l_UpcJ*Br`@0jp<^%f%k-dpupZ@TDikJbWH&(*HF^F-rzQ)-_yO` z!Z)z(dsbesigBj5x(OWO3bd6d-2RVs$*pTSs+I2GPDy>lQstyGJ?#TCfln6->MKUM z<-LPiToD?5zuBmAh#dO}YPzp2_om%_#n5tnPkb8L;c^twPmEVqzolRMiA3dL6DrXk zTihjz>hu@BZq7$vF`YvENq!1|LFOOfexAOeVf`VofBS~^_7|b$@~?gB&rp^=^cUg& zYvK!$N8uS>jmdSY!;@Kx*ZExs*C9+xpU1l1{VW9AI3t965>w;(l(-S@EPHqZLjB3Zq zQQSZ*YI1oRI8b<(NJEMV^FUEwskWXD4}?nJ8)b$DV$}|Aqs4 z^Jji4FLQ1=B@THN%9eRs)FURvBH$gxHCqFXpyigoA%N=a{hk)-Oy`G-uFAV_DQtwe zq_loQ@=KAe9DPjlzXVJ#drbLXLMIJw$+pau%76t_Fj98Y|rosYe=^?uCam zHBI=~uWV5c0wFj8wHYcZ(eG&@);AG}A1v$Hg_ZTlZabWYHu+8QPw1IJY=_~sm|l{? z(uJlxlX+fW30s3wW)b<05+N?z1co~obO8`l9G(7D`-=vR5{H$V2~=k^_K&36C#kWeC`_z7n2(oiO%_J3XO&^1;51C2%W558D?vWTP0+q`5sNq;q zw^9PmYIo|chf|Dz=*hKEaQt=XIgpk7c$z&{Bv%}^w|K`nY{wzdOUQ^Ln ztWka_rH&JRJq|&;L6Yj;wv&y9Q$;t?L&7lzX?25lX)r5fZ-c(JkN>%do3-(*pZwwg zntiY-jnkpU*&*@xrrr<_JgjXFqIub4bZ?xfY@fbWr)N9wki&TB1tInnG+y|5y1vDk z>HU`9vBL;J_DL|0w97gQUGb^btv-zy52SFLPYcFFJQ{F^3ddvFUTh@K31U#$bK6*) zf{|N$L|;z;xmz1cnwaK(8ViyHUauz?qcdO5lm~sExI*PkViI%4R*3vHh|Tb z{a0)hJbshrWO4{6HW>fa_Vf@f&s+1|J26+DG{`dti zVB>-z8IBqR7A-$S12aXsGSomfGev^Z?hw_SBnCJgz5b?XI}BEs?*n`u;?5{!L!Jb? z_4-3JYcjy}r)!iqS=4qJ>5Kv7I=>GF#&9q>FHqyFR5TeZ`9mS~%o3xN?5lJ+3k$Xf z_p<<3W*};|NO8J#1z*8OfW<5!<14eAXjZoPu|mYNx4KYrA3d_D8u1G?%MsCW=Psk# zR0{`lyK?aO7^)hxZnXD*rOb&%I2?a{#UF>(jd&k>!5l zlHMb~%O?vuAVSELv! zbvezPb(CF#UWK3mNB#h{k=y#Rw(J&p&4MibO%9EmB?8>`p2DKH_jUUR)OowsoT4qW zK*uwu(8pQA!%&AR&W7pZ^-1bKTX-plpVQRYBGoM&l|K{ArQ)s5T!al6`(w1NgQ;k? z*r+TCqD@~zyR~~srRInZ%3gSl=7=<9>{I$#$lut1Eeu)P9rx>cEDA#9)v#S`8eh8oBujw-(6 zsQyCXQNi^-8-M?4*UXvvFT{}ByrbNOVv;hn3^^l+c)EdwCvToB3%v#Mrz4v4Ma$Il!*Q0_bqI5&uGH8VzzQ)Imz#!nU>#2Ex!|;-R~;M^>vZ`I9Yo(U}QFF zE=-9(?xnroiJNsAz-GWH0PH@2!4>nXqR;&3$Y&stU+k0R;YQWE49h#a44yS*UnvUw zL5xrY(Xt=JC__BCtq>iR$2)1n3J8#mPtnsA5Pp#HHfW{zwaS5(~9^*iF-rM z*P!1gztZqESVqemn!g4@eCRQ2H?0Pe&syPcaH52@!pHq=Kp}?R9*#`_sJ|r`#0DFr z?FyjDYe6tiy{2_*#WH2)JxcmnJW!hCP=jBfExyP^1wjaVJ2%k}zlfg7#SAL74*MOr zi9*)_pU-V1(>f7cW5q^BCdB7iEi;n{TF?f1Tclg@^aa9^14NvU-$=LDLHvq6OJ&!K zYRc#N37lCsX`-5z_4b2JSKzF1vTl<(_f_jHV;~vfh47^8kPQ zeM)JYthYs+o~+&HkQF#;0iV_XECtX5yHCI=KyCj5+O=Lp*GSbn`#ipe3oyPfaQO1S z93OA%9PR=9 z+pldYLzlOMp|3na_B%iwD;%O3JH%<_I}`QTDf%lN>eG>(qP^oAoZ$mODdwV}Bqz60 z@Gdc5xwxMSc8S39mf==I$R_5Ixh4J6@@#jDRR$$=4(Rk0aoi9WquMYI>e$lI)_ z2rY2luZDs88~~(OK18_(AXDDBOY$HDTEj*PJSZ}h=qk^mlQm+7VGs z*|vuYk07$7+a79jR4lD9bHFRC);PCmIJwFTHF3a#W6-H*H>Os{Fr_mG=!;`8H4JD- zQ;q>jqZ-oYW1wWyBIx`vbTeUhUg&W#+fd$|T^6DdRvi=pBL9-+d1rnTmkfqm^z#Yq z+@bAcIUy#xI`@VO0C-H2`KOHLF%ED%L~Ay^Y2r!9KT}qcc2bOV`udW-Jl0qf$g71~ z<7+hR6s&A1)+fAb!?9|R-b1k^8a{FggIa%vPM#89dwWLfLE(IqEoUz>>&om%h~hFY z+6g0De~U6s19885M|)0-Cia8l*m+R0Pdt@51BK|XXc~M*cvrZM+eq*Vua(`-{F$u=(Gc9$;&_JHNE@;p!M};s&o$P-mDu%oC8^D^ne`BL*NLlp7+an z(ZrxkSW3??Kqm}bN--C)5p7S?l8d0?>(}QMT@)=0rMEPCQDoWPh}v8hPVRnfU%^0h zJjQe;rUP@%Q*luCa@EwzH1RUzsEc9L;R@uEjepY8E08qJ*>v^_^m@PSyojr!oeoixYqRJr||>K$$ikE z*tLBl*QjU$5B{x7J-J1x*TE+{Kl|B8U#*ncHaGi@~yT%=+d0K^PnJ^IqfW{T<;}*NCTlyd5X_E{4K( zeOo`@h8C}{X|=3xj*mCTr{WGjWYtY`8c)st6yp>cM~D9u=?OmLbhW@1`+{RS9R15* zD1*B=<)!d=+|owlh<cH0G~X8cQ+vK@;eu=LE@75ii77*w2ho};-BM7y$e_rEHFOctUA z?x*Ju-~qJzhDtpIBS7iFz=x2vN~KfEL+DVO(&*=hAoT_P$o~NNJbNK%@l(QnU1U&BMH{X$gpC^?h? zx}$%b*%oMX18+I$@`(0m2z`kL?uU?$5Dgk&1LI83i;tMx(AEv14KINI3x?z!dBJqZ zV>^|22`aY=GTci@UHOA)*-J=gb8~6uONbB_>hlWAIxCN6y%HU~^a{4-WVd+J8`Gs2 z-2kGKAqKk^Gf+(soK78-*QQXQj^v>MwCFX6;KTuR^R-y!bhSThCRRFf8Gr~6Gndk_74MsGUv9!4SO-jwh`L{+=k3&pA9d}}cYLwZ3w9V&Uj%K0Yd zR$H^btc~_-FIxRUvq(P73P-OaJ#|#D<>K!znM(c3%C%%4ZTcvDD@;KfC;?_O zBNY(3-#*elicHs+sl|ZAnD4{S07*AeDWgbK_xK599y@9!QpF?|)3epSO{Kj>SdWpZ z^sor@zFq44va+6Hw|9P1*;m=vC3jmnU+L~Z8*HVM66sF`wlYY0mPv)SvcFQ)nR=9z365JjW9l#)MYAT&(>oAN zJ4?zIipx)AS4w&*bvx(zmy*(;++9iaO3T{H^As9VT6Rn9}8S-`#~xlaDt(GE1@E$GO~%Ice1_^AL_Gh^#;~GD2kHG%C5?W_O!07 zOmnY~@}$6R2kYTq-K4?OtJcI<8+d$bgvkOWcO$mjqyY>#kR)0-OxPSQ4>}6 zth74K+6|tAH1l{rH<_76dy!;Lnb4MQsj{P+Z(F7t?U?X`i(9RtH#E_fl7!4vGTP|t zuB5i1k3zaAkt4}P%1vSOl5{llj6rI$l1PMbP>1R8jdedwY;Ikav?ti;=6m>|v@b`| zdns%BZ|Vb}L(*!!rG6&Xhm~$N;=K&R+XyVey7bsgtsP_y-7MuG1LYs#ddF5^JseJX z4zjK?tTlpYWksc3Ybsk_Mkw_wQ(So&u8b_Caph&Q*i{jNIh5x}hV=(@y}azFxV56D z6=axlJBP+sz%pzcMoTNm4obZb^r`|Na=b*Gt&CRcOUibXjVdfoWUT$iWSOsZvGhQ+q_k(l!lDX-*BM;^t6XV4L_J z`{!7Nz_vM$4=nas<5P`S)3AyXCB&!Fwu|w-&Beln0(O?!ZwS-r7LNJr!*?_a_F6>Y@^I@ zrIwXsaz;7Ve~r-|7Z@Yo`}Y|A1O6G~<&}s}&?6Q&?QFa`hY2z?y%;De+K?tXhL%8k zzJ(*kd$lqC49m8@*pmU6?_YYL1_q@&>P@AMeA)ntm%kU*wnP)^;sv-mvz*3z$-rit z5&sA9>x_5MA7U-}{0`dh^n>Lu+c%p(ZJuCvIG!;Nt6*KyNHn+h9?zZUub^jMvPP9A z=nPp%+|c10KfS|(Xm6Xt(f<4{+SQJy2Hv2{5z*A&TMo&XZ*9a9!ClQ9hc99V0L@gU z8O5PPT5qU&xYq5UFN$;Q=qa_E;{jgafalLXiKki^?t*Ayt$?-ux(lPN^)p%kzJREN zu7-H?N?ucH=Of)}JVyx=?&hD65G;gt1$X~%ocH$cXugjObz8vgVT!|NdBrUHkhILk zblpeBDT_OiZ)I7N4?nc244nU?5lycwTPf|^(dEk0Um281wpC&GYeYX*k+qcR4e5_6vRl}yHl?g-(qfP`Ev*dH*VR7kjeh=V3;I-LoWdA#cj-Y$ zTEa5wTUDkhRlmu*QdQP8$PQ7A*}P$}O9%W-&eddq_e4V^6?+ex%2uUqU6%I3KTT~MMvTS;Gd~doS*b9osKzajhE0cKiN>3J&D%& zNu0VEOGo{{o#7U$?Jq|t+aqYDzg$&*aM{l|!qQ#RV(K1%mEN2|<^bvK{(T8HIi*zs z)IP)JA{SQ$WA8WGl`rT(fUI0%z=C4BRumx1RBv6$I^!<&Ifw|6D%Ra(_|pLox~>*n zmx60Z*D#m5;3ax`l5*fG`hqzWzg`xv^E*0xzWWTae}>c88q&kCg~ig&dWpPgKjOO*hcEN*@${MSgZh1~$zn z>m13}SMHgh$UVaq4X&7qK>+mU!yJc?V9U6Zucc#gKxgX?v?o}4g=B=l zy+0Bm1{}*-1(KA-32B)0SXeD~<*OpgWn8j33$**5cB=}hA<|W`i>K-#@|@B$m_CHa zCQ7AXiV2k-%CjWu9xCT3Uj)&MP#NPI5cFB@wMNRZ6yy{{&1=hc8G8bYDb{l~nJ_QG z+GwkB*AfUPzP{HFAk45&hu@opCm@-Roq!vr8&JNmAKy4KV8)k2);5{l4nb$;WV;xo zmD2q>{8DG`u09?lz&ldRqO8PO>~>^1R$n_Udp6amBO81CRZFK@A^14HYz-}ZYO?j! zF4v;$I{uHyo z8nc)a@mWGf7-T}b@)7aq{gPlm;qG?E(+^>?xiYLKJq?o+lxH87 z68ZsGagUTEmACz=T0PlDbulw0M{(?N-hNiBhTlF!DYaPiD1p)X_M{U-@|wHHm`YKCv$? zi;{PgOXsObQK~L1r_VpDeI@SQA_Kl}^4dhg1a0$w4 z2vtMtLq9f@4V24O=+B0bep^)`hep8Y2a~8zBU#sgaHvM0KFcf9?nW|EY4-pX>=q9GIi z5kt+Rp#;8YMB}4nb;AStAzH3h9K5MjjGU<0bfpt9ayEyo|z5vqG(4G=%)#D=v5OLn-LKO*-K_OK^*5Era?u{ zb8yFKf^1_ttj8ky;Zc$E4BRzcEQlX51loJ}8AjlzTmdz%ww+BiyoXwBeNpM_9@4lJ z#1BFwXUR3qUlqASVBs`UM`igOMn!(3iv9+^g=7u=C@&U!DQnZoSn1{T6Fzb{-k%L- z7(q1nXJ85$;$+(l6Us;E9qqtG*v5S^fmMoo7=Gd@OkIit)NW7 zN0D>Ih{9bm?v%F81PTGTy_v#Zg3r~uzOIMWWt$|Ae8poL8xJ9UTnZhC2bdkNM^EFy z={rV}XHywusErVK8BoD4pZyx?h$i|9TF6t)IEAJ(mDOv6Tz-lBeSLI|L#u!zl^DtQ zex;CB4#5Tp@bEF3STDF7Oy`@*hz7H~3a!>iOz?({b%Iex-W6rNDUFnPSUm3h0fIsq zf`;Nc#>$p*t9_7^&`kPeydPT@@TJ%ClV{>~k#k+#3e~f#>GHGIuLG70Luphzl&?U_%<96r zWvkejooC`ZcnAl?srjE*76*Ftp03rU@>^klq>XJaNQDaC5V>_n5K}UvENBL7rEh@q%#Pa$Dbrvvem5^2P4Ou&^(I zcfseU7#(2L@6r=dLk+)>t1T4vC#j&i8)X(Y7UerkrnW)JJn0I2QP*`yP` z2tU?kI6j(2rpTI(ty=$QZR0P}#uQNA^wD%Q1>$fAdYu9#?ny-o=>!d>@sYe?on)jz z37<-B}MUN=}q z{;W*3yUXE9gbS_cF54Rp(%bH`jv6_kQyc;*r?%n{%d-qA}E#sA^`|^VO z$kqns$vVpHE3YXxMp2J`GC{FjPiy)CQBSR->;2>y1qE?B^~VJ3KFeF!UwXq*K7zIn zkdu{LwelJcl+O%`_X-LgEKe(mKalc;Y#nmAZu9I}6s2V~ZLuE&0@$0;_p|Zb0`T9H!KP;VGA66-D4eCt#>Ue%j)d;;*V%jvw{6Q!F$SsqIhGURw9(S4U8BfY2h|Da=Tv@V}K zz_I>VOb0UMJ|#uc zlu2@i(mXxSX|lv|`|ug$o+WoFqhO@VlJAspUFd8!jGVDu^2+7_l$0A$)Oaeea!*uV zkEzn%psajHrfEReenqru8kTll0r{9<_B`x_T{*m8cW11fMp-7X_MjBnV1oH$_Bpz4 z0{)DvOpeo`*Isx_qo%`LGVDX%chhBxK}qjQZ_Q91*A1tT84yt?o}<(mFd9@ngF<+K z;DeWF#|+4bw|}EYGobl?kx#vH<)QM)U%e`dmRry1ifWN|ehx*>1fA-6iqu&$MhSAG zq*-|F(Mg&-3*SpqY0WH*r^9i&I7?1f7XM0pX3J3(Ly>eL#oE!{)p=m$9m_W*Y(S(#~gWGX*_}&&y~)~s^xhd=E~~^WmO{8 zoi95E-oUw`ginA9Ze|74dLNjd=&0}yaA(`)?U*mC7?j!Tttjx|@8VYfMuG6sWKXiO zGOsx`Cm3nkYc!OkyLn3X&1??O1Yb{ML0>j0o>n! z7^Fl~Ux--o%mrWAQ`dzcPN%ohhlSGD!=vP@B0b^Sr(u8E+83j#!6NLyuAi;rbb0$f z#@W-Bt}T*bhP6~-F%-kh!_<8-=+mo|yw!_kHG?v96rK78FjTaKp7O8HB@#;jWRNt1 zmdKfkO$*9jBHNYmfFTC^V)=U`P5MT<(4M}s6nPJlurnT{$YSS$V&yE~9;DgJKp8ypsKjy^;dieSc+sJW2CU$#PweRUe4QPw z#g9%bv}?iCbGhtnU-n^1=2PF#q=U=BeEy~v%V7p{TtQvFhef|-Ihypn{HfxaXC=8e z{Z$ZM?d3jJrS5C*-%*nveK!o<)o@3&X%-^+0LSmRgB1ZR1#tYgA4r5p!3?1 z-PG?V`5_awVE|z9JJ#9=#b=M<2Ev#2;bs@y%zA_B zvs?8>>ZaASWR;xdxbGti@c70jF=^XWYP4Fq7&J;=Et@JMmebPJaQ@uBPPNuxckKsK z-!%{_{KM(q8kwj3^aXvl7W(3)QFLytoU1r3r9nRf{kAO3YyOKw-NJ3jRIpASQSy7x z?DcY-5;KC-4e&LMMt&+??;Ov3EWF1Zp0c)S3yt4^?#3&$X#-5P$5&B_jq>~8!}DHQ zfrUMoU_QlI>vQWf)^az+9Bj}d`eP#u0Q0X?!X}V}cBg6FCI|%12s+#hrts5a>c3fb zmAxnaKeoOCEUV=EpZ5v^3choZk}efcFhNmKP*SnGyVh1v5h)QB5o3*Gw`;Adu7QbI zV0U+WUr{l^=Jz@G1$Dpw|31(9a%bkwojG&n^qgTm<)t3P-L})E9WdKv-l57np`Ds7 zpgudb?Y*qd7k^pTb}_&U>30na{b|Q_*Yx>`^t*cIe0s1`TdBtYRH|6bIRvxz!;9SR z_mUPnxsU7mck2DBIikCGvV=gm|0>Sa1)vLjRF%z6&7*$1K!^8rrg^)tgJ;g82fMUZ z6~>hShrbzrrlcR3@5=4g+ExhrRef9+w5g=J+B|B6YN`Js>bx5Q&5kn^w_EGve|c^R zsMC(=lJ4pQsj^TATZqo}4rbK4q(fcHgjV>7(%zw%WekH~HkvQZt{JF%p|15$34-WqV{7uo8;onQ&uX1y+N{^Vz&RmIv zlJN$Vnh7Uu?!6C13xn&2nQ1dt;?TLyhDxUHh+$@eB>g>|EcO7&E&rr0d$h|Oc6ED; z)XJ&@(%kd{kVBK3w+=VM*eX@tQ~ABXj%OEX&|VPD{oQHDUhO`qXFQGAr@dM=dyFw_ zrIx9A zA3z4okDaEb2eorG`E>6fmc}}BK^CSub}~g|Y1>Qr8d{MB;=VPV4rKw|Jq+nf7MQSq zUGhAnb$7j5AH;NTcid!}VRdAjN<>%VN2ROSrj`4Y zCnKzncJc{My~0*TCd77g$s-5kFE*9d1gVsn;p(6UoGv!cIds zKj%Y9r?stZ%hvc0;eD5@65h~7q&tnV?nxx;Gr)&~<*D@L|-LJb5%DL z1Odr|^k%PRGOaqJT`t}2Pr+xkeQX1&{ikb}9JT8)MElP|@u@qW{Lg7!x=(3S+@)^& zRZx@MIG7i#uQ4$wrs}&;qS8>^+@z8%yXt3IBFdNyjF?!`Y8XniUaW4!#nFy)n8m%D z^xzx><)$HId0sn1a{%|a0878NqQ~bkIWd8pE@<6cszOlJf9U+|k`L{fP*S!#fkwq@ zop5;zB!XMDXzc}UV1=(OO9nshcd|CQ7Jaz@wNVpGJ{O^LwmeTOE@Ic2PocvXp-(I? zODiuyTYTJ@PG8bi@_2i;G$LpXTMbAHw$xcq#Eig$)ocBjXR|r~Ws?4T!H00rU{+C0(71fOE0eg0_7xf zxvK3U&Fn!*SD`*>(rDRL1k*g)N8he$r%5N=Xv#H6jy1>7w`-_3+C>$v1FP=Up`h!S zz{I`O=QtEz!_tx@eOTs*WLAu4U!s22HI4<={_Ru6i`E@^hgS| zI1t9AH*cWbz;M;x;Vt7emPW zj&_cekWDM^Kz~X1r^k1+9ZXYBLv+fps_IXT?`k(lkA~69yHMlL9ioxQ!Y zR~HK2Q|ubPrssjN4OuDP&z30gG595l=CT)+kvicJW#5DCrb$n-zpw3Y_Oe}x;JP}M zX581VlbQumtq0obnnlzPKhho-TJQjaTGxPXKG62p_)?>XFy~GgOw%61oZDqE?R=>9 z5cB$dL}c`nm^{Qvr5pV-mz0NE_s}PkH4wT~nyz0A!wTwR6qI}waJh)T6_b3HdtWmz z@WjR}8GfJp zV2FCNhDai(r&>F+=Uk+QP;E-0kf+*et~=M35wRoOBc>Az7mZ?8IAa3U8tJ;g11UXi(+KhdxowkSoDtF$wmj;)5zo0LkDTO zT6x;4)7n~=-Sj{DL%X<7^zgaXir(n7L(7fb$kqB09GgIYyZ}2aD5QliVDGZ=r(FEH zYOx2^aWLF7jJ|d&*`9DLU=|xg$tn-j=tm6-$^-Km=ttx7pg`U0NDuO~^~5A+jbur4=u=7464YFQE#Lk$rBTfeRVk!Yo ziyj;qMy1LDZW&flT}uX%;ddbtsA>G9cyWXGa&z64KU9%a-`n(B)b5pbYNV!Cv6hpE zMEqdo#WKgOY_OicV3PmIdT!MGIj(FjMneEV)&KDEI|w*=t#tvd4SlVRDW404^FL}@ z@3D0DHMl^FG7IvxO)73zV;oDAN8K41=efrWqhn=D7V>)x4a(QLSx#!sezU{6=7%7t z#(BLh(v9_^<@s1+^I7x|ok=ETsL~r4DE}Bpliz5smKoTQ7wEZidJOe_t4-4c(W|#0 zT1z&Q`#bGUsec~bdrFK5JqW^}(X{(L!oD_x6du%sShYt{FoAjm4A7C&$ z<3cq*VnKUvpza^BP*=-kZv2SI7Rkh$t`&e`Z1f_(LdZ+&lc{GRR(#$ZT2QDBb_kt_ z?5s#4tGc1IGjZ=2CaF5bPOqc)h1$kW>kU~dILbjSE)nV5*vQCHE(oc8uGqJrwx6_- ziM<>Pi*Nt{sR_{Z6A-KrL05WbNa_tNaE4JI2?A-yJ}SXt*9exwvmv8|AO9TWBBcwO z>P*3h_=KEo+Fji%K2VV1cd4W^NUr{9leZOa1OEKUMJ%>qgX%h6ir%+ivj?BJjS6C#sCwB)O{iMefaUNYQAT&Rp`KzU!a1;*}CK;fKdQod=sTMTW6ddPZ7 zmWJ<0^=`{vPKQfz?4hi@~9e-$tRQjV8 zhiu6BjM(gu6rW>Px{;SQFm9W+54)$ecTcF=oh3Ki$kG^+@tsrNNHSfrgO zwY@pNzNjSaA2YwNs8?sjvJb_kwqomPf{bW@jDwtvofR5Spk& zVgxE8(k*lsX|18C=C{ZgcK6&StS!N*3s2d!-wN1isDv+qik#cTmRq2}Me$!mCPt!( ztf{8Do+l4R!~w>XID)zvi3-xVSQ=*}+@w-)6dH;BHkIJUX1Wo?e$oiFmkcY7pkbv& zHR(blT3%ZCO0955b7@f_;3@iKIS&Sk$-Tj%AQURS&9MJ6dLdi^X<*J_FkBge%BZwQ zuyJ#fndQjESadP(^O4hE=d!S6)03te3s)(mCv7qoHLGPqu87Pv^iT%?2i|Mt2THJS z>ud%r)9&*by_5%ykZPcTMw#1#%9;ot>B$hPXCk~UZQ(G6+f|=U4#fDiQh*B_O+;NO zYApS0BK)P0q4dH;AehXMEKNlR$-|mEy{X zuu9`_5g|55Czwt_CcLW_JGHUU74i3el~8xgq32~pMa^t7FDovZ-2aQfvC*)cyzkuOzuHLd6TBjm=nx9O+L#w4iC7K2Rkg=1HTc z(*YrDrQo`BO$aEpF7!6 zSpml!66leY2rTdKR~iO1%yV;fl?+@^zEVwV5#ZWYWkE)LO8CslEL?YmCAzQXcvnVm zpc&SphBTrF9kLelH8-fejfj-8B50+J2$y0aNM|E_eM2J(i}*q_NSO#3Lxjuj5G3~N zhXTbLRsTtiYr26#ZAE?QPB=}n6^%TMKx35-!_}Nk!D=TsBU0m%{^pxe+{NI*^wbsz z)ghcrDhMZszZQWC&gl*R211sT&;lo>IL&ds;t)=aD~NhtNxce-Fo>NV?9afg>#5w- zFBm@{2^@zEM*Btyh^2KEL>=4NRk5v8_HRRDL`r>Q9t3i5DvUl<0A@}|CJ#FSg*BYI z*a`RAHyDH*k6;yr9S4+J;j4!!c2VC>SQ=OO1Akr%h5YDN?h9$Vov@Pp*U||);nvXt zA@lz^bFRT_vxC*}EHpno%E&-B2y&Lb6XYEL`CwAkWf#WDNT13=SlSDGyU?09Ff4t_ z!HyJcFL1Y02o16qIOr2f)9giv&4p0pba@RXhm;jrn;0Gdlzk6+Y%gkSc9E@vXd)$t zQg;W@)O4FVA)}>L5&kdiP5U~jY|^^}U2y;xS{F>89Yinba!2awD7r}%V`#6V=+o(N zG(s>qz7Hq3k0_5dVGlReDhpcvRjR(+zgPNHE* z?@tghcRPr>4!GfK0-8pG&l@YJI0g*&Gczpvp|l{#w7Pb37yPBCdrj-IPK-EUY{Gx3 zr8BVL&@M`J7FD#KKvxz7u|ppzp>1ieGZ@#LN_5v*)N(Y7XH689$oh~L?5T@nsgh#@ zuPecoGJRY`3ymaOQoO71mX3dhM zMb5OQKJKE2GcxMLtMtI|7ntl89MRL4Vfm2SNw+_zZ6rqBX>4onm9Y=96|2!CU$ zD}Sz{J07A)df18XRut!?!{ca6B?v^DmeG?+;61%?Pjh8aPm1nHO)HB~j=h{y8H3wC zmJU`HBc(J7_yc0^}&dn#%bK$H>-dd*xIJ_NY5cThM%*&is@Uq%7n$QG~Axa zS?>_ar7YsocR-FqgMeMislO=N7Yj2lj28QfhElsQy5%c^B#SU|s0Nr0`isJE`gP!5_ZTR6p^} z*wzw&?^lhc`vVIeb)|3q0txe-GP~9hqco-uggO_mdUUm}@REi*EC>({jCC5kv$-lY z2>@|8c#~EI2$#ssyt0t5Ay=3e1R0i!F~**cPHT)@_zd6I$|>C1pqJmGgP}>W+{@|d zGyMM6f~DimL=XeO?JQ!IFyB1k~;mbICX~y~Uo<(GjQNIGlPu!7&l}Rd~AN7TU zH2N+%G!XT@<535p2#jHgKhwL-3&AIJuaE~$eFL`#Gg+vvm?IT;1L19Y(M8=Cv6S{Qwr=!54n6-3Yj((PoxpcDZioUO!m*KSDwn`o~4i(#ZV0Zl|-sgxs~ZX#AovnJ4p5aH(3Bm&Cd$>wQqibW*#L?t2!SWav?fwqQ- z+V=T|>aJFQ^rpN+`RYgveCbDs2$r_=qu@|sFI7kS;84)Ak+C#0RM@m|4F}JE4gi63 zWVDB<>{k&lV!Y~T1AGdQN0)^ejXLPm2+UPi8~YY1^3e8Mso&>T)`#AQ3Y>QSDF}H+D2`!YzOo zV-4d_%0X2^jGh3XD4Rs4Wh>EH(n$=Ls;s5=oxqBoeJ01w zU?N+eQ=`tJk@odVmJyTUy^m z9FdOhq#<3!R*glbeK+w$BXyTZ(?i^ozPF%mqYsj;ws8vd%DWo1f#jR2v28C3= z7uK$*D6?lT9{2tqw5GQhV(g$m){iYsR(-HSOS{m!KG?+Lzfz^X5Lh?7r?9@FYndvO zIWX;rF6|2)9EFu${Ed$F#Y*-0M&J61t5Vljbh#g(u(Pb8tI`0-5m(_-OP?k4H8o{NLxBcY>>PQ zsrF!qFlP&B&R}6}y{mxvD_rXU1r%1!`L0}Cnt5=r=%tJ-da)jp<=#dSAjkZ6)%r5aDZv*Te?0R;Ar`lv?D}-1~<=- zfQELd6-^u=;-vm>=<^7CwJ@Isjzl+mWLhv%RI{giY(Pg`zQEi{&9HbWs~Jx!A)g+M z6qOu1paF<;1884hLP*-4gxV};Zc;y=+(%)hjPt4EC=B7cpmC!h4@`Sa*G35!yWRUh zeob(Is~FGI^cmlkgdQYDWA9#iMKeZ=wpQkK3Ru8q)pBI9Amfr!ssPY5W zAK6;cryfO(!T8I!rnoU+!&dcZ(HQWb#V_gD7_9!VY9vPk#ob?0{b*6A$%{M;AEH8V zKu*jJ&SI+fr#G2kH{4LB4IXKVFQV9(*SVjliQO=b$!3R2==584$idRv8|=6^Cl zyEmgMF%Xh_dNvltMXRX( zIJ{P%(4cX`QM#_s)NvxD#vBDhjq>OQP^fVm&$AL4$`eq`L+ys6u_#wHTh{veDD-U{ zC|M}-ij4=+s24@;#$&%$+C&S-1Cdugr>ya?qNP5ko8vL6B^RhxEG$MHOleRopnuDR zp2T7|E_gyF6NGn#eRntj0#+W30ilr4EMXJ7uk093%_fKrF8iMXQFcL!Vr0-G3*V-r z)1$(&r*wD%_|`CldrT0PQs#OxjuZ7A{@DJpDDU#GSJbn4vv^ttPpL*4{MXn(pDFIq^oACY&0@UU85g-tNWaQ+4w0cbf?kh0aOZ-S^Ij-ECu$+3#;a2KA^ z@&r-Wb_zn{Fk274e({r<(}-a>@*%xW5bY(?#T1$dPCNG_ElCvpB%hC@NfKS8Q3cdJ zNgR`w+$Z;BQLX;e_l7X$nRh6~FgVvBS(~~63T$vvqO5_9Z}15e<5Fe(u=^n8Ygz5o z2ne0!dn7|JJTn)?1U|XRpdhig>FH$QXW#fX56gxp#$jKW#~;U4^M2%E@=JxC z?dn-dOBJmXS1(r&fhgXf>bj%sGs`e)R;CzWx+khQY4qonl7h?nf?*iD3R2w>eL=^c z1>5xnb$%AC)E89!S-|e6VryO`W)#HpsmeHs5Hvjgu{Z)ld((rf(b~P8Ai*sXr19#3RS#7 zi1t%mU&`72w0*h=Ogx9HDmjta2Ox3rooN~76Al>}$`8nj*vo$}nXsy1VZd?%5%OoZ_C)`~_!_q~vVHu)ks zW{5G;nM;{}W{9R5$-tTJ%@k46>P}R3mKflE>HA}1H88R>x;mix>= z58OMIcFhvIq?+ew=xhLgWG9+A8y$>(OLu02w?(|A(sMxJAAO*zbFgNY&e4oH;;i(2 z3U&QcES1`~rO$stM0h-rn#~1I>|jj`=c4_Ea+Ea}vhb#B^kJ?@*EFZ3dEh^X5FIcN z_UZO-GxyFD4jReWmafl-?9lEMm02JX%9r2C`+*6dX9#rc21?uWv}A#>lh&W4%mred zlw?g{>9*3d6EvPMps}8GgG8WHt`%ZILo&LR(&!puZ5VPe&an^rnX-Q$)mkW)xplk4 z3T}wUAkH!}NX;YYhEq-8J~awh&Yl>T`EH>&j>8tmY42ju$t-s(69e{5v_46WOE8Rz z$0=Zmcq!RfQ{|W>Mb ze?7MPE&O0;paia`;1wdO{P}F4W`^IX1tnv?_ZO{PA>6DNqXJZir5;YheQ7lY_Sau@ zV};lvaP;_7^me6KWO?ZZzw`UejN6=O`6@_vDF?`Ywdib-v4K}A zH#~@U4|-M#Y07HRz-jSyely-SJv^jTc!W012dja3^KSgfjiap06=7NIQzfids=f7dFD?7P($Dl}_%V`RgIJ&9tTL^&&wUK8%7kfO|K; zgk-~_mF4Cm|2x%K8@jqdBvdrLh|gsMWQSL&FjZ`Ei|c=(a?P5?Zxr<$H|+-Sp@Kyi zXeWP!-v_r5v#*umGV21J-zd6R*FuxYx3#HE&ei<0T=|0~gl%wg7cv)% zEmiDx@tDG)$hGG_Fof_GMh3|JYv>Z8-bx*cDsW6iUP8k*i;hynEy~%9eHgZrZ2yM( z`+5hB{2OxOMo*gmw`gfOeg{)Y7`C8gXJLE>ihmY;`didA`)64RzSPasiH{<@H$J>REW7Iz?)~{WtHsC}xKeO(%o<~0aLIk?Kg;M?n zjA~w{JO8rrb^w{}5Ko(yEnCQ^kS8w&IBMKxngF0id$=$uNX%n36}cc-c`ggJfD60i zqY#T+*MPGvNAvM#yrUd_NA-6Ky9&9gY6}H`-%+pdf^3_kxE!G2JE0tQUQY9O!nkwB zhc4}erK0@b^mQi$sD;R~wF_qX6Pf*YiA0U-_y9yGX)|#Z5vPVqI}(z1P3ecS2wX)7 z>quH@GRhQjE)FO{Sjb3KvyX(=qbv##F_H#1RF0BxgjQxka}Bkiy_q1J<$6-DJ>s)e zYCUz`E9P5u%Vh-n&sD~e=y;!4YrkWisv;HV2ZKs!$pRm6b@4hnwh#8y@o0b@&3RfN zle6N$wSBnM%!4a9KV(vIaWfRF$HelLphNnN#t9+7YF&-UXTK<_yfT(8Fd$v67@?2s zhQzZEhE=^CEiIQ5G~8C|Kc=<^z>iivq4)!!S9v>V%>m%~+(-2F0K~T^kEz~405^OM zjXNkBNdp?uo`a%}X$C^t(QD~l^ywgIfj7bjvqa^Jt`GHA2#A;W6~m|chq^2+P96_> z#ihd)nw=$1NLO%l;1IOG-MeV~A#v9J3_N%ZN@*vrv12!n-x1ZJ2Qr~7|Cf4Yi-F>4 z^zZYj{4ZV42J-o?pz4Q#1#lmCJS+;Oa?7dJ5iwVaT}Drj2-or*mhlGt?Yb<#@AUSh zu&3Hbg|%d{jG~T$U`8*c7e}G~wp&VNj=|vXR)(UEflxNtO>xJ>6N~RVxtCuF%O8$V;7ThT(p+l7gPNl@cdCJ)ICS|%lcTUUoYbv!*LAYP!5!= zv_*6^2ZU~*4UXXLCEt@U=4^aSF(*ayYKs@Bc!*S0`ydJx zsW&A-ya)e|P!dr0A82(iU}*VDfeXm>6gHRT0&02+0>{-T!6;=SIfc&}g2+<%&lgj+|^p)*(+ zn`pXzMm&|at*5NBFx8r^&+Kzf)YOFJsPPE*l!gXvFc@&ysfX(m`5(xPMOia9H8tUsmeQK&0oo9SyilA4ml)U76CS{X!Y|86Nt|5rWl_m3aRy5T zs{3>;QkJv4gg#Yfe(Ml~ro_=ybXi!NhpX*ifGARi)*`nnqM}eaSNmC;DT(GKSq zRe_^qav#%a@DXz@8{yVGyr}}wR{wlTp%m zG`0(Z9s7J$nuP}`{RJJpDu!2H0vA*X{KJapXfyqPIxNspr)${l*VAa~H3--87&>@O zcsY+vQ^AWPIFES!lJ)NgAHb1^BBgU08C@6d_O;On3pifaA7JKHD9Jl)pGHlti+INw z+jun$VNU=wim@lX74AATP)2Q|yVt?Ui>8wHhOn<#a~eK~ODVBfXv>K5=1&IlZHbT@w`uCOyupN~OD&zWuw~3V{yf?bmI54K`*^o-z7M(0=9Q(i#@T%L08Io%* z4Z95!;ib}a<~ESgJe4$eL_noBNB`TdaSnDm=d-s}(GR$gugn}vz3zZGRga>CJCH{# zAJL0DVuNNe&Alr+O9p-E^XGiB#hWjQ6|ZXyX$RCT)qOw@+Yk7ID<#Da?eACs5o|d}zijTKyCP z-4b8A{1ikja|n%lCLT*tEOmPhQ2NZJInTko>i$WU6w%yPH;z%Kz3RAxrxaA|T628% z9i=M}yf=)a-3lT-9#NhG65V7R+3P@>J;qTz9cGg~h=%LH+IL^0g*u3^(PQa_4uc3> zNb(D?^pSO`#S7u)x^xLvpF<^>5?5E^?T~FHQFXP}2TYakPif8z1P0+Y$U84YsLzm0 zUe?AX&%yKSK-IsvHsu?uwrI;!8PNwfKg{@aO0%SXN(S78BLJ&LA zRxf0}0CneJykW)Nwc14uU%?v}IEIp6LGr(~lXkumJ#4yM0*driLQ`Ljk70HM?_QyD zbsc%V#`;VfLmgfVXUp}O--`0u7GJT1*}qm|)=}DP;nRA+12!D}fCQ?Y{4XZTlFX4k z-!OB&w+3M#g}>c1k=F488!_|-5PhwZ3duZ{`FCsK|sa3vkl(jG;6`MJD zSZ_K|LcVZveS_if2kRS8)ymPuPOWuXvwk5nWx^s$Su`Mp|5YT7N2&I z^*hlozyd(SiTXFXX@ELp=l+OGvbvjYXpm)%4`8V1Ol}Bk53;qJu|-Fv=t{FQwBsEd z6BC93vv4X9fz7y&2f5)8MGfgfDDp=7{tg?>X9fko2l4W_NPoN+eSAg%O&IN+Ilqx{Ioa)ZT=NYHrpRj7Dh$n+zJ?NN@g$M+ShDYW_w! z$*tGuTi-w&3XcIT)VeKPH&v|*MO|~6^+A|Rv+vOI52AuY4A-_qZF=)JoCF(rUv98H z11YGB8cxV&5{^$|v$Wx3S)Bgj$81zPeELiDn4boe7;X9j$uPaj1Wt1{m(vW)g{ zzF=6Pvl)F0m(joi?BO$C>CXbl*^W7Mu>hp$3@%(MgdDN56!j<+c5ng37DAN7Ep1B* zMSsmV(tHA=I)|&=KYq|{3 z>a*yhc}-hCgF0+JMUOv&3JgC*E?+=3wzj86U&IirN5?R0_}qEGCOq9-<@_-^^aal5 ze#glBt8lexlk^J#(hR}>;aXLe9;H5C#SCe9KYH^Oq`Z7TYW58;jUP|Dzag^GZal|N zAus}V`?SN+)`)S7;vj)sCCQe2zr$i&JKY2l;jS^mGG!68%ez-+0*oDEw%2BCH*PM-A(62sMhDwBk7YQJK1-D`3ehvL-$fW z(bk^va08DseiPLwC0CK&9H1VhFrvsgG{2NwTRNIer%TB-JOm;~N}_<&!5>lL*&3z3 zj=3CBW^N=GL%FKt0#0KnSCZ;(q_KwbB*|kbeKC}KOEnHrcO%&$bnXImCoz^kKu_wG z+l(D?`f^N|w^&K}aiuTHu|#V8k^1Gs%7rY-GLoCPr$Z;fY&PgLNE3-fWhO~=-Lcx`{k0@hi^G>-zIyXi$tu#PD<( zixH=Vn&?`og*@~a#t`M<+T!umK?PcJxx&X|d8{hrLV@r(%3giDY@Jr$>uiir#er71 zL<~^8!9))S)2-7D0w$4*sa!{zzk@oP%2ljxznWTvfh%%D-+&GvnVPdKD9i&QoXpos4Dczn=JIsLlJ2L4uKM$HumCR*#sYxa^Gsp9%d9=V> zc5QlHQ8IRurkq@_z zrGMx|Ik~+wVi!4UWpAl(Eo!C(n!4|zAzIl^GTuc~wX!dwFm`KYXNOF-M)2T#9^eC< zw!Y*8%XZRREk2M|lPU_ix>RQ;brfbg{>`z{|D?3ma5R$ z07F%EbPd=uq1d#8o(S2eeq2cpZ||v`k(Zg#1I?I8DtRx8zi<)t@YMs$^-#N1lcHp~ zj#-V0tgUn4(1_kNOUCSn)uipH2{_|XQd6e4IwEumO|wv`zn#VVbrBF6bwBQ^NDeNa zjlQuNav3cw%t*k)_7P6ydGN0s6R~a&k8(8mI z+h{9lq*gWP9RDT{rB@bmw0jkN8UTBvTXmfot!M?RyCIYp|-=;P}^1Gb|t6>o2LFX47j*Hu^O$gl;dj(OsP1a z3#=3O)u<<3CV;Uu&M|a>IC?lTeRnU_jd+Sdmc5x;SjqkCL?$pO7>dj-nr&t~e=$@W z;sK}bz`yeqiKCnO7#z+Y9#K3t(+ewkw6t;q^{|%fOXVli5^K4egZ?z`?>rm>QF-{1 zA5`83h&#)Z8rjJ16&62J!FEHp@`k$AiY1AZXB20H4##$Io$tjW&(6w(@7r*;xVme4sy7t^l4^>fg-G6=XY&G_VWh+R4G*(>s-h;5(F!?}Y<` zA&PJ=RwXMIpaL=V)$SGyvJAflI1ynlH+!7U5~GgaUOUD~=3)2SgShGRrOkepo@`Hkj`B!{sbKL;gL|kA+P{g& zh{2^ujGe=d(qTv0xI8aRd#08$;$!vR%F7a7XbDWxQn3<;q3I zwT9@=MA;j|BpCvXE(@g*8IV(oWzt+F<1qDhl5M2u!!*GOK>(8( z%G5=!+PN-(t-F8?dWbbg<>t=!Ec)wWc*~YBuDRz?-HWUDp_<)zF5IRe!V>gvtto!X z8awh3Q!BpNY>Nv>=c)`k>ms|@7UAq0!_1R$<0pni&LtyP+1b7m2Empxp~CtIs{$-0 z<|{3esgbMf5OO#Xqbz`DiFM4fm>MgEFOxpNa`r^m6S+6^xw`l5cweL&txg^XliHj7 zcEsg;cUs{Jl3ZmpU3Qh-T1-twkMcP^1!2Q@7xbbe17NyV_>1WZms)V?5H2<0(v+-i zn4JMyBg{$NsVsEIHKZnP5MLaVXp|c`?S)n=3s!jR%d^IZv~=Hcp35n>9U(V zBC#HtAfqqBWG!?EA5M6!esw6$l=J#Ia0fl{pqAderH)In1~6FQ)15#8zm&uK)|5lT zlrK?w>yK)70v%C0t0=&BU!Kl#K4XS<>Ix{`fluh(<8O$=6Dz4ocmjU#E-1+v99h@Beary)HPBED zMXAY?uaCb#6sbc+S(dCO(cp^E2okr^ii&d6M0aG6LU_Rp)A!hZ(H^Zh@;jIRQLsmG z75Z_$dA5_{@B$b*?Vs9U2*u$019MM_&xQtLbhHNohSD2m#b7oV-)oM4(S}}7Y`QX! z35EQl&-=R@iM5nVS1_c%@fY4uj@$Dh6k>oKkW7j{%4e%<`~A1KhaIH4|%^AD^v&3tV?yMUK_M-VBH1 zFpS(<>g`4u)#U+F>q;Aj(AXNFl22l3Qw`b6^ZXA(gXALhq^B7G zat)6uMg3w1uo)2)*6)6AL+<_^eXSvTTmMsmM~@32IKC}HKRDcuRlla}W|8k~3j3+$ zC&V1ZB%`bGKQc$ul&fjl-@EW$zxj*tG+*iV>K&qb;$=iTM6U@>8D^=8S*qBe5av$8 zISQm9bwLj`Y!MH^w$G;NW_;kOqI%mId#vq8()(JN)jWHuR~x@uf+)GRY%7(2NK0x% z9A72V+1m0<$u*z4`^goYx?v}(Xr|0q#1bhlC@884D{}yz_Pado3M*;qF zlvH?@rt)tr(gylND8k9T&UNG_lED#LUPt!STI+!B53x!xGa>&OU9BUxv@;3(DLo=c zP7M;rgzzq}p6NeLqiVvJQ_ zzbZwC>&bCmvzq|fd2OF7RycGQoOHk=m&Xx|)9SVPkC*_itDvL)_2tSIv+E)>HofF5 z=X1p%iP3In_|) z?McT1~h+YUhw@xUQeAsEZhbRvZW z%bm?Cm1Xk4;bx&8v@uw&VgBc-;@sW&%2Y#o9xOL-io6P1yxUULwKUOA?&iir2z7}- z{47vtUKt8*3?ce(ZR*}wt{PA(PE9m-2`NIGGzv~1gOQl;F+u!-6zz^b+r2e3XrPI< zEzB_xm~4i*ogoI0VYJAUjx?5iO??|;T{C=Qu4I00EKku$%NkR1h}^(Bu@s-1ZHLQ1 zqdBe%%*{ec52DKku}slmJkIG_gWyUKuIwSBH^ zUrt*>fogpvx*aM9NpmWbV;J_IYa*CRdak zpVO#ja?J{zeHlE49!cZ-8^j=uzlw6X%D-ReKr`9TrR(mm9IceP5P12s(`nrYD1E*_ zra$qHl7nQsO2^)@>sCc&zB-H#<&TV3@>=NiS4G0h>x2U*hc=9oZi zFFM{_c5fJB{S9c*7Xb-46up!;M~2a#hz19s|MoL92m#OYWD)Qb|8pTC!>0)0i;x9R zVOg_(P^A`fPY1$oYtF}MJ9R-fF$;grR5@Ent6JczJCo^D3w*VCPkP%zuI*rK^{t3q zb^S2(h`z`9)(EKD5IB5Rey8A;Q1;&}k;| z`!~n|NDtnUZz~{g!wS@@6-;1-AvCa++);9pDZ7;%A=U0qWm?NFr5k-kG{JYO-deUX z^~K+~tD^2#YSmhH)0V|!1LJ7(2D~*Nexc;nvc3H9i=jc%XXEH{NuN<{wCf9PX)W89 z^F!N|qnZwF(A4ECU2Y9)yHmvlZR7}ROVE1Ou%Gz>qPY+d!K_@)Qja#Wi|f6{`nrVQ z>g;fD98jKBg?wvT(MGQ9_5}gO!3UUE0W5vY;Skt)znC^p&c-ON9U`R-R<_3l5^ZH` z2kUK|+29e_81L0$i>ewVVb+@(x0P#KJ_`nsgg2Ej%^()ha7JcTX?k0EzSMmixwgXw zEwzQ3wSxe#YdbA!C)cnaTL?g9Y=Mx1xujO(q4;&>ve+&3w4LlxwK^U!7XIPkBMpY~ zraX4-O4Xpw!Fd^a%vQXD$gjQJS-Q86X1A9M#7gy*{HE!aF4%QQw!WZ)+}Q7ldqGjj z{x6vYl0zs%O$&;8^wb41zA$$J^=8+QC-|w-ip)F86QopAO6w@Us5`&`E2tf7ovk2; zg5TyQrl7pp#d-G|Lua|3 zlU-ME{DAJB$i<`2!)1yB23g-X%1rHoE^-g4+-~aCMfR$VLh-pnRfw-5}DO!mQDj5Tlh|PI)w2NF>?C!*b&haxC1u&;}5Pj()ht;|R8XuW* zOcNR~z%%h5-Ds$YNr86mh{%nusOB0hvWmr%UO!`*D9)Y6bd@_t4C-fUpbP=dG8KkD z21z9kdPDxcofJ6D4X;O}IfkMMsK+~4Ecn8SBC9*7Q1$3(C_|S;RxjMhvYYJY;J@?d zmSv5Kp^1!iX=9=l97b%@O|GV0VpBqZ0oZ#wn%xa_H){uN>n3|N>tyncXl9~)tl}4q=xjX1-MSX*`oB9Uzi{C4U;$P7j zz>`;fsCRccQ1bJqm3U9;SAq6*XDO!+z3nbHNbFgb7pH`6)KGvA1Os}M>WI?gL#zgS z*m$jeGtGBbH`8VVY;u*pDX-S(YtA8N35e_R8rXBQxNIlNShv#eCB%{Otd-N--$7PW z%joYO5Fz~i=|m5?QrYEg*c?!#gc%gzb`80wWci%B^pv}mnbKNckx)e0J>_B2;g?jc z7i70H*3_n#>}I?Ks*v({6~*vN{kTeg4*+nT=h zf$cWt3y}8F#YAXqS|uzWwCdX8xXr zu-ATt=yUpCTGJ0)VzoWp?S}!lJtl|#&{`e8QgDCSSIV%YQT^o_(sV7Y?JqBsR#c*f z1F)3s9Vlji+{n?y5`j|fJR(BUn|b0?BVrk|9E;H+-kvTFkSjOn_Zb?pdX-W$mQ+Fi zuRS$1!150Y$q3>wz*0i(Lw~7a(OyHmuOgq~{h4YHl>Kp81PvW1Hz>dJ6HJId!+?Nj zb34)gfpTA|;U{t#1gg;EGbIgz_i#xZ9UTOn%%+gS2LnWpafR++In-`x0rGX~gXZSo zqqY;MpA19WIlHHTmzoj%g;A<(viK9JK;xwHGz z_vjc~`M9$AD}UlwOzQr&rpWW(&O^|$SlNcQ50%$fxPoJS*vLrO!`fVNoalY!)jJwB z46xDR`7@%g|pVAt!V#q{}1aqtb3c3rER)jIUJ&E*~@@&1l(K zsw&8Bv|Pu$=oUyg)(R^#?L7?`Eq9fhF?X#AWhM>0# zj+XmKExS^q75S7iw%K=jN zWfVSM_IAp9u5R+`X*xX|Sw}}lVHt)l%K7IsYdmO7YB-%7FNfEU;v&3-JUXq!O3Xe+g4x-zYpSL2oItHjgFJ;-42yjF~I-QZv)v6$qkUVE4` zscbW$e?o^f6V4$3Czyp{RJ-zRbr*_yWFo@CA*Em-|aOCUhenjIOOA zeT|oET3VhrG|*N4z?Nj4EgTMMR#uHEI6?h=T6rOw&GFxDv@-$xaeOdcO90Vtg}WaT zLA$F~qsECK0$L9mk%;oCA8CD}+^lmKsaS&HTT^T5(G4(f%O7IFwU}-<*#n}Jj+~>) z$*1gdWr2t{Sa6$2D9Y~bCW!tTs3)M~Q4O%p|$RN32i6|VaW;WTFVmE9WN zu~;~)5W^@`y}Q!S`2>@7UcdPdsB^09&^Vl#GH(!|t$wR1{qQaa=BPFs9d4ThToDrK zH~C-HOws<;@1lQZHf5&DHH?o{fr#1iCgrEfF52$d5JE5RVR+;#d_mU~eCd)8R_OuU z#Hy*jPY&yCh05PAKVWJVKB-fy4X78(@zE$L@z^+`xX5bKCz?1#_V%i3uClfJxMMge z@IWD6j7T$z4S*hyTKg)Xd>T40_nbiIr^q!tXKa37G&wt1JO5ZpoC(0U2_w*5#y=%! z@f{;k{Nu=TDwve{O=>+=o>XSAmtI`$eVxTsSNbtk)=DeNl6IQxW*Ju&X@y&{8?2b? zD*;5I)8sC;J~zG==@PPjbsn%4ov)9j%xUs0GoRV{;Gq0Zo!QhTO>XXacG6cc6{NS| zi-a)~FsA92@ED`Wg^SdLq{=u;%1x82RDA&KkIWc)%r-9&R>2LL7%#p2erYtXq3X4? z!OXF`BYnteI?P?ik5bHZcsnK{<%{Zcg1aDE##+ug3Pey{E^nXF!ReqBiPPx*blKN& z#q@l&DGb#5rt2AJ)TWc4k#{;|`W+UOo-Q|#+Bc_@>9T|C^Gy(dG6J6&b3@KQwx9|w za8C;tdCM5JBFa+f8S-?g`g`iSShlAvGa%nte%5c|V?5`9Pt>UA)J*DCtBjZZs~1KF zn0#G^2S+wmAAqL@Xcx7Q+%n`@Qo5iW8IVjnnNmT9T-mrX%;U-*UgR+oO!U5%dd`&H z0+t{~Bse45L!)YYoPz$iG8JV=GY3~oU{&NqhglJ>ISlx|C!e~3|EGyicF?|=vPb=f zznUK12&$LH7w0Ydt=+KruSI!#un;whg4Js(l`7izu;D80sKPASQR7c_X2}WC)N+(L zOOBUr+#>(kva`H?Ha?Xx28r#VU*{_eXVZY$a#NR=@V4mBZ-;^j1p48)EN3*1NFT|^ z+_Eash1qfxGRiv6k)8a5Q5%_d7GAyl^_T@h>DfkhnEyEeZ^0j^j!OFqTNx(`oy=Wj zSgqSYqvpt#tupb5nj_r!2FwrV@vQY?Afo_Tg^gaT?E|%#G};~gKf2yLuBY_=6Vr5<4m7Y@%KK;y<_TZt?qcOZ~RNP`CH~v=qwmHuh*yEv!K>}c}&x0$x-q_ zUn~-k0Ff@h3$=3zx;G1AV1Hlonk{#)w72+c1kJ~QJo%1 zBD>F}Tt_+BygBuMc_jZVr$uauFrWg^f@3qBV1&?X|O}fAQa@?H-Ll zC3#WBd2&^|SvY6RM0lvD>hDFp=E*~CBJ~;@J?Y^*G%RaH-Xu4ZZY`o@lAAmD=P~Vj z4pz+Qvv)?;HIgF@QsQQE{sW^u^e;vHA$!z5coqk{P8OW~8Iy0c+zbce-q`a0brcO< zjKwep^FQ5Bw7M4k@rQgw>h&+1c{ zlpMc_o-cr;{;x#s7Ru4CRW+~S<|B-{#&G`+SZ<9Z+$cj?3!xMuchdERa-tM58kfjH z1Nb9`S}&4)OPSYz^EpGyy4N_?IH)b-#=sQ%eUa>1>#zGDjmc{P#1nV$#%gKbsvt{f z(2;`B|K@0L8v65n$r!q~NG@e~NADNO(bCam3STTQsQPw3AVlkdL&B`08SBPlunZNU z->~j1EX2XiaSG4WUQ}#}9AC!!9tL1P$((I~NM*9^#~>y|QU4_nXr^7GSxe;m(&@{T zvQ+*@Dzk=KE|Ygjjki$o<$z~LfC`yw?yBRDQ0L_^P_%t%sDlW5% zntG6OSID8x(Qn`Aq~v@0uL{hDryr!im2#Ym&wjS2Md+bHoWCtL=?cDCGoNOygt$8Q zGkshMMi@VoyjMZvvfW3sR>?k|YY%@e%8qd}*R{I4c31D;=D7| z8?U9BduYl!+0C|aA)sFyOTro2zD_P(e9nG+2H1FZ4_#g-N80Xuh^^9yQ?3(vtjEe( zzoW_PPVRzK!S!|*GSO5e)Q)Cd9C3Rb=)Y| zahZ$bjBwr7GuTi1275ppW`wH&)VlVxZ6he(=0E7=MsU2T=c&dfxWB&ar0$y_E*>eM zC7ZBaw3Bi+$xWoJ=Tv<-{e>u_rK3ZS*G#!I~>O8Ze%A%yYk|w)&R6b7{b446pxA zTD}=86tR=eZ-yakN?$6m1y0^SR#4&=crH9H)3Pn_HXdHaG%*j`^YJ)YZj~#_Uv_PRx{PL#bQm$a%ddz)HqH}k4E{xbhrv`oMt^OS3#2t$ zXwP;S`FGtSWrtkP_R}n_HEJvavh9$2xzc9l{opAa+4DRydy?SxFJCzG^}&p5&ffvbhMu0gH){Pp*=Fi=$CvM*HYJb8^6 zu_6w^!SSm?wZu%I>x2`%(f&X20YE?+wM+ICuVDV?Q;e(iPE{l>+l1$wT=4uZxusOc zpL})$UcSwz=DTHommYraigG4t$tEy1O>8&?%C|U$X6}|7NV~ez&E4{2xyxyW?wjAU zSuW{97qb8ht-6rw9=U=4qT5WY^>8W`-LNfP2ZAf}7^M(Ao2#zfOuy}cp~7uF9o+*e zHmfu}-2?Mt!a8ccS6*rJbgsrG4SVV9Ub(8H0WC3MX1fvWUN@>!>5Z3~P1 zKy~UNU4!9x!CAoC(-GvgAHo$T zQ0fj!JtBLRDtFfWdnn0|@x^|l-AC|Ir*D*hL{9WMIGrcNt#)pQs#DAq8whYcK1tJ@ z7Hy~QN5St8HmBuB2{b61 zdz(HUmjj)nCi1}I;c5-xII*sLPfA<$;1-HJA;;JpnxGAP;1>G*1mcP_7SO*ZV7hm0 zL9I^8_ezc!uQkr-h#Y{pXtsVf#DMorXmd7fkBu_4&8@JBu4c=r&Nmk`kp}Lu;g!SL z_5*6v*Yl}w4tC+ne9Fv`8&H$V~1^sD=`44(j`=S%@epGVMA|IJA z=B@c@=f%L*FgWA!HZoC**rX`fo}FgAr$eXYfa2xOW3>U@?)~V+De$O!8>sGSFq$Hw zfv4r_Nfihh;8HDqvJzXm)6#h%xW|a~aJv~TI|cEBz2>TRm11mvZK47ArzyT_d#m?| zv~*@?Rz8f`+Li?%t(+(9|7jLg7pL23V z!leX$8x35vWuZMjqpYu*z8d2PqJ!dFGugMz-@+ylWAG|e)|VM|1DGj#GK3#w^g{em3jY%vmM2M?ro0AyoN*&_n6Zpl)*cR?<#d>sKj z3DIp3QsC`nHv^I~Uxe^5djnOx2ngyrmj+yvZ%C!ly@G3qC{l^6INStAH!&VIC@L$gA0%1`deTmF3%Nw2Q4txh&Px5r_>7iJL@V+bP z_+`*1_q*h9Megce>G&(GVF!nv8Bt*g2)}dwaXdCx9e)G;zmR*CgoHmtiUz5uQ{4(_|%z2Pa*(Me8k7ml}L5 zab0$H_d{(hxUEQaUG;x@{+Lg#ufwuW12d8a9O>f*;Z zgxdvQ71zw=7L~dyca#<+Qu190vIBo5x{HNqkWG8;!cMqmC8>82 zgWGlj^~{xfmUiy_Ux@XdjZYba|LR2#bHQl7%qH)9a!^p$L0Db*+Du3=H66x5PN8`E z&>TQ%pHDE}Vz0H0=9Q|wfF|9O8#|isGzZ4D@(qbD55A1p2X%BCdU#K6D|PEd;rHbV zuK#qgFx#VK|HGOTwGOlWj}-Mi_xAE08ZDeS zoyI(pJxkp?_C^PKy>T2&r|N;zwBwQd)+QJ}PhjAd_q6R_tV65HRQxfhzvG{{F%Y|V zBZk^MmRpp0SWP$k@(pxI(W!;M!j_TCMyeB!fp=BQQ_*AWP_t@OHxF|AvH+T%hwUC4 zK-=>mg+~O?b1u6DkgUQhndeUpRYaJXA48G^koTL%XqPI780yh;RragwGK~c?{bG@L#sOyrc<}(oP)ql{)XHdLPcB3WF~D2G~)%( z*slw1e<4rvKD>fq6Bo>7$7LK>BiF!^bDS9h#C|PI*S!_ViMzD#C4gjRE4uSiu3V}GPCWLU@ng6>`NK;FkmoD;lC*FWy?!MR?J#fI zPtm<6+cU7su<>a9wa1+{>{bd#o?)zE#Y9$uIli}BCTn*NYS)1rdzM1bYI$5iaL%E)C_dvO@aaqo-afvN zMRguRrQU#lY&%0u-e6;<^`nVzaBSGjkM_TjFGxdL(X_X6qq=unf%6|-r_Ue&L-OQL z8G}px1`R*IFNd6V^aYzflI)d`SxlQIe~ZP-;9IT9@f}FY^VSsc4qEgBVE#MVEzD=q zTf}5BYxY#fX z`2@?wh1S&OlibmDTq5S0b|O~uG5lxigGSJ~PjaZu?v?-;V{l<5OAuZoAwHVqpPvW8KHxRennu4+@@Kh`O;5egS}iH(Gs1cs>cx94 z$o-34-R5&EZS_~Rp!Q$nDM5{JN{7!zV$;C{Fe{A&{^?xE$4LVK%s5V(_2W2ck@|_0 zuW}pZYfJX45J#b7Apq}#d(+sja&KvEOUnBy*Y8oiyUE~YQV<~RsvdZz=@&0`xT}Uv z&~$z;rjZ=@uVof?8O)bcykor9!k0fbe2w^zhLAy6GcooyL}m;O!P&b@lgaoEsJx{c zZTkkuJl2K&`38Dl*O5GnU}N63jz$)NWFE&Y8bvtgc(*HJynr3Wljk~$>r(wMbDs)# zY2p&HHHaRr(_kRvl^?0CJfDSq4;*w>lV{OXgYcCOIng$QXzg%yh`AYy>ya5puy5rX zlanMWNjsZTlq9N4lV{QhNqE>^!!e4OjGL&D){Iu-)))!50u)FhNb>AY?&iY9=2?Qa z4d3D@!d!UURagWPpdBSqi|W%rbK&g&FGul#mp5U74;BX}Yy9G^((us^1*~1OfwTqf zBi?X#8sYICXd*oC)wK(?P78iRH$56!m=!G47!>dX&5td@ARBbPvwG_@}+crd4o&B66T8O=72#H1$ zj-%EomHKf+Y0T!%hR;)Ii4F0DZQGbOEV!UQCdxBM&_~XSk zyf7I8@>C@ph}a&rbdxUbUj$vV#uB?~%j49w0s6x!I`q)m`39FtGj zCzkpa7amgaMl`Lss3@iXqAyL2hIF;KsA6M*ZO1@xXL^YeqJ>n{in^2#0n*7~lu<%7 z5XM%Fkw2qU`u|DyONc5`LMxJOMWocH6}7SzVba-_G|N^rk;b&72e#O9Bqg@76QPo8 zONzF`XIt6QU^~pB(cr9AcEZNs>6eaiBW4$t2(_h_s3aMh8L%3P@q2Z7Ejm|HRF%d% z(YKPqtN2$VoA~n7f9Ftndr>}h!$5cyCY(40>XPyIPpWxbU-4LD<;ng$EjRwR*QXP^ zZlER2FTgi5IMPZx@T0Ce3a5NdgJyjC2VXtJ|JB0Q>?{6pmMDV11iXWPOK%N3gCA0w z=@;kfH!XHLO84!BlTKXwUedW<6eo*bPG91!&G^a!V?XHn#!AQHjee~o=%g$>rJOFfD^Lut(!IYmF7UHY zABTCXgNN!arqf(F(OLKQ9za1q-Mr%%O%tNFQp^_uh%wx90?(Zt$-7q3O(E)*37!OC zE)Qy^F=fC&JYueZ_v+J=R80}fi^td1%a=OQ9Yy#!`03?H{)U-a@+3Jp3g?nGrl$x- zR@D~B)XMK`}!PIB3IKc;m9(u+qqsBDs&RA(JPCd7e!@T zRK3s+gWSq<&g~c*4*G$WAy-jnI2WoQ*S9`bD=2qiy z0MD)cA$n9w3~)a47h>Q|v07OD{V4KU*QGwCMSype@4ZA0Fs;!1cK=D)}Y=*0fysD%No6O=wPf+qx$R6v6II#udNOpY>10ArWznK zOlK!oY*LXr>Hv&yEc#^NK|+#7#-LW=4&zVi`7h6z%ZHdzp0g-zW7mk0D!kV>vT_kM zZHgwLr7?I<7&UMKi#s!sl3hfIY=%aBf*!m$F6pZJ@-rQD0hm{5O7~nuIjLAvvUU}o zt~EZQTG|H-`$_wFB*yTlFim5OUrhB~MPn(o3H|OWN=s^aTIVW)Y?9KnuO-)^2d*Mo za;-%HWkgV&hZD8OCu$=XVeU`ihm%bh!>iQcF8LB?@Cygk3in@W_KmoVV(Ny8G^dQ{ znAq?Ab56==o%Y$%eo_&J5|7N;3`;HX0@FKyo>>}!O3@9e?lMj?0>)s8GcD&P=?fmm z3%=@CeZl*2;XO4dE2_Ai+JnJm@O7&8lPcjklXqu^sT}prdzx8RgnQlnz^kR1SE9nQ!rf+hJB`e@{Y0hQM2x&Qlm`W0tq#H62U0&bY{7}Qw7?Bi z`PWdo<0ksXIlg^f6k|*-W{3~{obn_g>0PGXFWoTa(-32Ln905LF>m5RP757KmhwQ8 zIzoRv`p~?QF|4|}c{j~;7j>i=Z|J(i;T?-&_QQtp`loP5aK$X03A4VKuT4o3sl}iBvfhCRbM_n;jOmosSjly7dAE5 zhr%GKW7C3Nw8}#SO1;O?bq`VA?ktXlm?G_u^&?wPKtwSQYT+q{$;A?x`sRQ4v&?-* zH$6p^)a)I(dx_s_kG^Scw%0jFvlRDsGMR|6&r$fTj@tUJXb;}-t5quW@(1Z@Y<1aB=`#csl~Ta4R6s$s(Xu;d5fA- zv0L=Fw-{agrVle!obk9woqR-uqkWmz-{}gzGzAy*cB)0&eMFk{cTKA43#1vpmOA@_ zt+ty>>AqsHRI`9S_=?`r*(cQ95A1qHX`1E-!h6({Hv0)5$<~4{`-xWc&Q~~7-Et6x zuH{p^asoH!e4t6?MDq&6!#{wgWrG&q;X|4CH0Wf@>wveI-$eFdYlhh0Ur|vx2(F+0 zq8k1pxa81lEU+C1hjdW0{-WXj;mIrYgC~; z)~x>v#+y05+j!tOuU#^~!wVW$o~6wfw7R@#FWtFJh6!xJBLRIS5W7lqL>Pz zb;pCacOKLb~>n;wpo{t#G4$l|^@{K%@2@{W=~cvFm&etZQ6ojKCK@BA0a4*y&0yc(Xc*ogNvRE(zh#b&;PrG?Lk`fpnxc`k zr~=imC90Rr+HZObcQA(hQSQR(9uw#*oSzrJc9T%xS-!dOMVzC!sTfejQJ6; zXI5vH(n zrJmeEwIN!h0FFnqSJYFT=SO?$is{lCB)qK$LB7N|N~>;##N(P^`Ratxk?x7i)h>W_Dm^QtvT;ao>8KT z<6XuD7+he;fb7pS!`7U-M?n>Fo<+N(M7&`tnMaE{KF`nb&gQD`+F{4iPPF~GRXEuX zBbA*+1?q;1R)5-on2ffdmC?e#*kz>bP&d=XXi=j~0QX?}lzsXT$Yh$?6-lHd@`w@b zOLwhmZkF!>@Mga)d?LBbj_dwLGh#%5VGiw$0d;vkneN4ia$<6UX(sxG&FXaza&7?n zRQC`?G!W5tBL-+{1TT000W`CLXyCm1AUmqq0mb|t0|EZmR#R_KVFOV{x_pyt8$#yY zd6OzO6m_NJm8ow-5mB*9WpiAk^2|Ox9~*?AB6lulJk7tw`(+H?!MEjTE9&e{*Bgo` z$0V!IMQKq1xb~hc_K}b^wl|{6u|Vgn*7RE}FzVG?IuI*b8Nx`8!xxwQLV4}XIs6~BN)0Y4%SbFjX8 zX8tE+@#NKjE@uoj``(S(ybLXFBz~11S10SnVy~MVixIJcSwD@D^S?kg;}hL&3`Y66 z8kxt7@?H_2m=0)eSs1(lpy;@NF~}I&b=>N57fOf+e;wpR1LA=VC(mT9k7wfW`33Dv z5WXVDnN@@ndIEk7+s}^j6GUyB)ExHD*;U5fa81B7E^nduCTPDlfqrWO3|w`B_B9c0 z-DeJn~D&tZsq`GkKQz}DG+KVVgj0qQY;9p`x`}hYZ!^sXeaQ+d-ar5Bf*Lln%l@ay;ZJ$T)u%nRZ$WI?_eZ z)1$R80Mx!9sA)^#Z(B~FmDYZdpouL-pvQoLAt&Ys~+2WxW4by3|rs z^Iks)3O9^FQqe_IV1p?*F;J69EN2cPzgA+Db%K{AMDQ{dX>BXv<>eUkA4#@X*`Jc^ z;bjamt;bV-E67O;r;*YcSPcJH?bgERoD$31&YU>yq;*{A)0AA6&AY@>ZfoJ>9jm=% zyM!_PayUCX)O1`p&jjB&Hp5&Eh^11AfQnw@saB$>rd(;rr0KYIY-m9Wn}5|~4QWiG zh*3uW-xqygeMuA*9M<5#D2{ntN{q{R(Oezhl}fe&>c40}P1=YuhKJOrjqr5Zfl6^1 z7j^5`OMpcSwXh2hjVL1lu;_kP^OwogEph{2bo& zl@XGa>8mlE{N`&3++qbO!#XBC^;t?;29yJM0on`?*LUiy!%=L;O)X0EIpbA$B0j9% zhrt4BSivbRKpSoLFmC^7rZX(P5t_U%(u|p#&`A3vx18Q{Mr7-_jJKE^Iky$bQmb+_ zy)CSNk(KCRTM_Q+>i+)|UptZ<+lesSryF=ig_xTZO&!~bkWzn#fwm$1cNyd%Ub8O@ z?B8fZJE#}uU(<_r;ODo#kz;#Uz$Sj9==Ko%=D1L=_MoD3aQRYuFo4nTX$#7!ao;rW z8D@;YnX4VxUykgUF=pzB`uZY8XWaWS-R~K|BinHOOOc7%w#8+9#oU*D0U5$z-e3c- z@di5o*fn(w`ehiI_3S9BST|Id##lC?MIEs* z#c_jdM-d|_PpCvE5#n%q{dWTqy9*nKP|Hpt)h_8Z+9dU^0bD=ahH^WJ^3{EBenZD_ zCaSgTzA9?p4k5ZxJSolj{M+wei_$*yzyVbZmUUe$Xw)XE(-~&Fm*Lc@v+xOT<^htH zSrM0ngsWZsm{6tsrDi!WkxDtn7PpPbuP`Y+_K(GJ1j9f`P?#2((ZSA8-_{JEzdH-} zinrW#o%t_(P0jb!iJlMWyc(wUXP;h5Bl<;ZCGzS5onuXZ3h5#ugsc$`MZCW1R4m;$>(G6~v130-*%WvO>pQMSyfIve6xpkAse^mkWLPntW8T)IK2I=GsecN6Z0xikp> zr045sMmGqP-LKKvZo;|rsm!mel=6C}PtyjH8}v?<=yNwwT^yRP>v7O&G&ymAL=oM= zz@Dw8ncYRabOAA^-9=@ui=1GMJw@5-H5`w^<%xi40E{MH7OKs0r(}{?E{(ILi%G!e zsrTqjl1R3>s{1aUKBd7uM6lFg9EqDb8iDTp(o zYStaoiL%Pntf%miT~MXqkO?~=m-eJdJ;iXR$Z9yq0)G{*L~qPq7rrFXjvRUkce~CD znG4l{fD*0Nr#iia4?f$a7t9^!+R@BjB361mo^JON;Vy3~KwsF610z}(1sWlh4`|e` zmlV`nR4{y`j`$}Pdqq=v1LB9hqHVo}Q%C!nj9tig6rb@hF5{{F?usnxpi~I;t5HRa z2F3{c-7O6n&&^x;c2sHL2Y{x1`byTV(~e8Pq3gluBJ}SRIMk6@W+uO21IFS8@70%f#qr2pH#OGl;Gjxs7)UcY~S@yh&S1+Yhpd4Txek*;qQKico{8_ zy+<}n7HJWVhVdhWSqgw92e(4gy*^@@?WQ)Y8bixbCoZ6AeML35Z&9Cs+C1Hkko*}N zZ6V9?+GMNM=yqT5_gVAkOJ7iq%rO+zPt-T`qRIV)KjK8T^b@sgt#-UDDnNiiq55?@ zz3hkezqFm)`UA8!Z>Pxqq9rF(nAcxi!_C0`20(w^`8)6-p&%y;C$vD4b7Erozh*AzPxl6j!Im2#7spcMJH>?t4iZik zdQa6@7su*ACCpQu@g5lekA0qr}?kHr-y!Ot1cPq;fz*NCqbF=ZEiYI&8|F#)X zwRmz-dm#CrcS3-qr`@q&&PbiO!Kr+&06`A5AavY9}aaU4u%*=KRBv@+ar%YE*58a9+{bl zK-6J@stZjTEkXjCjRklbgA?|09r&DjjD^Hpu?Mp;r{;L5$FufnNsmU0+9mi)fC+20 z^>ivfMufHSw+3^}Yz^ryI4qZO{v;x8VE`(`WRTRLzNa4eANZOB+}|ZT;wC~=4ZMc_ zHP>)yyogMDWNn|mnlapHIhnG?h`NS0^lpssFJZrr>3SX{KtBo?3w!eicS;;9>Xhs- zmQi;sgyL+qs5C7d3r!?{2)!LE;>&R+RSt);g$*vh2q^a5M;AQq%J=WKc}cy-iIWHv zs+=kU?5f^@!~>C-gBS~_d#dQ-S+GGj4nFM9koik;qQ-N_0x1~rI*p+FsiIn{P4S|l zMj6qct@D$?1x+MaGeqpa#6$*R1rM;QyHUWr`Rp?2aJ+rY5o~JsbY%LQ%vN8GNV_L6 zkv)nsJC zKLY&=AIG3E{8H!}<8DJWCx{m9eb*z!O;Q4OxFzm&KMlFabmYEJy}40ih^hgf$%%5* zC<#6^aoDFK4X^Q4zCTK=(V~YG9LNUFkI)1KBo3-b4sEz8KPn9MMKSPJC7L&zYi-=7~?TV#}h|S!{=>@(I zSe>Ik?;4xApP#F(xPR-zgnz`Qg+D&G?tea~Kj+W!bG21B?Q{J5zn|-?eNO80f>vdMZB>3j_cMj! z6aX9K|Ko#3XrkZNQ=n0}cqDbzVW1?s10EH2=#=jXV!+O#LUmX@>TMJO@~JrYq7z`a61deCwB23^k*R%+lYnlMo*2Rj7>UH8sN=ze{z^E0!vQQ zijjv(0MFH?)MUCC6n6eCocBQ2Z?68xYpvYtcS_rBO?B>@{{G7WQ3h z^(AC9(*o|cq4~3fkFtD+m06?Auon>jL1eIW7rp8HEK#*&)m0cN>kd3t1d7ZSRSf&7 z_H5y1u%x!Lg|B?k8dkb9_&gKOBK2h`8E1Nb91>c_sqOk|(%0>c>WMV04>x{Z&-)M|c>9)Ac!!<5KC{9N}U} zC+E4MivO^2+!;CXG75Zk>e=ew@R7lh2iZX7k1KH2Tk&p?- zF}|J|I8hM1>;NOH`spT}m@7id7FFdc`KZEgEoW@y#jbG=HCEpwmwBR^^LA4WW3W4# zY8COe!%a$>C%hcq?$^2tx(U8ywA}D7&6y{{n~b((6nU21Ikcm%h5d9*X)=a?{=_!6 z;LfKt@LB85N;rpBvQ}hJ8={Stvm-KXK&-(&{rkpr*+L#9oa~(OKB!1f-)l>eBtje& z@Kaq#K8odFmV4BKj06>K@G06%Vp!^W7&@_Sdp>FsQeQXIC-J@f9PG7;*zzW+(?PmX z)rhJ(xeEVY+cdyC=75lSXoWe9M85@Vuo&u%FP!%OWPTXG&^n6IJBmg}Y^B0ty(vo@ z=8OJuPO<+3D#cJ_F;)#9!CLTG07{M;gx{HVzdvF?InIC*$gr^xQ6CH_1xy&9U!$&n zh*Ax&hq8W-WDu~l9MiDqiSEUJhCbqqhfZk$ZHVu+{PM-htckH-J%p$fi!(;M;s3b6 zxQqr7_F0zy(7`{1yVw1ZJO-S-;hP%^)yt-$4q3O!Ef+Xkp4N zjVwLS;*N6F@^}irp#7v%j7c~;LaP>t>H#SR1|;ZqllU<-24;%O27TZ5$J(~%ArDN^ z0ue4n;DpvfQLdzF_7hb8F{2?1Arv0^NXr(AnELPMYuo$|cX8{Rv&KaS3J1uL42KQS zINuwxm8MFb(yQnEs6N~U_q&Uk-QE~^^Y%~SaV1^T2!ML;=QH(cGmRDVd$nx`7M{YG z`yY?Zv;vfkug?rUsa;?lvble=@|90$uzJH@Me}5>q;E%5> zr0a{t9%=d+nz2N5_I^H*mxx_NdXV&8QyJiWmvP|yL~>Xvx=Q^f(vYPhszIA`tW{k{ z8nZa#7;~UD%9&9Y`P5NiJcw98M$`)qxhR?dfgq{0sh5{1vFNY&`EUY#UMkjm^d6@f zq!g$OFg~?($l;XgU>!IR2AEqw$Cn{0XUjNpSPuPZ<#?*IT%;OW(EjD{joundkCuxz z(uA=TzCt8O6UWfB6{3q_COusN@eA73N)cqJM9o)<2#3b_P+U@L3qTmpDU6n{6tz7K zcp973^83?QW3?i5S*_B;vGjSR@Tz-+A49}7J>IU@@-!7!=x<@!&>GFwi|{gQ#YtnS z{VFWptoL+am3RdA*Yec}%FF6QIjcpW!HGVsMl9Orx72ctSRh^aN`-4+UfTEDu9Z+3key%8E-OWL&$F)DGf#Cx zA+6ekT?SX(Bs>j?^nR1*+`i3NMxMTHe+cfwMrjf3n!OZQ)m9CTVEo081C2D~{V7j> z59iEeL~640e-NqAineY>5I{pn62QWCotc)lr`MZd2|Rb6BDcU=bYcOu-vV2nTRob& z1-8(6akOrWsA6|uB}k#31ZF>y<)KPR$0=Gj?c4F@`ct{B2m`K0jkk(J_EAs&yYa!~ zyiK&I-}9Umg5~<-=wiwcHRXz?ybM;)9@12(-c5{^HtzxM@R;^^LqdbN))IsQkZ58Y zm%GuXZDOKy{tg9hhvl=!NL|0}7^bTM{@gUT0d?69!`85!=mH$;ZYz%5M$(-Vs)9$l zqS}sDZ5LHxgt)pL{>+#L^l>{3t`-fb_734zy7dT#HAFsOg+tQDkH?@4YD66xumi!m z5&zJk9jII{hKhCw5066=G>U!ju12v<&E_9L8}OcP5{2&+d*r;v?Ef7bl5tn_W_*at zD)uL!wD#^(tkBt~e*o3sqpG0ttk~^84+_N|ws?T716O$PzZE|1rB=IOti0?-V|F2y z{82|*uuI&KZvRU|cZ*zU)JyPWBsSj=)jnR0+kM!Z3_F>_^bdy1Q9x_6u)wg9V*FB-Tq6wo>w8fJrj_aaatL zPHf96egxw&cv8Yq@sB~F3dclUr#WZ8L7qq%#izivtF7|XZokm-W5UUP6yoDFv|xK( zxc;zGA|7)2c?Hdzp$-fF#O-mIjPLdpv6(GGVl$Ki+nzJj4)ov{`0ew*$l*97u>t)k z@VF>jyenEV6st8T@wiB}X}VaG0*}0;yT?Uo|?auoK6ZayJ1Ti3N=IL#_kk#QmiYreH~H?CAIQ}8Jr!x*l*AYI8!^4GY&)yV}Ey|Z{JB=k+-Uw^;_rBC6TLdbL2kEK>j!R^td5F5{ z8m-6{yQK8?)Gi0(D{4cBb3|oiX?m6eMl*jAl{$rJjJi0bF8bSBP3104fq)O6(*9GT zqigzVPIRQDlg`D!K$(5Dkr@*y=roM#jeRNUG*s^s7isEg^!Zl=?L3Vrr&&H!_Kav8 z;baa82_8@r$-+%_Y1M&v@FVEEm87!fGH`*8lsD?|dRq9hK@HsMy;_Xco)M7-U&=ot zMo5`Cl=PRV(zHw$P6qhXE~AMST>Wx4#(YEsd1)H0I7gK@ldXHK+7JNVIY z5b=}1mfM_V3BJ%n{@SPt)idAU9ECt<+Sl9|X#ImbQ1}Jm*`sL(95K>@y;HvOzUu23 zn{-hP#+&ag)V6r3Ee~q&OJ}^~b#}mT`2YL>urMA$3m(@eH+_&sF5ndE(F?*Y;Cy>- zlB;IpCAKC2zrVYIaXdZ(9q`+b04jD7zU;lnDEJ~G@8ZykkulQLWmztq@TXB1MOo{f zb1-D1(^6V;Q8-KQX49UFBC?h_o|*=pqh5!<3femZ+QQj7>v*r;$1mn9aly=2;GI6H zj+;$^m&EgmcW3>l@pc5{pfMXW(l0~%3VH_*z-hE{jppwlL~^ z1-$#lDH?tSNV()A-MfMixVqld^{S|0-h0L?DztMfLp!btC*fC)kq-gZ&)6qes9yV> zZe9gy-yOF5nkZ?IzJ-y)b?E7by|SuaM?{7B4&y6I4Yw*?ibEsOBv-9x&HfwmRA0LMH@5HDUNYPiuI0QmGbspPq!HI!18~MS*Uk!dF(;5dD~ zL6J8_OIPbeO+ZR#uP)EY+EItC8Sb>@CZwC|E9uKk;q3SKdRb zM65Ave5|1eR?W~`VvrQIhc@1VZt}1x3#6>nfE2+HKJ+Lsm!*7$i+L?{LUc&zgs6cV zeYhp6!)sOPwutlVu!0rk&vAUi)-_g_>q6;OyRFj)0fz~0G?+~bZX?QO>U%nI8^VZX z7Uka-LDgn80my3_`xN=B<`2>AQ9ZzWHDyN^WWs9d9%={mRT+x^N1SYTdzT5O?9=m5 zmsw~8P7C6v#v;cg{0~WuOF9qB4DVz0W;(KTaL{?^L)RZ9H4kAs$&EDrYcSIIJMf%k z9eSycF6bTPgFv+n?g-LGi*htPOAUY10ex!#9lpbXdXwp&JEAZ2h1k2Ii*&6zt-lK$ zXE6P9S5%cF4??=g@X3!gIVXdtY_3=$O>9dCaz$LlTF!`F>xiAjnc~cI^%bQbc7(6~}Qg;6q7g3cM%kLA)7sPxJ|%708P-+JW7;UDZh_Wd=W3#5)r0JA&~t zs5my@=?Z-}I5VJHZ#voE7iD?>?hDt1nn7&tn1nXGdE*h}uFf`9kLT)-q5rZ(R1XEl zi|a43Ea=@+vw9%=9ULPtSun~M1k&vLFy?QqP8aUOYZgv{4@7hOf+`qe+6U`la{|8qljKU6{W4>jKgizqgBZ5p=f5CyGLLASoPW-8u?HxtR7-| z5~5Zy{fbb1f7Eg{{R&haOuw3e;Wm6Ess&%kf}|PxZwhkJu!L~}MgHZf?!&JbJ|>&N z0LP{eXT%!u90zr$Esx-&xV=fUT205@8~=(@sq?zC%sS1N9ScBl=QwjSz+S!mzWF8Nwm`?>9?@`$eF1JNdB{nhCGIYHi)twi|{)C z%(F7vAAqlFk$REZU*2hJ@L~1#A{}IkaiPi-9R@za=*jEjPF3@StD!nI$`fbZ_RY02 z<8@50X^pz47MjQp7s~ub)m13VXP(d`Rg|;7T%N(zay0Ew#cXJV4e}8w^)`ck%@@B& z&&$)re31BSbc++o{ zqd89?p06!OIZuSUYn%N%kQCT^q9T}!rR7-j$z%iDs-B1`(yo1!QGk#N3))-&N_}o7 zSw0n`MT1`E9Iq3fG0m5)L2CRGy6^^(`dgj~Ax+y#$DWEfs}9ZJH8|@_;u$d9jbfg` z^f6#D4SFUbE2saC-8MQ64X~g=pzj^bjjSfuxTOVi{c#E^~{`;DtVF#{$9rg6_ zBHsC>Xyu#}!)zsolbr&Xt8uD1!1|>PH1?&a+hni{gq^e;1CML9$Md2DV-E{lv+^zF zc7m}|*_e#SnU=3Ib>%XZamFx9$Ak9R4Yd`l9gJEDD6r}iO*XGYeb4*OET+Jjc0w(M zF7Y`SX>dp?KIs!5vuiB3vlPukd#!rzIhW&HZWAcHxc!?jNg zh5%2FBQZL)>PrvaVXUzV)qF1+N*7j9>U$CBT{)b^028JdgMAk;wd4%IjAi3)m-F_ECW{xU&#p4-EzC%}3M^7n1&2G})QHIq^#P&m+uKvb2jLRbvjawIAN>Kn zo#Gn;GDkaWf(^=hv~m<8PQvS>R%|9mbSO0SgQ(Q%@d5ra8}^g?M2GfeSVA<6mOmqW z0WSAMphm_U6II=()#WU3oTO?rl&x%ap1?hH?8Glr8za;MK&nPj@sA?NH%M!3YT8O~ zTCfQf^+!mJ?jci`kD|3r`F7fpA1y-%KO)Yw%&%nr3CD_N_NJImBHZ2+xF4(Poj*nzb8A@9^*+yS9Z4* zsgOoK3ug|F`7Ca_EYYqz8|$ggefdSxrXryBda9+rkpCCql{&4Lg;|H7BR_L@RTrGu z6)QN_6GNG6V5OLUX5a)yk(%CHmy@2^AQ&VA7cv#GK3t@_;dykXUF`|XJs^4{u&5aO zn~pVn?o3@cM8}#dD8wgy=0;Plzx2@~TR8w=@v*_w0+jLBTVWtaw5~7OX@cp*6$!iA;LEJbYn&@P6qQ^##~Y=E9z5iAM7U; zYE6*u(Pr)q#jDgLZUx8>P)C`51*(H=sH8#hEAdAXZ!&k%lsNyGAcc`{KVA?vS+Z! zS*Tve2|WvCQMI;STD~F za*noHDix#^w)BrBMt|xd6)UE&iQ2!I(p++!Mx%-;RZCwf0k}$P>B+`#oYGZ~qnzo4 z%jSwHF80b;z2nu~F)UgtS{Psqwo+;vDo{%+WxQb|UA0o$OW%C50Tjd? zR~&H@@@MGh)Em(V74Wm)J+vGYuxPNCqB~47kbN)bRkVHEBWmFtI&7mHD!EjD-qSwd zZ*}&atjyxdXoKB6SN0zRa-OT7uajb{)RuB>sj00J;2rGFgjI`!fd-^ofV_S_Q=RV9 zAGS&v$0-FLi-MkMr*g5Z4E&RSr&G2{koQhEt%r3Q*qM4*`tzAO`yQ3CQ~FBT(`kyG za#^}uoH~|N);s)$gEjgg5$0_p)3TiGmGP2O)>M{SVFc1K zexABUuRixj_1329cmAbrLhh9Uwb5XjYq^bTL87743GEJMN!;Ko{wO1te=k= z+Ke(4#Z|JpMQatMa;mepxfwV~-?R_#QaTm%WLeU(6d$3&fu(|0x(5-lNvcOM46}UR z_-D+#`j;nf*Jw{5X7UQTJMFP^%nQ)VN_10VXZ(T zW@a2YQR*G_b_BZo^MzJ8Du37??FIWZyNy_qdDDp+IVm;FzZIF&1Se&hG_VTUmjW`q zHK)*0%2_F=Az77HaDKKorIuFe*zTCj#H}M})|42^F0Cw<_GZv8&Pp}eDoo>O8HM`A zA&HG?owMR4z4oEMoRvP(g&I`LMe%l55Rjc8$`jWY1JvIboY+Ov)Tj*&cTvLad)LF_ z^fsy5pS|h0i}I@!F@~zRD$NYVDAiRd<>=oYN6rQ!_#`fKbSwx8?q3b1^{z@w>w%#f zyR;#TGD?f~HLW=8R}20tgOFC{Ut>8A1ha=gph-5r4uf31WINxYg;Sh`>gxayS5OOU zHDj`NA9OFXl=4B(Cf!c)(ZV6o1tRD=(Y7**htw&SE|pPy9sSY1U=}XP%)h6dVJlR3 zd6G?8rD0gd+aGcNxE9`^of1UHnDSlZhyit9+6vQ{`F~#)3(=-95edA?DwCwAgGsn4 z^=eggz#X3K&6mJEO%@)$dQhz<7-5l)@FFe>#s6csKoU4+2d3u4;xxrgX(wH-Ne|r= zFBdib11$La7|9qD@-aI8ANh>j+?C*veVwh$@@rv#wC&M8qIo2X)CgPsBOw>`j~u!A z^CPWnXsWwX!ElduxhoZ=vLW=qU8z#xbvMbZQ-1c(@X*WzoQ}jPB%C^lM;J43WO6Y0 z)QMVD+d~O6Os3%;pu8Puhlk=9Tw)0JB?7sqA?+}=n2UoEx^ufuG=3c~*ldag)uMTr z_T9w=1Gb)ubMS{v*o~t)h`}QE^=}E;0e&}N#kFH;`0jB>pbqj4Vbo%miuSZ3p2iwS1*jfW#ak&Sjfka0Z=g#04I1gKgiG^A(jIT+ zUT`#S_yIA2kw6QRP%X~zO~~4Bwy-+zRLRHoWotFzpKM_f12SnzVySqErLIjrx| zi!|0>dEP8iVjt!KU+r5pPJa1W$hx30kKJ&NS#u3G%V_37+~=vc;U}t@sf|`hyO6a% zK-ppN?{XNHI{V!n%4yE@_>5!GfQk(Vn9V2q+V39i%Vp$WnNvYISZg$lgs7YZ2Rr!n z-DohKJ*di783?)8F>G+_i|QPue=Ol3ed132|KJ z;rTqa%ZGSA`tQWkS!xyKlR>m-V4>M2aMOwdL<0xAIC>MPTq%{3$~KF4_E~Kl(;n0t zA0}HSyQ*F3PLSd&jaJCKni5<7B}UpfbIcddsEp`C*6ITk`Il`}9Tdl&k2DU4SFccA z(2kO;DGQ|Y2g#wj;x28$RR+}+XXiJFIOluzASI3uGe=4kEkg9}LEIvvc-B5}@MVz} z5}nELoq3QgC$QG&Yi|FZr=>kp&G+%NwBM|)O~N_X>dMXbaky0w+#YUB^Y7j)5Xhuh zD|EJa#`oQ0An^Eq)(q8Z9^{(pxjot^wBOB-)3X{7$UMm{Sn-CXCL&mABDue%8No`W zD)(@|BQE}nDIXb{J%;y6y_?0-N3PoQ*hfg3+4;6$Av%z%E$Kx^`S})spuKyhAK{_oTCtXkh$f@a`ARv)!(^3tItb$NL!Q%JGJ3xzby|@XlA@FU2(BWM8Xu-SGDv%hQ_s3e6>0tlnpYQHr|zZ0 zbs@7x*<^jLt5{10aNS7s@u)^tg-9jB+|VRIRbnv+e#u7M*YuUtN&%469))hUGWAHVo9=UmbsclMzdjg_*72(pV;8W?`1R`JSjcFn_e zVgW`L-kQ{SrIH~a%PB!QZ7?*U+$Ksr>CkfWY^sdKsiGxKl^N2Z8Wh+}aji1Bvd%SN zEHP8(R@Z0QnhPoIGuHdAT^w<~91hWPpp*7(!X6DO8o zl1zFLnh zxyKHs9{u!ZFtF%7y6NS{-+P3gq@}W>!j9`E=vn^o&(?satt;sF*2?UPTm1F)>4TosgO&C5;fQP1 z!9`ym6$KUw%qSsI@hRTX@dF$*Pt-{(X;h*zP&)IK3KEr897oay@c3aT^=zYbkTRp` zcpIg&^x21e+A6iAS5eflty0r4ie|TkB6N4kympG4RH%?gJLQ?Q%r2{Bdu6*pdN!4g zc2Fil7ySR&`V#n>RD7 zs;!-Bt6~>xsGYXfiq>|n&_rvkCGYn+cM|&hzxlN0-gD3Toaa2}+0JvK`)X;mtJW|& z^fh&8B6u&FFbZ*GamNIcWCYz4NQIx+Gl@Uxs|_PxlYUwo)8-bBK^iLB$lqM7Zo#+r z!}gKLU-r`y;0e*MKbpSSJUykqHb#Nw?!f@9oZ`m|4b+CIe?;;z1GNrHC%$i>mQ%#) zL-)IXQm7Z-F-VJ2U!3F525HT;m%orrF$=Z|q7IO?g)eV2SgR7kexwsFzb+u+7=bve za+YGCu^~x3OC+h76ywy{w}Z8SD)pDcRRX7s$f!bLoG8ytc#?YT&RO8HZVc8c2YiP# ziU~%B+76fuFya4H;H46@2I_M+Z=0Z1DeL_a?)!U-1!&M=Sp&?>DGHyNpoOvC#f;T9 z(5xJ@CcLpISvV|wJOScLhsMi>XzOgliehVWPx3J zLFH~V=HrKIgVc@R@Lz{w`9SkL44cS{M(N#$Y3-H3%?%&tMfMA_-HUVL*c{?}OV!fS zhJ5#MEw-5HEs0JL&*#N){}I~Aa+k2~&G7IJvfYVuK6qDPZv(z~1QxuhI?ow_P04kL zR~@N^eAMVDZ8XnCKL>3p&&Az&FO4a|3mE;02jnK;eCJbQa!dx>mKQLW&lst-Q~$`| zXGUrbP3`N0>xoQ|K92~+!Tm>RT~z%;K6I287g163B^!qW(@uY6gzQYpkt$^koS#iA zGD&i#rnD(|Id}rupa*y`N*kj-t;c(f)+(1N1s&ubY8x9P{G`G3Pw*FS>hgu7wZ=ux zo>mb(qtLdE{QPLGLHQ%P6#f=jN&4LpG7xoQKo$gZ>xfH>AzVL6PSEn~HY&Bnl477`;Ooh9H2U?ER@`m>s1val*Fkc6Ye z&ubrHxzH)V*gLA1^RU@@Sj=j|ca7DK*wnL-VfHnauybtoLo3)@qHs9_a>w7sw>6$` zURaIqeY4)hHwV5+|9nSbd1AAmWDEK_%u})_jt#w6GK{{p^OP)Oavc0`(F*jr4*y`B z7Ff72J(uJkj?-d`UZ`!1{A6vOHV!-Vq~|<+oE8%0q#Hjo#GdGP0Q1bwq?V8Af}B)< z15@T@SRnOLI1;%4gZtyDA;R(*pK2Pf_o>F!5D(HESXIm{1ys>K#* zRm*7qBaX?e;`bH&2~kTFZ$4h@sAkmQ^Tun7l!3hR1g%Q*&$lANr>jkr{e_Y^Fvc|u z7w6rX-b32Es#Qlp*vbO&lU^Roa2XpX{93S7I}KS?WB-DfGfiby2TUcm3FI+4%!`W=cEut#3ztC6?M zZ7L2Kw=AZ4&TUfCk`vSN-6Z?NncUr|Rxtnz^}Jd~1`m8RrA@-3#h01B#6{sij)ZF6 z`>z#1wc4KFd9jIFdEf4ZP~)M!yzWGhC-+`HXrflpRQfQ@E6RqTSuudmo2Zp8A(qf_ zs4R*vvZ@;Yexf$jKWqsB8sSDiIa&q94U(LQ6E9H%rzk1pHH(5L4cz&=9)kXk5y3t1=&(tko*w_)DVT z8+e2#Yk|cVS0!NK>K@^&%8w;$U28Nz$~))pYIxJz%Gv>pED?ZrY6vXEWG%2{bdFRQ zgx|p6L>3=5S*ua9iIEoe3(|hf!X?XEw~~pEs8vG=wx%h6J6Q`VYq=Rubv9k`{OJ8@l;Iy$5$mr;Mj?{_7i6*TEjZA2)Ap%rd{MaiUQKBtGMVH zEB^X}{0udDVv2@)3l{UwQ?$?)u1c7mRr01N+$$9g>D=9X2*!mqm=OUcBNF9FQRHqO z{!q^QCQ5Z0wI1MkDOzbIC%yDEt-GS&oY!=yc&75T)3q)=YK$hH)bP0IEYZLDL!GLi zvlb&LYS=hoZ;Z-jfVN@dI($j>($7M+L|ZEm<^VkyLZ6}Er=$@^QYRj3)5)c}3Ix0zgxgBg~TVB`!fPndQfI&F+kZ*Lr*3_3jc4*z8&S{&b?NZ{F z&4T*yp8(!x78q)%J!ff2>ivei#%!&ox}^^9JR6Mk?Z)Y@+4!vf{u%#cj+UZ+cb5-v zLa8-(Y5Ghj%qU7b?v2Y>{_&ZUi27y75~cY(oGf9;iibuL(2b?Mdgn)9?73K?{^ z%-0U9t8ege3$!M%$81=jIhFG1^%rWh6s0TQy-2I0UY^VEF9O+_WP1ehd^+TkYfwdv zkP|Klcm~h_3Txiu~e&puVN|eNB=rGTc+Jt z54}!*vrHSPDw*m1Ki4`b>X}LW`!BR1>hSZt%nGd~uBq*@0z%YRUg=v`XzLVp@4U-Jg5!3~z=w$*5C)_LytC0-+W*Dtjvs$(8+w+40IJj=JQ z(OQ9f`Dcwb0zN%`ztR@5vv4$sh9RS;E)ZFbb}!MMt829(!K1Dh_Dai38Y-s!k&8Vg zDN6iuTC#ghh%lZAt@&+qxhN4ni-DSrY!)~ zrNg}G7Kmw^4)Y;fphLLTg&)|W#gyC)Q!kFBj3c(|%|ZUbR_!{JHjlPyWk`V82El8~ z0X}#ey4HsCZ9v*D$dtE+^&@^Iw{5Ak-u!lP2X!}LQA)Ok4KJaCe}@q zP%HJ0NhV!>#wp(6dn}W7{K)s(4E4l5-sT5vLZ9tRcl@A5DCz>i5B#Y01=mo1hnB4F zzRQ>H&^D=OcBh+v(n6F9Jw`$`j(ykpz4FBSFrbpG{z zExPni6zvK_3_aivniT_-4HTVj@HhLhep_(c0j;VsD*fvNTAWfms0(RflCHQ4{kEUK zKBzS+yZ1;g28*Lk(G+fpn2vt5v-y0-+hstUI#`O&&j9ovcjjj@!1n*t5|;*Qaq7BY z9&rfj@&kMLz(d+mC6re?tSwa+UFQ1^!(w$Mp5HsHwNW)uyYPHu53Iw7AlJ)}s^7n-BwAxr3@$;Gdv87j1avF>N`y;|w|uwsYmL z{DYoATK(w>O zkQCH!Q8LBLH9X*~X2sFH0cW+(37gJB`>~3LozwnQ|6R@5d99WD>?H4bUTd#jZOOkq z4~6U1*8J&t=wGMuzzbS+Wjb$p0h)^3pLzcaT04cMZ@i#2Qq+=r`K^oEzv`du`Hf53 zPNiM?;$JjXVP(3JDs}n@_`Z_j5)VtO@QuG}?%@85|Fa}|WFez_;t1k}u_Qv%dH3J6 z(M4T$V#A&b`!Rm%H(>Q0TugUaYoyja$jz6b{+quueZXZ?jpyldl%+fo?VQi`&*?j0-?F(hvvU}JLBDv!p zh+ldg?t5QzkxJ}7#uv}`-v_jRuFap^*B&VKc$Uy!!8mqZ*V^>y)0yZVPJo%6ZJX&n z&xy6!5wZp(!Rod(6DeQQ=eaUL?+Mn;RcPAc!d_-qFWiATGL(iKh?Q^j+x9taY^Jm) zC@n5Jc*+B4Q+@cx2ikfyXbY~v(k8R;g@r*xr{bLG=m-)YK)TVPY;Z$uEAcW9wZ8Q$ zj0C4kv?Y$PKl~Zp4s7m(t0Tf-0YS)?2V(fBw|Tw#gCgPn_Yzfb{_X5TEzrLuQq6sO zBl$}tr?2H_9%^MjDvi__(Da@ZpCKmgVqzWY;c%>FWcqzLHHF)3p+kEho0AQjJ9QB^ zNAloD8msf;P)~2j;OWUC`{R7jMQk4V7GdY)p=R3Y`T0j6msz~xUm6ZYJOW2FmVft1 ztIVVR(smXvJyi;cU^O4M;!sf5i+|l#p1q+PNkg5-u;4>Pk*&E1IAMPSOXUGT5pkvf zT?#Xs*qwO&c5e|vmV(+{H$LKDFMMlH-`1AtW>*2Oe^I z64w?QlY5a~>P|C6m}7V`;=q^Z_5a3fkLLsa)`H89k(rZviKE!eF(dH@y@F9}=Pkbc zZ?KpH`J=zJ)lh}b{YRTz_I_b$dSN}E z_5==0ZG8FiCs6H9`kc>xs{N#9jO8t!Y2i(#A!IXLX-PV-KNeaSI+xwf9rOlW^b+Hc z;?aF(iq?flIhq522SUBN?wR(X>f4TAex}8jPiufp9qib&XC6Sqi-V+S@!E^GdJZ0I zD(Cj+&{h}rWPJOSZ-1_pQIov*$>$opm{nf+g~rtN-n_{Rt+Mx>ycfLB3+R8FF5^dD zXjN+-4=48KzBus2xU{-W9>seS3IHz*cOSHFbDUW}N_99V?`Vszw zPkX7AGk^Q`MV^i-j8TckDx46=N(`NR_(eS&))C}30J#UJVDUm?2`R}a#KQ2mFVe5P z)Y28j%on`U$~J91$C%yoWTsg*!I)i~(8pRu#AV^QoGW3Awd2?-Q*pl@t(r{nIluEt z>lXUsY{}FP7e!^^r2f>|x4-4eBetC+XHU6<_@LKXXh7Q;h2e8}F>zh4#a=u_0(kpx zeD!PXd-cs~-sz3jS3QVu?{Bm@IL#69R;y{sUIm&+hX@GOZ^G02t@aCCnPc*>%iS2s z7v({cS-6t#&(lImj$Vo0M&2;;_UAcyP~CojG#w`0JmI^v4V$glmY!uj!OPZASaR8| zUr>REMu9bWp;1SPWnb`J3d^*e0bTQGdF9OERSz=^lMcczFLMuyiuD`Cb2ZCwpl`ZZ zW<0bIVWg0*MAXfO85R2Yw0S6ja8tn+=Vimn^{5YK3p9$ZsfQGsXmWYkh2r!EwCC+s zy=-2t-pw*w$%u1s-1-Pc^}y_S>D&}xpldi%zLi3c0<|(Tsb7ls0 z5`VavhdTA2n|VC-Jb>W?+A*0Gfu>+_vREv*yejQv5-(AjFuW3((c z?JTa?UxC~eqRjT!cq$7tj&pVJLxpBCccVfdUz_~}t{?vis}W{vv;F=nvpo+XQl_I6 zbcm)Uhh-&DYA|DQ64p8U#X**T6Gj+m8c_ z1jV$i$UtnE&5ts`4GEFj#Eif4%g@JWd4y$FK}BYln@*(Qus}((T^ibbOb#exTm%jEFVOl9?f{s@Zn<9NRDxJi=qWtD#jIO^om@99b>6Ca@K4m&MyC-Y12F5D~)6?g)Y-SEASDDcJ&F0 z2?t!RPe&+N;I#)=;4O?pAd2PCpFUV%TBsPkjM$&4WX6!_PecmYMHi&Yly``4BTLpx zB9HaZj;BKB;bAlWRMlZK{#8}jxqu5B05`feNm4$V_>E5}Ld;PN3**CxztWNCll}nyKQO!c zMN^+{!nA@}`62m_3B z2Ezw_79YX;1d}Kl`2GU0`RYYv6`6Bz3jj)aik5$1P%9ZZr=)xVnnu1bIZ9|=SZ2sf z>%a>ys5g)nhvOz*3Q+wE#11r2{RDOsgOHHUa3-#=HPW|Jx(ywAe+f8n8MplGz^TMM z-R&v6yAV)8DyG}vA{$XLAit82k-?mqHV2<6i-b*IN=uzw8goWU+c?)CKfOC1I=WIy z`*|?Z@pp)(1o!puuajJdSXogntQduk1hr2U-CMl!%}Yl3H2d z$#1a%aWVU_MEXWY9!~lbH=77oR1}ejPcR_Vaf421NPq8IHe>Q7D(K15nUGp(fmX6h z=T~e>J4r-=D*tcYH>qxWGDv`98^#W$LTF65?U4mzk@`izfS&z;=JW^2D$Z4%QgV$1 z`IWeG`iph$2*J@c*qUf693i)mW=v}%)E(n$;~zttMNzz1!RKe-v&FqcR&@YJ*QjJ3lCVS;hFy@#SrX=k1W`VyoR#9|0dhcvDyN-^;AoCa#Cd^vE+7O+0HKzIEn=zX- zR_dpI4NGU(0#94vdDPT*sI#D{nP^J71SG8v&&bB@plt$OD-HPAGY}7}O`u*$QuI`e z$18Ozt;>qoixD5iPp^vyIoa63D&raJhN7ABDnRLS@&ne(2N6LiGnTij$jaMdLStP6 z{Rl6q^Yll|)8vb?thfL*y%o)`K{|2m75H^YG)713XPfMl(+yBkEn;-2e4Fk=efpMuuWFTy(EjsJTe0}Z3%77T_4 zN)%x}wco~-(!dA2fo-qH1uK5(+r0ONxEPttP@kb>w?H$F-bn^euMT4+8uT4v1ju z5=YW*ALsgZjfC6wmG}XvOsr^j`GiOS`-BjHOJfJIW~Nat`om4y#01Sbgk;+MV_n}! zSj5n-oi-Gy|5Lt#OzP(udWqXb>36Y-dhS8?E4ICFs03eYMEL_Hj3bKPprU^ z2v4sb{*#Xyd)fds$`WH{Dw@A0wPO5LFe?Xq_zBhrS3v8rg~99OWDpc3W`xP3sHU36 zlA_;WATwF!X$J`-#D+`Xe&~ut)kH&9TuUz#2N<&AQoI=P4WcZE?yI6dG{l5kwBdvJ zW2#J!PyKB`r-WfR!(%;k$D2%#BUCb8wxNC0u@+tsAOl70FTl(##Y^~g3#b|OBVTrv z3ei|sGMtKip$>CJ4J7(<3vJLJJrgaaKQt}fczbjJopBzP?XU7d`xdvcQJP(y!KB`y zVUMG4!vxC z1m_D;ZI~;@4?j^f^!WG84-LNo1;oxkn-D-j`c?(e!3koNL_NYG1%p!2OQ6-=7U9dH zL;MZW7USxHNZl7rwlunAkOW@D9=-0_ygx@0nNE%P;=}_~?_zA?^T1D2EfF$;>NvoO zzV7Pm*=OkGRsIWY`e$|8-w+S>s8~$t7@;ij8(!#pNm~|az{&e5k-nos`90n9J?EzJ z8SxH87ob%G*m!#JPHD$#3kG{NB(Yd zQ#^)f_?U)812$3FkZZiGFtO7&2k0^SlO*Q?9g0;DrLh%nQ5cIZCi1UoXvue&J;E!o zs5!H3GxFU=pr}{Sx{&5rZbcc1UmCLz@cae((GmSPndC!iS;82gP2Z4#cAR5WfCv@~ zo<>A8jV>Evnmd%_0=Qifrdgcl=-_E|I?2TAt+77Dg~nBC=SlW zm{X@Sz;+d?qEnm(>cLq7dF;35%>U8v2J{0m0S=uTB9KAYbZmsYr}c`SX|3b z;K!6Us3bL;oa_aXu?@jcFM_&s=T(#i>ks_>{t#y46!+pp&u z3nm=9g&6Ef{Q{|2puze!)Vcs&u}O3z3|}w{o8C%b1rRsR)ejv9+biu=S)ySt^xc&1 zjjJ1pxfymS1KVOoq9gw{&Ao~)=L29Dq3`YS&B}|iNYC#Vq$J93jy#bPNW8bqyWFB&kUkTU{nEIAg)lnebONXumr=pc@2pTRm8 z!;6kE>i-!5b^Sdw65V~_l2aIfvpOG8b+X><9}#fRdDS=@2knNqWsv=RB&dhsU=at? z!lGNdo#&f@+*G4ID>%kAl!5G<(lRlIXoS(DO*I&roS?Xbd%y~F!U?JSm1676UY<7zam*nXN>;oWal%KZ}^ADTVyR z3e*u3In>K`mzK60Z?rYpqI5fi1QI_VXYaAV6B@{tfzE);CDVea)(smfz$xe7x1sc-;fNvU=s`+Dg;1T@6$f7W8RG4h zw}CMx4un`^!qZUk(nffi1SKzxARBM`-#I7_`NuIg7jQ_%KcsUa@B?e8Z;jv>gT5tV zHAK56pzcQ$e+WXIu!0?;jY$xJKWV> z9eRRrkrsyV4|V2Ob6iH&fO|Y_8`B3uqc_n9q#*oJwDVC+I2R%(T zJFh@y9!HTfKqA7Rm0CLI={v0ySxszd(wgI%-jlXm0t+eHGVyD{#zRnVr}*e{oF+$e zK!j#BA0+c1U~$A^qX42yG(@wW-b zv|OTrNjdrVNB%~`8;ew8PN-)3BNPlkjfs1%Oc_`EwX(^^r@y)gjQU|JA|di z_H}@IfqL?p91$?}DRJ8LPIGUg2B`85RJjKP|99wVI{H9ZM%m>CC1saSfc3`ag2{5P z`QH&wBcQxDV(86n{$fcA4LHvju#JqFzY&@Q6J$j)KK}2xr+^LA3!y0w=$tpfb>>CC zH~$x}(-Cdm7h_1BM#{i#C}MGq@zeLq2k1%n5+~Ry(r2TgDb#}vVA{xa35=WAzQ9A} z9dE&mzCWpH;mE3!)hzsxK33M(El^%mp%iT{ zBt+q&FQS2c_u|^3jKnf#`?O|WxNpECV$r8V2z8OKJtG@MT3-~`N8ule?_&h{eFNJP zID_|8iRXYvvCeN~8&t~Xh(rl!<#4Z@5rg;nHT^A!H|}cr4-ONPM@TDrC;tb5^YOPk zHg=tMK0{~VYAwlp22tVyDvy~4B`!OKDDeb?65B*Eyz1-G3D7#d{sS;IM8%&OMErk> zW=(#tsJMVP{R^E+KC@57eEr|Hw*9BT8YCIJLl=^Fbq@rVM8K> zzTlQGm}NnW&plUebyjy`;Spq~4;C}w=SNFceg@AQ?2h+|ToUpSxhFt}VuKFltayZj z;$S<13Nm^dTX*~^~GKlerAZIRH6v?rcq>e;f z45Dl z^V7$nJT56miv&wZCmn)GZ9a$K;3|HI#CS{7*ds3z|B!@5pCOBbkYJyU>uWGiiF@=>NXF(7 z<(2pWetLQ(wKFVj(}3Z$yZPI|_XC*5$PK;@%u<gT128gVYZ3B~> z+24`c%O6o}^2@s$UHOm>(inyStE+{$1If!^rT&!q*!=Qs0!?W#fRg@+K~}k`I!mZq zuP5BTA$5IT2+OQ_e?xUT7q&{Vz-p*YZFqsO0rGp3e_5S{C@1;R>g-q5JA$vM!P=@n zFXDG#K}6TTvpCD(R$Ga4xDhdNjGF&eN_)X|(aMgtS^LM5_z zi<+#g@|5?i$to##d2&tGLivrS*JM>x?`QmaO?FMKp{J+UVl5T5aTVbyy9xtjh1!VXf4m zS-fUlh5*1fd3;^gM1A^(JL|G4MZfYgyuD9m@Sp0kN}&;_UKB9JFy}NAng2earS?DW z-hc4db=e?oK)<}aXECp#FTM-?1RNzQ*5>2tq54KH` z8mWWgxH+7ai5Swwfb&Wsp6M+NI3qd$O;$n0E&qutX#V!&z!SUl7h} z)cW=#as@;Po@mmWy{FV&=^zK%q-1Obq|hDHm;VvYQY)5ErYVm>V1O7O-47JaAjc#F zKNn}Ytv<7=iM9C8^;v)A4zJmO^-=vE@mUR6w0igoKiz=!QZDoA4OxhKaTt$n$Ql&; z{V=-cY#k+h2J+7uvRdUvj38Pf>5E}?)0@Gdfbeja_}PZ6eCbOaA%VE0^(XBlra#u{ z6M`_Lc@0@*95$)khz&32lTEllcc3DlE2^3P5X%EKcv<<{Myz+u;A-F^v0s}bgF>aHeuo6GZ8C-a4#5*AMlcVE%E5? zLc4LCN@Avd8QVP3vUrNcHJGnx!ltUrX7a!YRzum(qas*xnXXk0f)o|)iYN7Vq7&>f z0+ODKV3AeW5Mm$tOGyRc;_;?00}v32-I%?QYrIw@t5xbm0_FRdPW@7I5h9%ri)6uN zmQ}_85ifOD{_+4N4HT(-RV3D#ncs-Sd^Fq7t9-<2G&(W?6}toKfUF`o>0zRZAnmh= z<+s3Uu!gF@YT7cGro{-LBEIC)KVnr%rXa20K;0*N+efUga*-En%7&>cg877|SiRTy zk4;%+)vrGPtto4zEa7FFv8FYaM?KAZW+xq+nwSX4g;pSbO4lX#1+X0$ht|bfKD8MO zSGM!5D5HLJF8x6>wm?x!o#iPlSbcJ7ZNWa#R^#S88oVDQ3PZd|;o&V=6I)k&kWmH^ zqyZj7KopPoQG5U2h;v-FWnnJ_G>CSOP~fzYhVWVt%wmkiWTuzIFk>+_#0yz%=aFI^ z2g^mDB@$%;CBvFj9_g;uVNmfRV5cSFqS*Ay!@S-6eoN;5z_M40I8uqit|$+A<<_i&+B}Xh8AaAD+m6Kr?Tjaek!)az z0Umw^#Khv}d!FlH3#v2(RwN$Hf9_^$PQhST?-KQ;-cR_=tza0W=GG@Og3ULeOC; zK$B4l9vKN&eKZI@tKu)3pv_kwty0zD0UsN^CqFu>766i`{3 z^2{5_Q9mGfc9aW;-oW5 z2|lwe%8R^P22icI!o_~fFBX^);BRsWAehS z4um0GkuazutBWIC^E;7^}{M&cnGm>eI;LATx2 z2Y}g4(20dnGQt#dXm>Td(5d&HvCfbAquI=i{7evpAF%bR0 zs$y#hB~EA}jS-x&!S(?OEbine(f$Nb4>C2S(jVmv#0)sE<VfeL6k2vVWS#~Lb)LKB!cn?cpq5~VC~VLji}cM@of;! zrciCr4_L_Mp8itd3=<|k!zVm|yN1CHz7xSjNdiiMU>iCYf5W(MxSSj$y^d=rOh1No zKPHVI=*$9aw*WZoHQ2i2L&@CgC@DwZmsAa1pkj*0|2?r|;;fl$2i$wI)!BnsDd^OL z0RZ%WT(H$SAWH0kst)!a#MAbVc3I$C0s^`j?Lr4DXClykqJtBms6DXNdywz&J7ozp zI3@=vVNB^UQdjiOb@C8W38gpU*Q5Wz{a+i1h#r#8b)>j9?F={DkE*5vt(EYLaS3oz7>e4lCD zWZs|HHozBy_aFq}LWAS~2NxWISM16H>*-+GjnztG{0RMO!F%e<@v)|uH`q-fmPi?2 z-^Yh^Wur`6s(RD4d<}gFgVVWu$Y1CrKa^NfQSp+_ z_`?<$`j18sge{1Fr$^&KnhA{bmr@LXUgQIGMy5mPMW|Hjs6jY9>Wp>y-(#Ic?~CPa zVFY-l<3w6FR=L!k7uXV}2aDlICAMxrTYjz^tLH6B{=*A(XJIzI7oD7TH;*<>qVL0u zc!?$h4gT8#X3jr*-aG6jjEW+i*SCRSN(jL%KxG*C+9HH`-8FqwFBxvOYauWDzi_M` zN%KH_3;m_q|AnSSpetCzKKlW32^R$}U6~ z@eU(3ElA+ETtZmp@ew9Rx~x{tIPgMRHG%7yQNbvM;Pnx7iqb#@pgJw#nG)*JHo_4c z8#mC?b8Q+TWkrZaSB-li0!4YKi{2|OH5WAYVAsSzy*7X!4I>V1CNQd0pm=)ZBb2XB zhN^l67?F3;1l)Mji($Cvg=4)9#ovL~ARe)0-h(Z)Z>F@>)Y$?!>IaR!hXlH!;z5A? z>?agGMgq`+B_WAG`!M|xp~X(KVsUp;ngu5X6rhc1XDd*(!$?egQfNaKwj@5XCuEb` z{D+>bq5msFVE~#O@=cEJ3hxvazydFUBG6j)m4F6^CLxA^zEyg$s*u2GSe6nvu4#eMu}FBWXOf=1v;TQbIRGU>8uXA#rR#&Gfv@-s&Sg_#@( zrQn6*KZ*n zwE&{?PkXbnwk0041zM4-j%&m~T!$A3M3jAY^&DYMXcL6J6l#*RASzB180{+5Foe#o z05N|>KSirr2Jcz~9T7_d-a&$Lbd}T%Qy`{7NtNGm+J(|G5=@T9@-uiWL%f)?3r5xy zm^s}6=WBx-#9b2zuO8zZ9*FogBqO*3w!B0-DV7VPs0_aeaugru)NwA3Y>D9+osnz( zeVoRK7aN-MQGHm5ZP6zP;Ne*?#+q`(0^>*(^87p6qVvQ-Gw~6$C^Mrh7^|0#>!9*z zgO#Miv&-IAu+hr>^)A8gfU%M0*`T@TujQ`ff*{9WUG$eZLMV2G;}^r}!PQLo-C#R5#>{(V`4FzI$8rvZ~hll9(2Nmr!TU=8%! z_{Z2C__)5%HoShpd0$qEm2B{T$jS-+GrrhdXNh>wPCPY25+gAgDf)-B+6f?N2A~ES z>R(E98s~3ud2ZeVhHiyBkq1BP_j)(?i0Gzw1hw{%{Z>-IBIvps`TRkA{wLIBbVP60>e@)MpOEi_5;kWv+ddf|1>dzW{SPx{FFqgv9issb~ z+-^iK3*d)IUr04E9HJa{C zFW;8r)@yLor74A>iYvzPBT76&3W-(q zTvF-*pC}enCc+?3CX2Y>$yCJ11PUX@QYJ}u0FUqK1;a)O#OGW}JXjVgYWIE~H(vbd z`%`)MUlvG;KqrT@{Sh~g7@XB>qfOCwmd9wBjRa4l*mN$!-H5LH8`8qvykH`aoR`2XA~-L?F4Kv&ELcP09F%4p;D$NaJ%xu+geMpFbVJ zHrYySdPw@blhHWLx5HKFFf$OY3{CWfa>lF!Nxei!VFTg(@M1rP(Pmi^p2FA9TZ|fw zJ_8pWkI)ZTarBX(MBoj;*(AfW?YPiqdNTY#3xxV_apRx8%Yp3`M=^hMD^IIbx9H?) zwJ^PWQ^;ubrK~zjEE(ykO3;|$P9iT_+QvT_1-w4a`6yOF^*h9Oj$*Zn6t544E>Apl zbA1$RP$m^PyoYF^G&CKjeguo!>v)6FtVYNpY**P13zPt)&<_+d@lI;|K)nG5L+RoZ zK7BO%r*7T{283GEc2hFYfDl}KamSap(bq`49PEjPM91{iAG7PKI^hVP`U$h+IBwo2 zEFdhI8KrtssZ)7G@v!UAYNmQD%0;6eze#~#6dlT=$FVBqW*sI>N}34L7!QwQ>@YFP zlUOAOvTEu$wjArQ?5C_&S{W8`*L|hPeotj#SFg9 zn(&Y~m*S)%BW!RX-RepL@Be_7#t{DUQ+A?7v0rn*_9cb{S(fW}-cdcG2w;ifknjtr z(Q=)f<;dxTbQ&*e(p*f95P8da-gwp+%HPHlSS8i>Q{H0&RA7twXA_vcSXQVf+da+$ z6WJCef*(s{pCP_Zd=eX|yyo90u?rP9orWwE`Fqk`R~-m}(u#x4txkyZFPvmw#n((^ zJJb>Tc=t)Hu^P57ecmMC6@vQgOlBk0ikErtWcE8kkG`GE5|syh!W335@QSwqYFgps zy*Q5In-0XRY@Y%RP!PW`g;iAgrRPpzgOs|J)WTkI%A+{vh+xbmWPWTzqPib(BY2{D zX$X8Xl7Vn3P#*ojSER5!wbU}cavC$MEtm4FX>5$LJw0wZ+pH)%_)8lb3r*9ARJK@! z;^$2&vlLrj-UEznpYiw^tSayF8Pq`SZ}YD|V-eayTrUUhQ(d%PT;leEP5iIVSZDR& z2HwiW>V@pvKsO!U7duA3k{e(s#%2Vvu89>yUusR{OOR9Dn0yMG1K% z{&VP*NN}2!#3SaivFfr{e8XH=HU{UUpPq|tLp{@mKXyY0KKvVAW*)ntTIcbn^H`^f z&)g5eh>U4yZrU%zmMG)HCu9SOpji~x+yH!0So_d>9axx^Z5fUt*>7jwQr}FXZMZTzsAc!3&1Dt zwC4{{wn1YQigv9zfe*AqDT8R?DcW83(o@um7la!TGurdGg{-#vq$r=VkX6u@4)ws; zg`zYWY#iUT5K7VEt$2?`?2Oj46^82m$q$SwSFZ*)71oaI1lAl?^LP|CL z62uE|Z!j2mg5SL#bMK|>vifHWeq$;7R^7ZR-M$R0MnFlLu>6ZIpw>I8h#yPw>zsA) zZte4i*ICYjs@_>)RCc4k9A07#`-`DTzL_xt3Hhk@E+hHq<*dB=TXQ~VIhzw2jgVgu zcnX~+KYQb1B^d*RjwFHi>SuhucZx@R&caGK5NFPFTxsJep7c2jEI-*ISc<_^e$9vhoiOgK7wD1)5W;@1*=iqbzMdpLn-}d-slS!U*^6- z>j`%P(tJQ62Kz8h#q{MXzhKq;S2Tq?4=zX~DCdZ}2oCiHbF2M_@qsItx#B4=-0?}0 zbyBz#d}y4L`WVp68_Ex^VCB@?L;3X;tSmb*lwuPc&AtWa1ClRt#Keo-ZzZc+s>uj> ztd@Llu;b>4`xkiIm8?>|(!-zU$($%AicnNGkX}FMVQWI$Fon$`<)`CYFs4+d)=<7= zB^wYrIq$U`%tt5Xa z`3HAlW_Y`*frkf(E^f>nS^%G{gY;_veT>WC|T- z2Ed^JNY-=w?rPT5RNTm(xRT1wAIv}e5{o}AiTC=F_3~W<$yyYe#&>_of{IrGc1S~+ zIP)?8<4bhvULt?-C96>{0AGMA*z9tQO9b@m{BKYplD3^3-`vfYA0+WvT&nmqk4G&l zR*Cx`FXmI`h-fz%(;|y{ZcfoHg>w1qHPA8jMG=t;iYgn0w+OjRpvESYenqCk)g6Ek zuO>iW1$C_lY_cyhI;oA|p2KfRXq zR8RcOtAEYHD_2|OY58OIUCRUIGg|JU=JMpPS#o&FKx!FxmcjDXm2lbJe86)O9Yv|~ zvi*Vi?N=cPo|(uif5XBm*IwwUeZ2Cn_F?iFwfBSBAGL?^wckLVO}fobegoMj{T9Ff z4Q!+j5p?@oRzLW@u@7v;U_|I8V;@+9mxG}YJw$0lvi+9zR(n6=Y#pm!Bo7=9mY6G# zw_eA(lwamH$l$zq&ywp~!XSSo`ta}9F{fJpDQ~u(RjBIynXK7S9^I##kt&n0|@Q;dDKFVc+tUFv#C&JdZY%5!r~`PPTp|?_UiIC z`GgHDs@>J!3&{#UMFAP09SJ5^8q zW&@k2K6Y{UMp*Ob{LSxe#CFp8ZyvOX?Np0?%YWI#W(KW8=-mHS%8nS7#&+c6H?xn` z1MB#$&8&K*>T?WWRc!xCb|_0kBkZk*@O<8lSKGpdH#~Zcc4;uNvuQ#u-ZEzAGkU3Z z+L)bbc!9mja_F`<%|*#Dp0S0M53l?QF~nUBg*lF}9Do@NQEYQ4GCMpg6T8Maakc@v z^k`Uc{KWVN4lEFvW4$LwR%}5Ii)ckTfCDl|nkUD8%wd)5fFj(pDF#Z3#3-^Oa%yz}d$-u~7d7xoa*1o$3c);$8HxOvbRO&hH5 z_axJJam@4KO?ywj^F`Jzo)35E19jK<5G59SKAge_SSR?4ZP-`TG+yUBR-ycDhcUs| z+j@}uPl?=FqIYLLR2**FXI156q%= z*LmQNtX|Q^djUV(it4NK_#at7(ab#r&n(fg1OMblwmRe!`JO2*_aQ1K4`gF=$r8Ru zrEmAUd0xQ|2Kc!i%>{qVY-J?aD$qu8_+b{iOw)|)PYdPZ=B zTq+T+XJS#YZ5L1diM9D?-M!bcdvh@3X&K<7OpZ%*k_@ZHUtDdEut_meANSrOL)X2; z*n7)%veHdTo8OZg7URI~!iey?%`Dk=sxbRK_ zhP|l~KC2j-LG^kFjJzIZC9Q&mmn=6iwuJ z`H7i(pA;m1LF+x?Zvq|VFJ75f+0SCsfQx+Oe#inF4)9s~;RiCMG><;OW~+}|@iPZl zllBq)VeW?yF8B>EeHji#An41ta7c8OsDGl6yxRLH$$;jw#%8ddUY6`OVDbeCgb3G# zvxHtEt0M1skj+y04Sx9`3svqe%V1TT^x9@1|Dlc^_nJGzc;6R~w}QBl&W&Cgw#AAu z2s2=QOng(C_s(FoOWaR}f|g{8Oi{<2z9<7?bhVV;wA0KDNkv(j(VlPsg}3N8cvZ|j zEw0H?qE~Nz_b^+oUOK{UM_7fDCylQEh!#Z1Pkhr6R#Pd*e>uX!>$E>Y8@5B%MlvQq zkM||gyd>Ir3f7^5t9J14qbOLG_c_YK)p4cxyrV3tX#YRvIC z_iS6DT>~lTdjx zzUn0Esy2!j`I&{)sXAQZDNYxG;9{5t#+N`U#u$SZ#07+ipx<6i_|Tu(VD;Eue)4D5 zyxOe2SYIDur2(FZB&wf-Nr4m`(`Q2uiF@Ib$B7BEdF@jyLj8OUA9@NqOO4Td_9-;J zBA)+qiq$W2m1x>?vF2)ez0<6)q9zO8_zat*T;bc!Ku=U+G=F>s`{D8t^c%oypT(*< z-GPrk%j&@W@XNETOv5jB6@t7vAxbVu0;>4tfH7$|2sfT@G}Z&%7lu;o;Oj0hbB#3I(FO*D=)Z#Wwjv9&?ekw!JZT?dE(6gWM&=fFpmt*o5J5 zwkjS1o%=w{nHPSC&@b+zo8HEP3%A?>xUCukKJ78%ko_j99K2Fa`NN{whC!&X-@~n6 z^mA(fz> ziC+Y3BA<~X!QwuQP>8WWE*;0n?CSUwpDoxx%rHi~{H;xwk~3(EW^#OmLpkQAwyl16 zH#s)o4Lg~|iR)TIj*v>7g;4E}Kx?f|S;*|_hAXRO{_sZ#PE{NQ=`VkXX%}r3^}WcS z@5Vv*rMhDjbJLhG)BLqmkt-&O4sIn;0JChw@4J|2!%?hO%z0?oj6Wzc*-MH{HWXRO zB!3paP%ujpEiyhNM(c2#+h+@%ZFuAqbnub6ACje3@34*Lx~A9E6kx! z1X>!(2akcVCiYD!ESnGb(g8GB5v5fZTOICtlk)nJmUO#PE`qicNbEC?5_TH$y1Bo3 zz!7K<%m)yqgvw_hkQM$n!rD!2H2I7_jfXtB#LId#jwAW$HgOdLBQY3e>ORO|f8l3x z>_s-ec4Q=FnRcqCoej(f2>;=#EP03hA| z0*H4W@-kuOXyh^5Qum*gT}aEOF=MSO=G6VCjiglcO|BAs0NOR?(BfVq??;5N2b3k8 z6&rCcBIq>ruL-e4aIPQ=h@m!3=}pV|e;wkNeFw@4dRfmFOpMWUv9lJuP0>T69!EFu zM|w6oIBWq8YKX;+Yc%9=aZKtjF{i{^Bf>S|0EK^a2PEBAyzCj?mgTXohDRhF%3r_I zLjz0uy)~U!%R-zuj!xJ_bJ)Gm1KLXcL>OKyk+gh49N<(*-aJ?}Fog#+IuEjt9|uy} ztQ|EV?$Sc_K)GsBg!J7-p!1AG-$VvIcfh*YWX8_gjb%c9CB@o8LF(@8n;l}Rq(*!3 ztm~|_EmN`UN^IoCL|?>g1BP6)~D*j=HXryR3GrQ?DkE%&j0JYGc#ofLrc}^0F&>tN1in`;^r~X@H54}$G&u$_yjel~LRkO_k zlWG6g-!y+39)Ou=2)t%zw}DAbt**FW7|<{`p6is{0i_n>`XmGhf)Z=C>kZa};V~o$ z{7TG)`FI*t0N14gBrb#c2#MDp#wE-~FFm*n9ble~4*XD0$;+p}9xa*zsjUg!1{O%n zwU9u3OqB`-KeMR@@%hK~P}Bj>E!PAJ5BhFPakPgIo?aXHZO}o(QKAeoTV4JA^y+w! z);+f^U}Qf7cQChvJBzS?0(bnft9oX-Xj{Z2^^1up?v+#~f2RL0CMDK+heaJx#rs&a zFzp={nbLkhrwqMt6HpWz4Pqz+NYBiR3ALc_I6$4zJIG`Q9^r#Gg*-hLO3%X1e)<|b zAe0JGqCqs417^hmiW3A9gQ=zvm6+~HVd0Om{bs!R`Sj`HwleOnxHtwM+#koEHyuz6 zjF@QqgLZ8{D*Oanwt-ptuT=d-y(u+k5C%yVPC$dMd!ao!I*7uwMxNUxjqVG3bast* z-ld*3QXFffxRMl*4>?*R;|W$+A2+Z*Y{*yCv)-K7P~C9H`@ot5)Fw(i4%Dzb+5;ky zufjM2iRhhCKo+Y>!1N6nXH8g2`@P(K2w$G{AVgYPpsc5~Kapl}8>ncb>d01(8IvA4 zaBie0@-Gm3%6a(xPr)M@y!G>ihLG@KMHy8Eu6Bq7LwV=nLySu{M5jSB$fY_M3iC$= ziyC~Q6NhAeLfCW{X~WYEBp&0juWQn1O?*SO|lYx}sMt~kT z3i(raQJbkIl*#{CHtz-vB?7Pk$+TSqNan7ilu=$Fv7ut;0)P-kB-%ZuAfs#og5GkO zlWs1|u^=wT0=$yMmVsY!X_NGFOlyz)u?f&>P~;4^aWW4(0%USp(W_P?7#ZCTIRw2Y zO$5ohlCBd_lkoyx*K_O+-Akne{E2|^WMa1}xRo!{78`ka!uA-%&O(kkMh5ibrg;1* zWkL?hFrN-C(pL){5GRfVbA?$#(27(f#ku=>zola~x%3_R1pT_%#aJ|eAB*z9qFlfe z{x5#fnsCXY{ETy_fe6yEz+$o)(Sq>l0@5v!$CDmf!++E1%(WyC@AaGH#!43Vj*wI| zAUfywPj4#o8p~8PMKY);Ni66Lx|tYcslCML`*QN9NXC$KKUpLiS!~|M$820L2!tWF zVK%W1WUgx-dw6;qdF8rCdBac-Vp&ujFbk z?Pe?FV(gvf>iUWHZfS-|NCDBHh7i|L{)w0@EL4v@ zrhO3}lm@@h415x62g=LIoky@L!%*uQO5A!Z2XXPGjR+ld6{@_RF52jaL$9W^MMx2K zwi*&oKYFn(Hzb~TyhvVg^!4Hd-r+EMQ%D>dF1(j;-b0#$!YLc>9b~d#C(DR%nwE~DnNH*!2v<0MEDyb2cfYzLXLIQskDcz z+yR-l*r)acoIeNA!s#V^rZ}B8L?g5~ZJ8pyEXWLq1z9ag+M?nbJ`yp?5xr!#OtBET z2zE$%h7cODk$Xu7vIUqNAEFG1O{Corf^aiCs>l+zelphgm(;2c4k*e3GCZS`g{aM{==IUVyzHQSrUj6sJQVJO%&cj?nC%$na~uN?GtK)K zU*Oskg}@eJUP+hC;Fr)}9BCFy&}A!+&w>vw-NsIW#CZII!We>4rz)i4I)=mY9o;@V zDDK24lq44we~NJ9Cvsh+x5ulC&RRZzQ;np^H7h@di1QYC3vlt6U}(&rP>U+;6Kcp<0n}MunM7Hac~sec|JcT zoQk}tO)NZ|Q^1Om+qvTzqP~;Fw;>EQljS5Cl@xUQxc(cyn~lQ?6tNsJGW>M7s@u?w zNBT0P82I%7$GT|=RDsqk(3tV7! z6?Z7bXVRgH$kt)ga`nHlnM23)o@6B~IJ^u60p^kf6PrF09{Zkt0_h||zK3qtn>@_R zhpl55x(S(>78%_IDN5$O$wO&@yTAFL%z)xaccLGO|QQTHEjy!jQ#7DZvc|LTh4i zNn%1g_v@>~1!4{B%5C@JB@YoH$bfDrX=!k*|0OUa|ZG54q}r771 zfQF>aA^3)QAj-CklBg8Pk@!aRZK-qBgcTSPyoLIy~{1xWp|Py8qCS%IVD(m+y5i(e&Cv_ z{>P7BCKf8@v`sO|reRW%PDRBcn}vl+wF;BUYNZwyl4=!|71b&f zO3GDKWK^pt>7&_Fs`1y$KN*Og-|H|aK7Ok2=ll77zmH!%-agMc_uO;OIrrW%#&&il z$Cr;Ovyll8J*H?UcE3m=p9`7g&vhO!J`HTftH^mvps@Q@HJNc(^#W~nUtTQ>i!%~D8oY^J#@+p|H*e1cK>>9 z64uyt4!W8-O+HN>+TG$h`P=kQ!fK-B)tyU*WUIaR(X4gf2X2bv?_sa<>U8(7P4Zcl zv%5tGl|-}Yas@Xz7G4pYmK?^17eBji^qfV!Na9Ng+r`tVqn=F#m)DQy=8(^E=ShF&T8)^DKmarURJ|*FZBL) zl(O!_Iyng`bb)2%Yu52#(|wuAYb*0tE-h~H18YLp<#^sKDlaS6udA_9F|>kpY4_t3 zD_DO{f=@e_b>~ATuf`!iufyYW_k*+i$W%i2BlPbt*ksS+SF-L;4)y%Z3*8|{cx^>a zZrZ!@!Dh~kPfKL~_=tx5k)N@J6U-bAbVK+~(`5=;m{+j9@ z>HCX!_m#sJ$*%tW7wv(q9`-^wYuRPQ0`^)FnJ43&oP30RdtN5OZ z-sd}gj?c|sv$FeIKP~jh@|p~CJ+CG5{e|okdg@=3NO{l5Rr7ws^SYOxQoq~J-!ATW zL_M_Mkb2_amkx?+uH`qGyDpsZYv?ahukhNl{B7a6ch!t)L)MHK^6SH6)_wf@6rRO% zvWP&WtT*G(@&ociCcK$J-U3Y63v-xTY zzX=#7>b8$i`_&je)lD9%R@4}_>t^>;*VP(Up7zjV@-GWl^9jv+dA)i0-GL`I%V(y` zR|d2Px?i}n?=Ufvz`j~FuFfz!a^89JTFT<@-;cbl-do3?<}Mjh{92u1Fdw-OQ%ma& z-T_JnPg_~&AgHcs;BT?tZ&J537;<&`1?tR3-pH0dUcI4_zqP!%sQ9%;LqwQv!5hWJ z2MllPbRV8qoY8DJD@?b1zWQ>DVZAPps!nS)xOKzlt5vPMlet+P)MgNpgSLx(2F zi|*`LTlYK87VT(Nn?4>iZq)9POy#Pw?qAS)-=`*DX|DO^1vRn5;2P+@LY|Xf0|{5C z-*@o#&utH=v7Nj%HzG|v<`An^WT>`7hAAiOqAHSMQN#6Us z?Dc;4%jEa#)%?ST69&wcN94_g&#F5P8&*w}9|HKN1KupV^hZfr_sa*D%W4}3KfG04 zcEm7(&z7t`VmSNwWcN|WxL}C7>j>{{ZJ(>QA2D1!ZPA^I!h2(8UEMu3!AZ^XrI-R9 zc=&LrTv?HaxaXfas*UH4Q?rC2DIukMLzW!Cj_v`>J1!{R;X#S_(aV=`=6t%g_w{~W z>l#gMc@1AaNev3a`?_g!9xE|ker$Fsr@6+U8pDhx-42&JJGn4t8MDTVaC%=mD{))R+Uw8)Ia{1P;=H(Jo(tc8u#1{_nHFH&Fa1| zKL7I23(~xo&~DTn5^4*yZW=v7&VK(B=BHw=0T@t*P0*X537y+U6+T+zsmI4 zlCsgbibDA#G`8k+cA(Zxm#b&?GoGY-UQ@5?XT0Q`+jwKv#{Sy;KiT(Z3cL5E!asV_ z>D@nJz^cHpPVB@K}dQ0(JgE=+29n;kV#~Ei$Wa(R0Rgk}HQ9XI%iKPWx zEq77c^VdpVw(j?PYeUl1Ylj%m);W);PY*Gktef|+`q2>Mg}Nt}sKfNeMBO#hRIA=N zS~qi=YS$ZMb%tr`lX~NLUENgmBfaqz-NduiWkZeM>u!u!FBoPt>!!x5D~B1+(X~!d z-yLQ=Q&%#j_~0<(hhYQD*2r~(ehs9|R6jHr=k_xz_399#al3BvIJLrPoTU3|hboN5 zX}V9V)#<~HC+gCss+SKpuF{Q*QGXb2yky)BOZ)Sej?2ybY*~ISKSrVg_GR5aSNKrG z^7Fb2c3i1mJi=&{Z~3@kgi#&%*xB-;`8LpgSUon%c)HFpOO1~*T6HT9s}Drcx%v(2 zhf&5X-8U;#%Shw7!>dCx%{MCW^CWp4Ki@X?A7xSVMj96nw9k;2(~&^L4E2~3jMwVM zzoXuGg7GTd+yu4k1mk?&+wZEQMj6kKnfIW)W#vVFB~M&j+=fpYyKh4`o#8ix-TAFT zE%~YE-M#%k3S8RWq`ujH{P3A`Rv(bBA!Tz1$|sP#`-$HWdHZ0%H=QPV_0CJVe3{R% zM%D<->8PXlUKT<)68O=lhD964>efwH$3+{L=_019k4GC5U(HFsG;}{bLxwNt=r4bmr)~>Pi-~)v z``)^rjor&E1(vp{-<`yTJTv}rlW~-;X>#$2CL=!;+sCWp#~9DhmE5adKE`O#9eh*G z8)KZI+dWDBc8u|~p%a_yxbw1(;bjV*mIr*-sK<>p&eomUs?Hy4%+r@%+V@fV5EFq3-Kcw?IG ziqqAtFW7Q;j=xI_H$)`{IlP!gOm+V&yR7 z;sNKJ+kFjgxmG=RhH;keyV2^535@62HR{z9jF;#xTBCX<7#}_@z~|2Rjwl}7tv2qz zSy#v(NN<-gYdm2wGg&D^W_!7j+H%yT6OGe`UO2EztiCy2zE~xHhrVW+>X~SaIU$Na zuUC?vnLtv z)4elH{dkfwMz?>zS~tnKP`7-TI%l#mLwDEDYVl<5jMzKX?UnOws9bTdionbs&4KI)dUSFcxX7EFA z!3FBt8OAGhoA(s&pJ5yocHX1223Ee*-#0vG=bBxitRhjC&=kQprT&Oml!!`GFiaOY0 zoIUp4Yvh0nyO&C?`9Q8Q!b4X=_Z!c7TUb=!ZcWX!81K;i5~tQ!j8+z(ICGZqtkW-O z~C=@XUVs_QIf-C1+IBZbHyQe*7OPPu)Abq9z}?k>=3lb$|?CF*9$YVVhj?l}9vRK-;8_ zKG&G9yL6#idakkSl&VDLpB*>I9e+DlwzB+=z|0AL`PAlJh(fxm5=tt@qNye$V35n|BB;(kTr-T~0J#g zn`AseKlz^;N&Qf*O)}0IaGSY5KVob4eN&t`+gLWR*xE15rrTyU=DeITX{u?`^fS$q z&YU#GG|4<|+BEaz>nC47X~y(vH!PW&aQ)OtQ_a(-PhYfX$>M|=@z>ojY5JlB^OPm# zX$dz>oiQn4$_(@3X)`8Gy*_^0l1Yn;D?5xUZgGS+H;AoG{~Cs)%43eoAH7ffQQMPx z@~OC(Xzj^|w=@W|tx@={C9Y|7h@8cZB9@E{*P=$@C%o4;iX6gxU89H~(nwnWW+i}!RiAUxCszF)ruj=NrO?E~` z7tz~>tS`681Ix73ArrDf3d$X1zPBu&w2a;cq;i`qt3Il{w^3QA?>56x_2mA&b)#n= zaENMd+un#|=TzAMWv>#geIopk1H$k6&%*bY`|&&2(T!?U?v37UrlSttw=*)G&OS;1 zNjUzSJIMp}M(+VP9@R$Q&d78*FD7jvlArw7aL7VepN+A7(sG-hSkABIryUi4RwnCs zdg=v_s(80Z~e%_K76Yi-}8# zETW8%+s)f)>m6ohJLli??g5cUrZ*x;_eRuvp^C}aMZJ8s<+5`Y>2%V)QN`T~n zWj#B(%MXa_KR+P!J+9gr%3FK#*E`rKE68wt`bS#(Fl$Q++Ox2_y1#zrr-ZUOyEEj%+%c+B$DXcrj>jw9mr!A|2a7S|6K52=TE2SH8eJg zM!Sw`bOTMuj z^%Hjj;oHR>(xXft9f7@+5haA1c)cc6r-ZtWgeoqq|00fV@P9Gy_?O=PFE;)!ZMztG zDKk*U$V0*Te|G-?5ySM!II!=4c#Bv}1sMxTZ~OUx_=#;YFL(Zcuzjj=yK2HsR1q2x zRjvs$VI}ND@DokMQa&iYNu0vxJ^wTuJsVp2FsTefTqtDvPj~pMhW@6!x2;6lKDtfE zQtITqip>*I-{K7_}3}v z+krcoiN5*X^q#*cm)jF3hW5FUIvWNwi-CU^j=$UZA8yNMzpg&}Mw9-tkR5aUZSVRt z@_$s%@%PhnR0qcV#Ykj%Z^)6#&L$CZ`Xl*laK?N-&79gSDo9I{aNh&XBDluUEPh$j zEIuc^#IwW?tDA*0r&*K`&4R9;ycHiNFSjK)*jUbv<(Q0lG|;`F#{iY|q`jEevy)dI1+x?V-kwo-ejPKtv@lh(Ef`|AHc;pjc^=$=lv*0cyK zG3$XpIuz3q`Ke;C_xAn&O4+Mkhs66U@JSz4Sl1M z9eVS((_n8}x}FAO*q(4qt2mx?eE*O!J<2i}zlDd&W%_VW-38Rq2uE)vX#@w@($yjs zvV)rg^xY=&73^>Uma|>jMPt(5xTmLF<{#r1t+$?SRkWAGIj`t!`F(%6UFI)TIR8;> zToe(qhP2H0##KG#GJjc5`sabILf5BUZu^4K+`)n7QGVW0+hqO}PSY^zb@Z6mb9wxx^l#U`d;(CzfWj?f$=yv#9ei5z$lknLhh`x7zX7J3qI&OuAnJ+IPyQ(D zF8_q{FB4sCi23x7jVV3p!XD$x|JWw$|4$>1Hh8h0|27rt465^+;lowix5KTD^k)x> z93t@aK~YYa+y{k1$aK{+2ZfLH79x$1b(}pB#kL^nAm!<(J$F!82$?ov1fkKckMIy~ zVg+&5iw8w=!SCVtJrl)yF+CeH*5^oW%f3Ey{-98QcOWCdet$iH7_vBw1`n!Yt zceahBL)C_M5qJEbgyYW&|AVqJ4j`k__{TxQNyihJl*{nb?$P0p1yxb)B5K6{U6jzi zjMx+YI7U$BN47geItdw-bl}e-$=@yti25J@^SHD6ul8k8nDC!Mk=^GY?*!V#F+}9g zp@`nwF8(b3lTHo!wNGapeMV*ZrO$>w<^Rb+{%W7z!S?FtO&qOk;MINn@v_gX)RX_K zhX2EI$N%WuzRpxGB+7ql7h{Rw{(rB7`SP?f+iz8K{-0o^^4x#T`Oc<+J>3b z|I*klw{cOZiD#(0t&rWhjnU0Y4X&{R2y?JR4`=?P}!v0b0m&JCO zkLcM)?kCe*)`ZG`roPNOWPwavLV^78aF?+|>>Jr3E+vYhI>h1;9U>+W6w$v0nW3O~ zZdXv8##h#~@kKO;L{Pj?qr_=?-fm%mUY^@E7d`8ns!F1x*dK&v76i+hZtBL1#2gQfPoz#sdjHFk5 z9}0a-P!u!=MJ$of#Hh8P7(je*fLSH(WBXaeZX%rgn~gzH&+(pb;3F;${@KL=Wx@Ji zgW}9zXskLYzS|!ZR}r=Qg5q|fKM}_o$$euFBRe`AKXD*tL`Ku_4v|SLs^XgXN3h%L zI~gR=*bx-35)OIbeH0WDFJYO=cZhhl?}+FSw-c^@9sD(1*CECbuCNZV zl-R9wh>M8q%3ycQAietAV0X;y-yuvyDmxb)+aZ#OyT~7F=n&DzcZlR+9AIdNcy~yL z*m@izCq5h8Ar^2^cT#67F`tkZ@%0lsMBYRP2PTn2I0;#J8}ZTd4l&N&A!gr6!^A=I ziwTXmF0(`2NtsOFgu}^yLfwbSXYeIAd%8Nr=fu0j%S0X_%a4w=l-E0yPEi=vDN2ca zB7?{x>M1`uHc-Cp_D->xc!*eeTc@~%sJ!8i_$a+o$T(o{6h9CP*nS3a98pF+`#qf^ zjgaZH(Gkf%S;Sc@JH^W@I>jjB>xXIh#!fM0S*Pf_wNrd@cc*xdcq+3~?4$f=zFM@5 z*h1V*oJG99v{Pi>)hUvRiG+dJcW0*Io zl2GXVD;!Kb*eNbTxpNH4GTFJ7WueY^aTDr?|#xd(TTDR+13vX z=+)(XU(HrVco#97FcJ1!Leu#&X*soK@_RBkH8*#P6Nn_rURf7v#6V-$GIKZ5SP487e>7+*!Z>{MR-(+`+93qZT z2m|f(&YGN7In{@ljb90wwlc8kq?6D{M|#VybgbnTyD4-r$paqC?bph!^ApkA;K!t2 zCN>hMahgh8p$jdZ`s+zgAu2iOcx-&QQ>Dvk!^uxn@#`&5v^a zYai(p&k(z)tkS!s#MOlC=@xsZ$R%zhE~J6p#wL&+NkkAW4{=2kCB*Z@3gTMgtqq;x zS>mPjonkVviq7`Na5^XB)b*Ty6B{pQhYvS$KN61;w-AGgeKha^v3hwY55Jw_0%8NRC#lvH1s7zq(XPx5dkJy22UE4zC+dgOXJGr&Cb0HQnogeTx@@}VCNWIlxbPD$l zF0}VM#p@+Z_j}x$UxxO3{o_vIEAAARly!=m9TZ;2L62pJhbUY{gNuk$Xrz&bfBTe? z(y=$_#5on6;yey=z{_p*H4P9yeA_ABCN>dQ5wh%DG!pwhRF zOB}zXOUxl0#ATG-PT3YByQoXN`&O4o+}0(|+1e%Qi88`K-p)rDZG?5l--RQz(f%iu zWSQ%u!=m`MBi%6q&nCi&ANjJVg_z3c#7oza-f%?ZuKoMyS|8e8(OXwKre~+t-om3A zDP31Q+%^2?2g1y1aQKK%{&(LGIWTI(k(txyTy)v&OH)mAE=s-FGvd+gr!(pFv30b*zt>(WGu;CqG~sdh*7uSIAWl>@um@*RM*lGX{zbw5x!zu z#t45n?*dko;>6oV-ofZ1l9Qi$=q``e2}xD)++db$!L5_QUtXgXV`{Dul|8Sn3|5w^J;5L z2uE>VKOS;P!HYT)(AU#G221HMLvK}$LxiU?0~AD|ALCF% z3o1XO?`7)I zhvlgJR3oa|#HkA4S< zh%|QG&qadfYDR{3EJW=W&NUwn@&3xxqrR3YMrS<@q0+$iE7^{TXl>+xs6W8e%RE-1 z2U}&i#;N4ncb&Kp9j<0ZEWeJog^NpWILKAGkg05E3enoZDY=>s9%963?V>(v*d@yk z)8I99TyS5bNvRbsv|<4|u>?I>Aq}e))o2f|6*1S!@9!K?%R8%SXi%-_LT_ZP$g$C( z!L_0YE&5s!dmU4Vsc0TrE8H@VRcIPkD-74OKc=Ahc=ksh7NN;dD+1`o_(g0VUMup@ zkKRQb-xO6Vf^x$NwZgiXkzp3PMsXmtMALIwjzO6pT`Q87FqJ3OicIw37WA8HMXM|y zLx*l)|FN|q4NWK4ifpu?8?EDNg@)c!YK6sdBL_aMRurN>ju}8NnptbXat0$tCpytH zk&Z~swIX^c2SziRCQ%P9n2vtTNB87fQHnmSLUTMFzlr@Z1Km?=g~Lrkn_eptZl(hX zG=x^nLVqG1lI3S}KvsOPq8VM7hCXznekL;@x1&#P$DrJfrd!y4POV5rCuX4+3sAAt zIz$Bti-oC^6)^f%Dqs@oXVFviCovM4pUp_ncRr_T86!xp6}jlcBGk{}T+4Da**U;m z+Ce8~p%-0fna8=>=jcZBrM03St(Vcj?MxXiMr&%VD3dOz6>)b^ zA1&y`RJ5isBWSyVj-vBQW;T-!Udzl#ZOkZouA_s?$va3SkkDVxl%fq+$PHMC)0=&+F}BjH6q zYBw|D74$HpR@l*U3l(J^E6|VCXuFjIuOyFgs9(l8MmJ{2ay#|WbQ?1%%h7N*9lo6z zLpx^N&Hb;D$fLk|2OU8tR-qf~(R3FxbPpp#J6cz=9sOv^V*9-`gr57j2GF{?R)pWn z0kW9^)UV;3qZtd({Q$QgI@fZo-N*g!C6RO=6>^v=={imUIv=bRdt`ont%#zYvVkc? z^G2>2)IU@!^iEEdt5(=hd6bI^O`DjRRn&WoQ;HgHKu+Kto%ZLbSibeT&}r$ggEYULLzq{{hzqdN4YN{D(XaNI&9YLUS1- zM=u7^_c0w`ho3M)bbVSY%F(`)4nN2#`ihxGkB|Gmh=fwfxkfWatY?SsxSgcC=m6@g z*p8lma85TcqTMu%mLJ(J-OGL(IUuH>^Cx}=pxw_*q3LH%)k91@CZly9`=fUs_kS4) z(|&r6zG^PEhdBVIp!qj0PIRFUEdlOdbl31h$;E!PbQE2<0qu>PWAvlp5%LGP2GFW8 zQ|Lx7I-9voAEln7g`Sd74subU>j~aH#{B<1o2}YXEfzh|LP6W{YCqHQJxNtM=p&fmX zu^pAi>qP5j?te20Lq0vj6!fDLEh-J7hFz%7V`NX!A&fy6CZhfcI)ZjALhEL>Kh1%j zXCP=Qs1qKvyhuCf+QM<3p`DUC;d_Sr*!fYNhWb}EOC&qSJsJ$=PCF{ohU`yUh)MT zV1J!RMN4a)(9nf3FR(qUUbxYhT`wYDq+yIk%bI$TC-Yb+^AFSuFIuq@Z5Tj1cA*O$ z`j@ykNW`EI6VQ(-sG$u_YwN`dwBQD`q8pu9g!-I%QI2-pgFe(``MP=$zJ(cluwF!= zdlUPk|8cgXJ+GeU|1VRJM+I~~Q7_`8o9l%IHB3b%zh0!H9<$Jld1%2xw4xVnScyK2 ze1(obMLVcG&3@>{LiC_lZhywXRFJSe!xX+skI;-xOhOl?p&K*MgHH5fF8Xi_`mq!> z^r6RHFRIb@Y`qAg!Z(V>7Sdr%LN8{a&q2aP!u))_C_oPeP(%G|>`=fdK|d}=`wN^3 z^kFV4FVX?jV<}o+q628hdUT@lI_;qW&0FXQdN2_kmY3^=m4qD^qm3`ZU4cH_g8EmP zQdy1xv||@KQU3;0SV%+YL@T;*F?w(X>R;oWqxE&J8MI>&I?teFlJrsCQLm!5F z7%@hnhHoK6ZM#bUi6~1hygoD_(_Dn z%}BN~V)S7gYG^_0HadoW%$DVRBYPp5-lZXQZl@zf9H^9zpdA;Z{yk0sns5V}(Jjm0 zXGUZ>I{b12iB|Mt!d6DOgR2~EUMk8w`ce6SdT7FkZIoj)x<2Htk$%M0jXq36KW3o5 zjP}rtxoG;BYYWXEbN`o;uu$Mb8&;zogXqM_Vj4yhY8a2oCwxl`>Tx03(1ms^Kqr=< z3oFo#el&ebyXZl43H8ezObrR;vwA*V#|&WnJM?TPJx33g$o%J=qIb!o6-^bKOLSwU zEXM#UUvO=p9pkq%1DJstI#KzO89+OhquW7Z4+$@7==zESm2v$oy_*LT=x~OrU8m7v~Pz`H71Y^?n9`&i!;`2lu~=L@otx z+=BjUrUo_KgUT<=jNFdlUK;$Biw>3FIEU!OBx!)F9$htD_2{kT)S|794x$|^(20I@ z*E2(22R$PZ@c}zvH2Tnt?gs8#v>&J!W$45z)N4Gnq6w7`nUN+=5n9oLHcUkyrlY=v znL`u0(2NCW!4d}vCy5Glp&vciiaw0^h#A3XG`G?*bYc>EFbyqjTx4j+Y-u|`9Z^FM znmg!d8SP;bdODdQv>xLAFOUUY^aQsb`VLE~)G@}`lWcd+BCi7T; zir|4smMaY+{1e*6RB2d)a7%R!tgb=5@CJv7_>>X!ZxGR_Kc+z>pa)l=Euuk`$?^dW z!cfl0(1wEvJ^khhb zNJ6*1K~$j!HJKmE_RqN82~!59+lB_ zQ81y&|xA`Ny3Q%^kWyAV>pnH9WVvW<2WT~!wsm6ZxH2ZiER+3ujvRb zL?7BwIhA^-#{#sY5B=CBx1ZJ^qQ2q&H<5_{hKA6Je#}Pe>6~M9VHtYRk3Q@|OI(A9 z{g#F?3Eh~1rZYGt=t3`ACQu)37*$C>Ccbv79JT3m$niY|3G@hkn2fF& zbOdc@(h*e7;bKG&hVP=o7ETR1F#$a+Y?6Z3^Ek(7PhtkqcRuI7iv2HOrqG?tsge0P z%n;hpQBJ}~!tetHb7=rQm@A#f?Sfv^(3L_5{=tDRq~~b6hy$bla`r>}0!E6yG%h|_ zj>>LEiUw4!pd)CziWx%BRowr1B=lEvAaq^BRPG^fW2(@79S!`*NUv`YiRfFzIY!H3 zrdE1mgQ!4dX@dx&84Y_mFxt>^6ZKHJnNx^%td`p`h^7qg|Hz-{Q3h8rx-cHSn2gFT zTpMUXJNhvj^~<=L(S?zI@^kkE>y=tm#A?qvpK9)swx z+{Xy^Gh$3YAEuxmZKz=;D$G<4>MTC2JL zJtWd8@S+oan1_D!poZnBIJy5(k3lqH^x{I)FcVFym`Su@0Xnfnmapbw z{?$Pun+K3zIWVT7YYi39vX(VvWFBLGqhU-$a}M>;g)a1Aq0B$X6r+aKvV1)q3^0%l z)JOeB28d2{qYu3f63WB$qy`^h1Zc%nnSYc6pedJ%(#LqHMi&OrtkSVs4v2|p%i|QG z@&tE}%%cyjPjV{ixHiy$8YZH1GxvWw2``B(bUn*dqwhH`vU;YpfNKGLm@e}#Faq?T z8(TTkBRD`g#-j5rI);|Fxn|Ifg)+a55o^>d<{=sVn1|L9W(J+;L**SVu81ZM@D5Xs z+PhRl%XS))8g4+h zkGn{2#|kuk%}k;Nm3HoGCy8hhUQ9;IHyjvUn2R3Vg1&E=3G`NSZi6)R9d`{{zNa2~ z(T}!WwAaCbt2m{o{J>124Xe+ip;E($(TqX#V*C*fR7(fYUdJOJ>gyR9x==63H*iYOhRLX*6U~jxB-+s@w;$kQ zb|_(rS>vKWJEo$(i61hk9Av7{g)yubsI;>keVC2@Add&Kypu;jU6`UB=G3A62#*8k zQyN7%nsuy4)sJ?t4e5FVyDF$a|ajUpf2=ts*y)~Z4m zn);KEY!n%&AI#!dXvH!#A4hxW#HeE^AJQnS=+QUwK}+((Xb;T>R_8MF{Tx<9qewxQ zk%rKN6|#H;t8GQlfsu_O3(cb%MG@Mu9QDzRYykUVESgVb0H}4FdcA^NFrfBqfyvV!+f+&U@FlxkprO@Qm&@hC0@r`0JTBgzg)K8-wSw6i{Xy{2`KziCalT(Zi`&mp830op- zj16VV&*maQA7-OAvr$x{{hUS-K*iE1B8SlsrlDp!{k>dFXyGDGil!s0m{PRf z&nZFIYEFsFXEU?tUqihU>Bw4U29S6niS~z?Qq;Sc(vzt87#v^r_T0F;jVsVj)_eU}UI&k`75XH;RNY3@o34NuOedQ2z`aLdDI%#?sDn-2eF` z>;-HSl8dYciW9V5q4 zUc|+U+BUYM{|jdL6zT<;x-=4=AP*d9@8Et#S0^)o`a?XDp$$#r=^!Sdvy1)EbhuGC z(XX&H6nev0P$`xf(Xm<^I{UM568foKi6VN=IHO|l%bwDU* z(6Ny$mW4jdLWlhX7Acbj7?c%89T0I7I1r|y_e7R-LfdE#fIbYO>m-(pn#h4oj08<% zSalD*ST4)QvdA7f(O{-yC$pvzT4ER&`mw~!{qG;gB3H7)DKt2V2F5co^vAL^9NJH3 zDksx{IF|Q9?F`nIl6f-=U`?SO%Qk1AXBrKnb2=l9=Nd_12GD~!=slAT$$TQGU@FHu zn;DqO{ck^q9#deoa0<|gk<&Q9xvWhlJ&#qH&^()SJDrBkr(yJ6z=+Ytda9LZw{q$d z=+GsM6fKu=?qxoe1EXs`+h@?R1#}2CEOU^MUpJsXlPSECMH11BHnd_Ux-l2MxCQ-K ziW>Ul_N!PD>?{trkQqc5E=2vcEE6a5Sb;taBF{WTWFqD0NGIW0d_V-yc>^Omn*(4f zx^Cp+L=8P?P3M4e`>l**CL>?Q3?VO(3KyEN0IgVxZmdKf)}wM87x6i4$7pol#_DYG zBs2);|I;l=oK>A-5vDVnlb_zW$$2VJP4eGThVo<|4KiW)9P+XKu1 z`mhxBYndsuVl}!jD7Rx|67A+N)97)KSWLpSjsv3?OVGNWi)}VLY~Wm?ee@ z(E2b_ie?vA^Z9fD)6o0~?V#yV?t64?q8>UQ*2k4n9Y@^m#^%HjJFhfzgEamsz(E{a7%U z``=s01H?SeI?#%c*cF4Sz<* z(8-E?%4O6?1G+I5Ei4C^h#F?1{~KmPmVe75EBers$_!T0QM7%>)sJ3ul#%d}s6y>~ z?t=O3xSQJt^?R6!%Q+Axp?@z^i55S14SG>oK*QBsROrP_^!&o(1v-DF9{MmYjZ^a* zKYY-S8K@6%|2s*z16=j!tmgsZ3i6E{5S0T|L?;%=yvA*XcI-lZ6CJ*i2GNPWRyvMa z8wb3KjvVBapt+rnqql<&p|z74SxCEG-1iwIT!-m^ED+pwS91VG6E^f=CYr-Ek%L|= zk{+uG!!?vgXd)iHXp?!qzdjRfgEZkqA6B9>QWMIxln>U#VszmO^g52yL@NmmBWxUa zh$d2{dQGIGGE@`!sOMXxlc=)*K>fen#e}~L`~GAc@j$m zF5;9;(L@HC;@J=FScDG!R4S4%Pvbk#7SqslP2`~`fprJbdnP+BpoUDlg^kNx$=CD1T`tukNno=~;l`en&lSo-ggBLMn z=)af^sK0~}-9*JpHQ_|}0%qW5@>ep2=vqj_sJ~hh)o8t*b~2dqMVj!Sd9fzSWqt`A zzJ&qYz|5liMor|Rp0CBxZgEiICQT&X$`swoIY#?3P598af^)l!iucd~<#Y~~=e(IxpwI)orQJ$@d1hhQBsX!Co^;e0`4Q#)i8Q92-N*`iI9VBcds?h4v zMED&vgbC>7yL_|J_9#;=^P4zTsO2&QUV&(PkT zwEF_>q31z9lWJy?bo9}8gKOZ~4kk%jImP6@hpYrKV%Q}rt|iT+xRw^p;gj;TglJ*NsaERy9- zblgeDn)!CEI1bOfu=8P+7s_fxKG61k}F*Cc%C z4Q~?htHTsif4+MJ^~bOsJ-9`d4`LBcw4gqlyd$zn#E|fy9epP>2`_rbQDF@uWvRzf zv`wbo0~|P!B_Gjpc9YOhKeI_#*Wx)%!i~0B900B7Hi@Jh_CLQ#xX_eL$I&{64z6Qh zn2rw9+$P~9VVOq-G+ju84|1USO`;t23z|gqdOCA-s{V=|Df`qb;3| zplc~RK1{n}ozLl9oWf@bBPJ5FGqK5I0;O*>(${kIj;1Mnc z9|?^DTP9QfCp|^ z^b~E+(o=LjM~Ct$$AxHqzDeXr3+RaS1-3s$!`wnvO8FXjfQ|^c6b7SIVWKz8~w7q8&@nhZ;J=S^D)=Jf>M>qlN`& zKb9p&WghF%7QvFDg|vt9XlCKmj6&{z4~YUrD5s`9ZGjBL#e{4l7-~N~8Va74b!~JhM zp;>I9K*NCCFsfO^yh(?mo5e!(V>bHuvR1crbh8M53r}hmsi=*i96fwjQ7c+bX8*U@ zKCW40qUCftj!GOefquRcII)QKC$gV|gmn@d&^wvsTDLOQ@vOv(=BbQS=BG6aWg9bs ziResVN3_l06reJb5f!ujoMw@W77H_h)>)jI5(b#wEYhVnu|6&OFo^p5Se-Zd9d>kb z3eduOv#rt%bmUzcz!bDU+$>h06E~pkk!DdQ%draGk8+^xly72*S@b=|0MPX~%LJo_ zF{P+7W9ZFe0BCu#*&#HU$Y%lD_h{fL7O_SB(~JP^&vLQ6&yFupj{27*0e~*!)?|m-PkH~*OIhxCwMIrhzi0)4~U>OG}r(F6OG z9A7atpOEm;5c<(6{hl78byqV>eABTX*%3W^>441tMtM0StK}j?t&wX1?Hbp}XNEvMX%Sgpv41Qp_oDMOj_c$8x1G_# z8;dyi6KEK%lUca-Yi1;#)mhOzwMEpUHjVOc*gm60q@yLVMHHZUCd+)H6T`pdz?K$~ ziXPm6u5;-KYUgvnO6p(8{^-7}MHE#!sF+F*DX`CP5wYKK?yq3+OSE3aO04L{@b78( zYIa1=HLOjGW*Z~kMZ*|}?(153+YRm9#LQGtKZA8l(TDmUsCNtPqUY8Y;YAm#`Nlf_ z!Hz2#Df+Tn#2(b{Wy5X`;9v*z;s$iF_H31uHECn^P=6h3(xUgJ7SSs6ud{ISj||{V z7Fk8>+mxfNgcX4Ia!tI$Ors08pyk~b;bSmMq2+z1T)Lx0B>L%~mvfB1 zvKC?bnR=gaVDx;-NYMNl9omOG=`gx52kjMfSmwWB`+oNSmU47fGWF=MY;o{r5qA8( zMMPE8;GP!V1Hys#G85=R4c$L8vR@e4K2~l;OEn!rD;A**%hA`&s?NXCUJLD@6?4&# z8Y=Cy^BeUs70sPYt)GOS1y9oh^h~sf611^0Z$u3{3}wAibPaD6rRY47@>)h_Y86@N z9m6uOXgisuVe9ByTqfF{2EE25DRPG^->^vz<`RWzN)LaGNSPhxFbbkA!Q;_9m~*kW2=a3;S{8|igYwD zWhGy9-NJsYl-t=4?RT__06JH+iug7Lc5kc5N4Xwu6>&5QeHA+#WXkSmIasu2 zw~8+GY~Xv++Bx7u%n-UBVMp{m%7KC$Ag@)}(ex~*2KBFUpbn<^bvlf;H(NzDy0$XF zPEK)gtMH<=gmzHb-YQ}basTT-WPRF0^!zi<6!qc?HkVRVb1j~&MkWU zt)fKc_qU4hBOIuk{h}|AaPCjuvy9FoaW&1$1-K#KO4_zbqgT(VvDb^ccN!+C(8*=C%nh`Y?d5 zc{F?s4bG=wbS-ETMQFc)rGJlQ|8(|8?^2eRMc2)&%!-~{Sa3Ijf!*51pYh2rYZHF- z+F6}7Y5+Sr+eA9LF&FKt7%|#dc~=>zQ=F_jn}RO1p&K*N{s2q9qBn;XTL&?sbxbMR zA7VyPdzcQO_fb}VjbtF0fPPFt?+uDRh&kVfFsYRz_JBt>R zP~K-DMxs{QPV8aov&L}GOJ1A_Z3}GQ#w488IEF8&* zMjsT3Cs6O?gCd>p_t;hM5R&7aPV>-k*gp(K4uAq@Bz; z9o#Ows9|&r`5`Q~Ziwbm(VpY~tn9*of`*e`-jA6x9 z>B;RPW;`Q|Y3Gm1Tx6%T3!lu7r#zOP$F_?Ev`%gpIjBuzDOvO+u>DjK5Z8f6RBU`E^O%ZwTnV@p%>j)iKcH@t&^o(^mnqjBAV8-+9SF!dJ-Ld zgatFvwu$v9OGtR1WKqn?^lWobq@x$}(e+$VSf+m3vJz+bnKU$`LnvqAbsZu$k(s!yLs(dR#>^UoZnUr-VaiN8?&%Pv7TPK45RtR! z*p3dd5G^0Da3Y#Mq`h<5|05PmL_1p1=NQ6LPf6^EiRc{0Qc!3&um~P{jV$pun-Sw; zv<_#HJG6~pRW6wy#d=fcvwt+phoR@hP7y$pi6x^hpre?E7R*2^I;CS-6bl{tajd+S z%mK%r_r%FOzG+Dh~7Asgp*EWDYvD- z4&KausK0~u(84leF&EM9ovh@B_PaV+tzF*#tS4u_n5kfaIt}%#6X&!tg0(bs33=8O zD?n`%Be|3VsVsJd-X}Xn)MXrKGmG4zKA!`j=P4FSOJydXW*IotKgW!r2|Z}WGHF4l z(9h@o_r1s(V)JQm3k{(2HF|nEJ9s!1sIhccHCkAqE9L*O^*(S>Rr&w_fXv7U5(+wJ z5D*j*6&00~3KbQN6b*}t3>Axt3Jr^j3KNTpEi7%RHx;$GYb_NP?$R!`)CY?#Dl{x> zsnD>fPzM+b3j@2q=b1qr{eAD_F>_w`^*;BUbI+gm`Fqc~hNx@eO)-<$VJkHQ55K?z z%(ySvAPuvjm87~BdtbAI8)g<}6J`TuujUVuG^QT_9XyEX#B9OL`+?_H6QE9_9Mg1^H^i(w#v87|eFrgtS#yFd z#xS$k^~-lH_e1-Q&4qwKYro;Zti+7TB1VSw8`+qZe*H!nW|4ot(TwTDG_B*o;r&KD zrs)FYm<@sbMhj-($bPnBAwWU>9H@yIj9iqx+3?%%sqM+W&xv$bKUs zn<&Ig$4tV^!>o+zH|jAPFk3L&F*`7eCiEK-H}WRY*uyM}!5(JKB(})Kteo6$q}{}G zQ`z(kGjMvp(W%Wi_B^|p0L|z(axjbHH{&p1+lBpxPYxlR&4y^&oYQY?!z@bZHySXv zVYXssUBnySf_X6>W42$?Z&YLECH5P=n9ihrBk5L>EV-ZEI=Np=fH3ox^c%^y5kSlW z%)k_46tieEz&{rUml9=|EzA0io%;R?0<@ktxss4#W~CDl%ofaE%%rRFXaf#sU>`H? z+J2)Qvtbn;-41^pyS!m0t?f6OFk7++2xi>%{YFY2?%n{8xp~{o{YKVC-XsTyFk2q# zH`E=395Ws>qL`?}%qtKK%3jMmc8E3;pbP zg833Ldl&Zpjz5?+nC*8_{u`=r@NPVQt>4JStf?j~F-|{bfcJ~`Kn0d8iz5?vk z5hIw}-t9N)FrDv{oA2fRLozL9O%onq2JR=OFq1F?@8iC;-^j#l_=e{&BM!mePx%jQ zM{qyHVR9>G4dwyN%I~pIh=(1>G2?zBO)(>mlleB0c0UtfOsDUFQHL359WV}HCSf`; z<2bTA@c}%<%*PD$V-r2hcK-pxAAf6x4=_0eXb%`LnlVj*14c{{4q&EXnnn&76_{z5 z_1X*?FnTfLf^m2YrhUNJiCKf$f>{)fgAWoQ%yP_@u>(d2=C&yVOiE!dc7Stmc(JJi z?0?OR#IeI)N-+XJ5oX}b0izYO@b;d&bA`JcMovB74BoEVg}wbu-V85IPWC} zFpKWT;$viZz)+79Q~xCjF-;#6g{9crOAKH-F%MwIwG0>uTe1HI zdlhQ)hXJD#v*@P*BjX7I=-|yU^L`a?-fteNoj~N$r%7`z+UfL<62{UUY z&p%B7a!whQnA>tsu}uf&=8dO}Oh8TkDWeM0dDkh!ftgl#in$&f*mTO+i5d97DWe6m z;o(z8b~$hG2%9BhI?GQP$o+e`uTLl_lG`wb!j+Q#O{tpS}VCnf$V3|A)4qxtX^g zF)V{JEh^@haUNF=mwp~s4VNa7O|~FQDxwL2^2BI0URF2R#k4uDW zkli@3xfxNgM@X{~wZffFd>yX^a2;?%J?xdjwV%gT!nK{p)egGn`D_#10k^$1E+@4o zZICVJJ?wOL{mK?&jd|JRCgYi1E-_O(_SH5jU3lb zRG%l>iAcw^*&|Bo;C8~j=)pC^#mRzZoQQq+h~eiU>O~X-=jo#_?nS}f=aD5t;kLJzQ!IRH}A9Ay&7c8K0?r^9~y7YBvAup|32Fs9i~rtELSFcihQRm|J1hZ ziq^;2+)#U;91ysS@M)Y#Fk9dWr0debNrP*Kvunl`)N5RClgMrEp#8sU*)r+=yM6RC zEw%`+B#CUXUFuaXx3t*CnCl-uV%#r>yHvEi(PF#EyR}q~w%8_H3b!6H77vkk4Vz77 z?6=J_7j8RZ+$;;i?LiW^Q;m?V`%zn!vU|U6j(6u%a&*6KvbpfjM~o*Vav!BS_A^_A z_klmliqCBGh?A|K*~WV1%Pwuy%HGdxv%K5O#QSsGOmpbdqxZeO#M63N z{H1ODq>>#+jPd$mB40{wlzgPQVnzjq=Wyw)tMk za_URl>tYe$Spvi~!?lH>og-A)CtuGKaL+gn?0cX|bi*H^B) zsbATad6me$Uy)N#T3^{N@$!)_eU~T`zUHn{)_sl5VA=Y$Z5FQV`I-l^W%xI?8@#s3 z#&5_|N}m0O2O?zuH@0iMTi=w)ZM<`?T-8QS?EKde;}u!=8#T_hHe0Yc_uog1H{AF2 z`rgTXitO2750jsH%)7Tv!VgkamdWyico-pD4%(J^cf2k84%))Kd*7DsgSLf)W5yvu zRVJ$sk;lsGDf|+-l&rJukS)QS!9KIM%DU(Avz>dd0Xh# z&bHC3Mn-&3L9dmm-=j8~n~xX|$(AdL*YGgh+w?tY)7Bzies2pO+r(kiSh z)MQdJql5IS2NJs-q-%B@k>Sd88X>Ib={(>8rn!PiHONG;+j(Q90~m>++k2 zviW61QX zL-B4!JXMab<%PcPq44jNFef!&LN6Qk>QF1W(aGzV%EK5TZO}OF@@p-Tr1N(Q;p**` zcb&FquT=Q~Yhl$V21D!0UDv*^3u6RUtFcNhK2Fw&mBq(N3x9d(IL^n)e~*)qi>2#0 zp4YL7Z>~f-ZNW0*XIqf>z;CkTXHqInHvVjzGOD_UoM?ZT~A$xO>;G(O>($L zMM>AssGRnG8TpHCwpp?5Z@uhzT~||As9|#ZFSZ3_;160jja3?m0uxm{z|P7D980( zp3xv&_SGS{oUOx z_?=Lv%fa8Vlq)B=8{Izks5{{=4G4@N)D1Mj2FA+le(LY?2(~Jf{adLK^7?J@-fa=` za=&dU@q4_V_o$bv25>J=whWM#jwpF%0AY~ypX2JaW6$Rnk@6Y)e7(4#qxx=njPkU z8Jlft|6CQ)O|A+_XOP@WC=7DgTP^d7m#IV44c;xwp~lIvA!;tI z%Sk?bA(bjO`lu-cV!IE%#mQkGwTRp?!K^MZJ69exevlbc$gKC834X;DM~#=`ZYovvz>*Yp^n&aJjrMzfSGj;32qUO`&7%`NOUQ1=dPy$B-WT=|s zRVS|u#rH({LK}JF<%`iMQ+;`U;99xKSFPZQH@SuF^2PB$nPDZ^wX)ty2wK-1HU1}u z?7~-XiNh zK{@SvT3KbYAF)Ey-A|!c3)u5m*4;p^3+$!AvGtJMUzYphR-SD1$C17*^0mLZiI-b2 zTm@M|pCyY0N_dieylfh-Zlfd}8LlqXp$$;W>>cbjJCgpXzH~(udMV9@UF^fEOA(pq z0AB10P&eq>;{uYQM%G=R9x@NGx9n`$Jp$$77pNwfo$Mjoc4iE~M^Xb-jHQ$fW#2MM z_X{dgo)1(PnH>-bvgJWqKD~h|&fNClQCh@ji|g_cyhf319HB0^w6p7Md5lbZg3*Q} zBh+nSj^Ee~RtIyLuDX{G3-C?x(+X%{sm@m$N0Q29m61xfR(6fVA(QMMscx|6o;-S{ z4V8uc1Iy?i!?nucR3b4eNTquBo|M;vR5+FH-XPowmaZVuHC84Bt65~nYlFGN@nE%R zlH>QI=L{6&FQ?k^;B+-q0_P*Ag83dfRYr|c^Sw*^WmT}6X3a&aR_Hox>nL?Q>3(XI zy2l=CKE|P5?n}R7@Z}~`4xEz6%V;0GF`5`o9D2-H?7qKzi{1Q;O+{G}t;dY#E|5Ql zkhaTh>NGq--yv2(^bqE=FY!reFMm99h*;NmBrwWk|hsc=cMN2yun zOhnh|7UVb?V^czmwm6G83s3c(6=PaP&nezPHD-M zFYF`|Eh@VjW3Gs0J6LyRwD}ZSE-6GMj_RF$_UTmp^p*U{_7JjRmK+XI|1=NGK4!e2 z3yPB6W7Kqt)8R1`r!tuus-CB<`B5n8mo2A4)&1tWFOL~Fh}US+d|Q}GLyH{_qtw^S zi7-lbphSk_Zl!Dt=lx>8J!bGqu1mj56z!4%I3Eu#0WKeIs0XJH5y+E0+KF65BRoX< zTmkKbCszVjd>&T;he8^wf~J-t8ZzjF&Q^_xO5j{AE`|Y?qFZ(7+Tbf?C6COlM(jCc z;gi9r$LU9~s;w)yM!3hp`qEr1T$1e2PL#H@1+Yut7NsL)a+7%& zg>Y2iW7VD1$~Q)+8zyyj9b-j|+lKZe=UQ5cJ!~xOrd%Eu!Zpb82s}=8vPtrwD$>?> zB1-uAm~oqj^*XpRII9QO47W`dF#Z@;iip<#VBM4Hs(Z9k11>8Yu`)?p@%4B*Y88>{ z!Nns>fGd_=k(By+`5}^W(29*VSyybICd#uS&N=2i= zM@&#t7U%zV%=nYrzN^pB#sf|`vc2{^!h0#cFZ6Ter#@uyeaDQcgZ6dm`>)YMzgs4# zpi!xaE*{L13Q;_w0(oVE8Z)=>`_r5=x`u61b` zd>fUE=(IwL!Ad?NDtDfm+lGjkc3nD*wTNO)9b*~WS*{5#3huOi*7n-q;$-DSGDsn! zc^-w=CySK*<6IT5;A-K9yIpl_61W=Kp`EBlbb8=VyPl4y4lc;UdJbG8oWBQG2!~EM z?SyAx*@;Ly;aP&~;B+WFU!>XP#DW+?F>s#sUPOIxo}ut1k$sFo&1!O|YbacVY}ZbN zBJ#AJj3@?9=OBIQm&<^Qhx437$c0Oi!#F`Z;6#j?GphJJmzuGG?wW*+3b|^MOH14} zi7Kp8_CU_9FgeaiwEXMo6T=O4`Rn$%1g;FuGpZ}#s6{5@L@A;G59^JHO5i+8e=A%u z-04)%#n=H?B^eRO3lZW*(L>c~U@9V);!6grO7;`+hdbm89F%2hj5z)PN zUE0SEL?v*im8j7w8pH? z6??H-1$X)twKu-E(_Dpn#KT@F9QDU+6|_2ZjKk2MCz!4YDEA(+-%Gbk^<$}6afS}Y zF87+tf=dl!XXn9m)m%QD?^uWN_#mg_paiZs!eOkHEroPxYU-6abV)#hcXB|?qJW46 z0cv4D;KBgk2&^_>wOZ!RQDdid0Q<(DjcDz9A6zfo=@-%}+dq$xjhDyfsF2OE;J^vz zX1*jif4I}dOuLf~=L@$Ttgm2xIdElgcWc5sGa&HV0AFpl2z~(mbIo&Ut_-dzdeAQS zIviDbrlqF%iEM1mjVUdla)|dg0lvwY-0Fv#cqljq9pn*RZE%5;P=SM74ECIGv9dlv zP23!c9;lpr?)${SRlxaURbSfaWVmv;u^vum!0nuJ?tABI_ux)vUj1y5b`S1!9!r8N z)9y`iNYF)UuCrjxu_NYlh2$yTs$g+u=&%&U&Yx z?S(6W^Ncj#JIR)D92DT^;b16a5f)FEVf}C%Ts7PU9`=&qs^G#sxD2>jxG)bc7p?)$ z(+_=)S3TTiE_<8ZkyHlR2f4)K;VQWJ8RwSidbl*Wt%LS-)@^}nhMTUrnAI)O>RluvjJ}s_Eu7 zV4Pf=NRs*9Mas{ndE^o8p>WPQ=hk#_a1OZBc}vG;GF&H|XCBlCly$&)#!@a^JDg`* zxybF_x*`R}`A5OuOszC?;ryD$BvL@Unvc%n2FpNf)nqYPz)!E*tKotWRMGeC0fbQ+@8y zS$oSowaAhRY`H`}o~J_WxnO6a!_f*jE-Lk!r#B>K5YmB$6rxxKsX{L>*BE zjFAxw)Uw4L+QP!K+9a3|^uZOwjRNc5@$$i}6UfM0sfS%1+9`%TU=@5V{Bv#%vSgv!5Se&C1!FNsI1GBMmtiD; z)8XsjyX5#kRfzN~RCfC|xZEXYOSD$EJK=I9auFeD1Xjrc;KB}ID>gm#MjzY(xYPMV z`{-XtY{Q+-gh_Dv%(vzx^5P;j&yo#px>UXco2$UtG9g)wH@5(DWqGoiXc+*uq{w~A zYK=K-6Vy%3MX6>vpjU#w=?4***cFN4-sEWb{;V7YNISw~SS^X2Kq zYT2Y5;DMzM1L5iU33BCSe%`5!CPS4Vk6)(a$)%O2ePi>LX-ic2g$EF{raBB7&4UlR zm*D8vb|Q;iepZv|(D|T%Vr0t_HETv9FmA=Um3$gpDV!@DSkL5_4c7-(>h4Yqy;NNo z)~KDi{OpVCFt)yIby{Ajzrc2e>g;7N`qOLq!kL$1{z$L?70oIr1Qj6#hd2ms1 zS#WJv%ArfuICBZuN6aZCO${(prlzQgA#K2#bjO)lZJn*0aLwtmAw|tL$8OQZ>y;FB zrMVc$!lKL69D4&W^P01zL+AJda2c}lGGz;M0&@}TVCjOQ^J@&y_d%UI9==RXG{*zW zWjD~01#G)U4qc{3TMEJLZal6W+<_}&v@5PzCt4Z6IDWOrIab-YYtE2EOI37aDLC-j!ANmU`d;ap z^wm*Xg)B-YEYmq07%R(x);?e{Pu%RDtlGLvU0{tW#y7Z^b?F=<4a<}=XTc@P!DY&} zxe%DNinD%nV6N4ZA8TBJ(UDe;EF0OCTE?ZhYPcG>Xcyydhc&=8!=YJqD^y*N3)*fg zeEfCiR{svTZEz?teTBO$njWT>gA8|*u4Z^JoUd$8r3j`1vogd~{tpNKJ52YaC~W2sPIRmj}1jZOs)TCtUq`oDU6f-?a{7 zf`>izh-tJb3i6UcQrF9|SWJ^wmaAnK76Mz=IoyMED|Pgyy3$blTaK&)*(-yO>h!OM zE0ReoC=;!~;2Rvqr-R~bOow*v2Dx>Gx_)!|qXZ|1gK`GtIy>dS?S!MsJgrIAp@WwA zEq1qzOOX5A;xHBsKBI$C0ha_9<>e+dR|A)MD`PK%Tm)PrT<2{LBSdqz1dQQbRs@uL zd4E03wUBIqUjck4mO66frpwjcmh2MZdxLy;xf*9J1-EQ)7*EOZV+^xQPD2$OfQylp zX=-C+t6|CK7v(g@d=Ckt0nXmT(&3umJ^<@Wb2)IucQ}lHyBK#VE`*DdlPlG9dkxS(-(lS8>y{^C zG{P0gf-BS|R-ealvCzS!)t=8-9{Ac7Dr{jIT-zqcnYk40OEz39++ggvd@g`H;9*Z^ zlv22sO)~6CwbarEZr?1cu2doB0dSz)dnK*8q*7hF-?>uVZmtC;$c%Kg)~aYrra$B` z9`sm$^-ekwnT?=a4yQBfPzg+wu&bz~T7a3d{3>c*C$L)9U&So?QnB(R9`x#^5Fcpp34=(CBRK{*>c;{2XCgsMR{=5aCvYp)ivl|16;*c$7ExM zhs6VsO;{`&5c&g#rw>!>Ex+Y=20WMVLW{{#j+jX04ONN?bNdh+iS>DZ1v+af8 zz%q`P8+2X2)i$^a8Gfyrb8Ry)>*;fQIqh(z=W)Gob#PY?IunTL`xK@A8QQUfTqb5H zTpZjoz3PxTq-)juutK;9aTt@eJ*GZxM2`mp%it4a#3~hJuLh=J<#ug_E1q8i93ud$ z)U3^Yz~FL+vBo8IC!PPF2|1i+vPZy`!jaEimkwn-obR&^(!(Jv_ zJKR-+TnuI&T=~<;FY_8x&pBg#Dcn})<|ZmAagS?$qhSz=oQTl0GS5VF!*V$on0^%7~zJ=KqY&yupko{hzDkmXwHN4 zKaVSh^M$);(4H>B<#6#bYPA}FV*^mXc&rvD2dJCLbPCuCuTx^Y<~a5a>ti;1f zS0;ak_k#=4_PKN+4~1)hE0_H@>tU?bD$be%7yN?5I3Wv?sfjFWR7hAA+yS`1yPhOG znDuaZFFK5W$?=oe>uz8S<%TtChBZ`B+6Z2AFU+l3qaw^1aLMw;8mf>|U{>YXrmTLK zO1MG^TT7?0UO!za7q3+_BYVMpSap?4*DJ0)v#Kw!Tq}&NYt>kLJh1Ms4&&Ov(CG+F zf%B37u2thLdBFO=N%va%mi6EwxhRWfVF$28)@7+N6MUW}I(H6^UbwV-K8=E9eknwC z5{^Y7_mv%4YQ7~0*!z@C9?Z^T+9ZhyusOfF86pt%mTPF zIdMI4QwhZJ8`Q+GW?*2A!?pOt?dux2P??&oY;&7|S#=JBc;SHd0L3t+Zz!+>z7u}F z=3QxWInkTqrz>=dT`*|XM3<&*lmGJmE||8wdVL2UA5kgYL+z@SX57BxR+rMyGhNP)&iH= zaBgkf0apN5f=l{};MWJ&+aPz}q{1zsf5DwS^4v`-BqR}Bv&V7H>g_bRwmq`%CPG&L z_Ib}?Y|svI={G5b%M$C&G*X&@fpXc+YGSy4?*VQr-*=o@Ka&O*SV_b9eYx*uwZfbY zPLRDf^IlEBD4CI?rbi9{lRg~mCA$imH`6o=-d85H*$$m8w&XBG5)Z7B7jkq=0G&MX zk$W`i*BljXu7k^$$XnEW`v5TQqq9*Ok3)ffCE#-JEj*n9>_Ggp%&0(je0GbPXRU@S z`h?zydtt}aTh#^QTD3j6sXXq^1h?tT?8*SW$of8!HMi1I4*i>sgoke>>m~zBWY?|A z7NFBUo7=i(hw;xL5?;+pxS_YHsb+m}bc9@V8<7yPlhl(JZli;n3as2OAK#{~u}upB*&TZ;=g` zAcwJHE&^uCsSUJ^tATkk>2@`7ZY!{nhnAiR(sizAxrLY2j`kt%MQ+z}t^|JmRs4NJ zx7c0NRNk&4tSN9Ea6ih7KzqzljaDBV{v5|$ibzmR4@D4R=oD-OO_-rdu2iE5` z0t{#M;%2El@C?IGf4_sZiRlP(Wd9u~1AWXkBcpe!DV9cU{d-w>CoT_w=`P)=##lqE z(KehGTdkKV)2zj+IR`FSez=pBR+T{dMEPpE3qjlh3S4Ib1&61VW}SonF;&+s@+};Hu%8T(;cx*a5g4S$UVbbaBM%M9k51or#C* zJC93&3qCfe6>v&tg-p0OxF_|eJ)v^)E}9bMaK*=D^xbNWMIXc6eoXGWTSePr-XL`y z4ujT(>(a_eAIlvlZ{4kCh35kcx;W2P3vUVtTtyBH1?rQz+q-1gJrs;;aG*@OhbZd+ z=E%BxXleM@klNky*gbUUGW_fW0sQ@1;N&Q`0jc%V<< z4tDCObuE`)UZ8@kop8l)Kg!1KXv#yM@!`+b0+Kpyw@#A11%#jkm@Vde)f8(Ta3@FG zHn~?{FTYm>4b$gvC;v)2)JwX*;!~V0_cDs058w8YH}6%K4l4$>{^l?a50QPfWUBG^ zsi|SDkooZ))YTsgT}UGO*5vgUvL}6~iwBF4^2=EOD>(auljSb1__w zcx|F3)dFm`$cjyBUP$o2us*cw%xbfE?F3x$P13l7;w$)KUW#h_#eg0kU<-0D;dX-DT zXW?NDvH^dYwppzi7hFe_4d?hWcz0#!9*NB2Rv*yaHe6oEp1BOnrwc{Ql(YjwWp$C7 z6{g-IK}YJt)7)1IMl4(<9N&-sg`v-;A{7%>0M`q5w}-t_xU8Tq2B%zKr%v3WCRtkH zYJ=qJE$U*sdYf1c?mDxqLC16~oJn5Uq9#tw0G5sFIx|C{(=HdT1uoOWn<6--jf^R*(She-HC>T1gX*f~b- zdq^#umRwJ13+*~*(k=t818&4%2z2`9!Z}0b=tF8|*iLXs*tzmLxH7nP?uDf*i>dLP zaLpd}bV>Gkhopjwmi<0_`0{Kqp91KU#aqMWAH^t#Ot5KemvOIl2W^GiUIv!}cRD;e z67{L$=`!JAHPLzi*oU~tU9xX^SY2Q?y{jvlO%F4&9Rn4Ta{7Sr>It&pQ3^p!gVty-JxcQ_9oRHcK6{jIRwX!B!b)`K1n8V3x0cZ8 zj@?5NO_o4=H1%S_Q?{$xwF7e|PO~|p6982bx!{0E6 z_Rycyq=h;kCA>%3nmYI__YwS3;fml&z`9?CQ@)G*R`P$T-|ZAFo%Qpuo zaGG577`2-|LcDgGjz;DtmF##-*%lZfvs^D&LF>Wpg&L^(x%(zPw zvO>5tIr*3xAGQ-%hxqEjM-njW^dmDkUDCa{?&`mJu5a*vJKN&u!h^x1i8LcMGuSPUY}83da+C^ zRg*7P+z0=c`YEx?_!Vqg#Tw!O-^=yK$olQ{dF6$3&qk`wipg-DbLBnUGv|RbrK^;I z)&sz%`5f{nTehmva@$rl+-&+lhh)=MGDR$~AxU1{N~b3cJdh;&wyK3;<=~wQIBrw> z&ZU#M8ZK!eCtd1lBT82C?TL8+j+V<4I2H3DSvXlH2+;!$#3jM-`a7Byd z_b1e3b2Zo`lb%$|tOLNf%esvHy1^4J&p%0QCN`mbE|a&PRI{xG;Na9Q<9gYWWe*qI zHnrUBfD4pcwoy+;e57;o3)`r&Q-LkZyWGo+asmR^4`!uo_!K$34YgGRWX5j0y2kAP zvF>C1X*)$A1IR~DUv5_mEtTNvbP0co#$OA#@G4pH6uqC|PiS;p-DND4$Uf@ee>|mT z&d7z+$3(y8#oKV{q|pbd`(Miuv@V8vA5$NyUI6#CjBxVRP*NCe-Z_6}nacnI=NeAr zl;fp*3AN+TYHV0aGcljlWoo8930!>>rDsr{hM5kRA^XetsHh59mLt(mt1HZ= zeY*DC^fbyR&INZpt?o2e0hyP6hIH!#Ms45}Q0;%1tO&IG%8SpCjgmh_FXzd7&!}ii z9(W*6x}QPcH-op`B}+wJVbzDRx8B`lOk+hRiTb{%)!|ie#rJfb9<538W^_ltd;@&_ zJud)ijGfm%Z?QS@EnIZFYdOsW%^!vQ?EVhe)ZJXqeXVraX)90?&d=5GZSh_{teNK&=kOMB;(q(+FBg%VOK$>?h z+UYVsJp-E#Rf3!r-SbT6wgXdT_48`hRDB}*&f+eEm~mZ!{Kvv&Jn}_)ck8S4P)V#<(aK{f_?nwn#B;G;}TjJ+Z{cRLm+5R^YHx8I6yZ)w@S&D## zo$|-u)M#r3xQL^DZ`0psN6Vs}YPnS%qyfpXzAxxaGsek(cA_M*;hH$w_kLOT4cfmS z&b$-OS0Z0xhOHe)-hGLz6MKlTbLelnyM40fC2FrsxE6Nf3`m#GKhfTcb1`pd+EK5o8+qk-RYx5rMrtfq%l!zFP#aDhi= zXn?DB%DlhR_UZ(eacXdd9+eG}!oRDS39;=cO1M=0j4QSZU2TR~Zc~s&{me8yfd zmBXuQjwy(()RWR11(5KR`=p2k-4I&%H*? zlnpKzBHz8HW?Cx14MQZP8a?O$N60PJ>Kbdx4`>r}w_eDkQ>LeyV3olY4CNG8cgJnc zF0w#79Nmsx_z?Re>28%*u^*NJP9Mf;r6#WQfWXTKE6_anTh@WWr`^$^36K%QR2#!mB%-y>7dV>_HfGfIy6HN7p;y9WA2D!5nE}3JL zA9asB7rvoXbZDo^H0r^|0C2tA>EV@SDSxF4J9%Ku6K-lP{Rti z5->V_H;pC-FfWXQY26FL9^I|%R(&{q6h|<>A-gwISMS}e##-~?O2&5cEj9D|VKVX` zYV_tBxMnzC0<14x2{ghr!Rf-SuTXxia0lQPYQmMJbI8)y__3vp>zO{}J`rc1(eC&k z!@cvk2)IxSnZ$PxhI0 zcujAqP^+%8rgq^xhfaSi`+q_y|4^%@PpE)PnnW^b$J~{O&Tg);qB>;7$X?N3)rZKH zZz}tQUbsHEYtGtFCcc*WEpbmr1b6H5v;9pqW>`G1U^3atA^~ai-adPiW4R?6wT+l_XE*<0(|5D z!+sik+y8^lf$xPUp%%Fu(lb)pp&|saGrNt&gC6KFF*IKepM4&$vrr9u#Y~y@Zxv!` z0k_SR6=1Uy94hPottO5Oby6qKa{1-zYON>EF7@MGcsv1F*(~|jzv-N0g5%_?f2;As zVi1*Zn;$Qe>(IyAYAyFwVy>gev;uowqG+?vaoq~pQpcET957UNVZ)pbr0T6x^P|gw z@d@2VHEs;1@&klmfgh8k@lbWh8xv&qTj(?=xbz~~@D{Tm$vBVYMd)-dbw{}C`-6s6^J~dmvYIu z;Fox~6Azbg9+v`_eIAzyx6Omo{^h~dFOu&6P%Tw}P15xrHGZm2?8&aLlhLBzfr_dVOiYOxgR6n!lvhn|@v3&Z-^N3$`H+?JrkI9Q9IR7+PC7?HSY|~sJToK%R z?ky?i?PW`fDGjuVnh^NN@&+{}tPj|cj%pnADgo2~BuW@g^d~Axb~UiLDFrTF_BOD} zrW6<`Blf8KE&jigO)})EJ!vW5IoV@mdT4^qXOA@aS)%`ODfHk?@XO>^&RaZzw} za7-aT$UxSIAF8P#`EXU7bU#OX!xhS}1n$6k320)SeHA!+!&!GCkk`YpA4C(;*bc1U zAU8Fs$svJWUZ&E#?lT{3Xsc0h<$3aI6LFXVW}l5F3S2(WS55-0mB9KtyJ=Zk%0Hu zGi2AtYR=+p$b$R2-Rp}9hmMj0xcu|DQn)<03gr5V=T`|g0LQ0@dPkS5W zN`!O5jXASm#meT7G&;)>)NYaRz3M4zoW;wO`!EVdw{zLV;yc>~^37ganS}_P2%dCr zz@qjsrBDTzE>ri>qU{Bylyoy8z`{<(pZ3v9NFM4%HS*Cu=Hs$~b${wM{_5^vHZ^riLaPPon|WM&KU7I5y9-Df_a*Xhy$SMsFX z(V}KrLz#+fNB*r2d$fGsLU$ksF8|NnbZJJU;Lqs&v=^%2(&fVaj2*WCOP`iC`zi6h z!^q)J%QO2a@$q0PQh;`Tni@%uI&P z<*jh(a4W(3(lP6RtNfeX_XQzT0lE~v^o6=Ex&XNIm2USw8zeLfcH9eH1|KU&-usF~ ze@O?b5uEXA_n9p`Qn1qsR|_{$kI95dK$e~${8Eh#iMoJSukJpx5>baC0j{@NKEN?^ zHn>2Jf2r1nHEDWR_nB=Qw7P493w)i{xaP zk-XZw^3+!}%oD&J@5%>Xv9m=QowmJdl=b}&n)mMeG$kNShJTIrtHw&&|8+At;?gxM zzgA<1b;2EhyK}fq3$wF>(${LPC5;_d9L;j*YetGn_3kVC(D&l?K8>N7-!S^q0@wVh ztocSw3-bvk3@zPfCcSjwQE;_z%%kbekLtf+7A6gjb^6~>b=3gd_RG9B`nUsN)93U> zWluJPN0n{#FcU|SBjNmH|ARc<-lhsHEpVw{$eM$UUWSe)hqcP92U&HM3r_k*ca~h= zsm$wSb>8?x>Xu19HZN1tp>Fr&h&#V6b2akxCL#;`Tub|6uoEwD9wJO7z}jzR^tTLX z)q^A2wXT}c&TeEm->R5sU*%;ghI>#awA(p%n~`-JnNTsvd)wt--%>_PwB5rpx?SC2 zG1o&IPoohnH{sUR94$kLfH#^TVei$w{|3J^bPjkO_ z8#%h9DcN)ZTj%ZifpU@_uH8TU1FEhPSUMonek5x+z%>TLD6-`Qb5u|Ns3r!*kL8_B zJ;t?G!tN?Zmp>ChtM8{D)kW5Fgk{zq_8W{`M^SdIAz1zs^<@Ww5S1_{2cn^fLE*33U1VK}cCE+eGJxZC|H zPTWzpF>8S<4UsiRbp{_#rXC}&9;HK?2re2UA0MUM<$#mJjfokLv`5IljW$MqOb4skub;y8orpEy{+P>7&?f(+|Y7hCJW z5z#$HfZl2^TJG$kvhN!hV43+CF zIn<-pgx7*gX7{*To!7a?8?UNI2=+qvA zgA=sJ>`gmP`kiV*bUEB#C!Bt6o7Y1_AF-60xB5IW7V3~UULs45t5sGtnS`0w z!(PYibjHZnaWyt58?In}k8urS3GV!y?8?u!pH-x#24U$^nfJ50-oow>rs8Gt^3SXe z$N{IP%CA53g<~~1P%ip~E<`JE=W@B}7d10HFqS6I3W@^G>Pshn6kHSB*Cu&!wX(_H zUufs%L1tbqfBeGNZl&O)GzsaYI%xoxrpbz4`o3*orU`plT@gH$^0%_*%({N` zRXt%%oKB&-xySgxz4>3yuT1joge$+ThmBBNTQaBoM*Fh`E>>3mrY24p05;^3IrZy$ zOvLCAsyJePeUGt2R}w+ekftt>PktkYvk{bUl%Id22y6p8HcEIOO2Pql-XZt(F~^oX zgTi`O53Obv0i*I>wvUjLeZ1Z_1hEo!l5dF{fd%*J49@DMD7p8fniCQ;lcaxu=X8L$ z()lIAwLBmnpTylVaLQ(#!CfDoEd8Czwhyis?ml-TW5@4ISH;gFYZl3SzpFJN<>2Bi zlwX&N?qscoYuO?f_p2pgec=2DdyGGO$o=Cf><{&@v97Cz{G*3{_51xQY<32Ms7HI; zy*5{srbp=9-Isi1F~~miaHs^X_fZ)=K#4s7PAKVNVqkw3FZ`zgMl+%=)M>nXKrI`V z53H)}F>0*x?g86)nRH5RwnWUPm-vdjeo9?GtOOii-D8XzCi}eDS8(nhOfWei9dF75 ze^8;N&mngH)nhceH#Ir+hngQy3s(on$dR6Jnf4jl3ng!r+YI_AJ_%l?oPYNii`=WW z{$ZdbGvKn{>d`w;>oxx2|FeyF+Ge*~tKfa!?lD5#>znl~)YGf&V*`5OTi+q0X#JS# z+8F-nN;@r*izpfY*JDiAgW>AwAMBTy%b|j0f|q@IWHT_Yp~wCGQMP-aQ>Rb|d^!AR zIew4|Y^#@jjwSJ8)b<|v*vo#0wHDm;UXO7#gM8$yyj1%zS@SbB_buM`W!6|WMyUC? zhc9&_f71ER+n!)4f^&Q#0YmK5#?^u|ntR+U&0HCNyDRy0=eq@2TeGYgVqa>BNJK5} zmDh*Z$5~RqJNL?$L+s(!T(EOr51ZEVT?4!G`q(3_b#P^$_ORgHwNrhjk3A-Q04}1X z$6%I^itm+xK$e!o0E6e!gKCk#`q-l_N#M-=vd_mp+foS5`b>tI?blm7z!_iku+(8Y zi&Uk=Y>zj`&vSKw%=TI4TwsKpG~4G}YJhF6GS5PYP4nsLekD&>?9tX(@V2jd_&m$C z9_D`*`&3IIT;A6*Y$)<7aQ-(vhOeH%3zF2K_Bd-VTtZuq@hA7%&liT;>CYz-3vIG* zsQvm2tH5OkQN;RuVol@n1l7 zbx5A`wJ)`1f{VWG(Hp7i)v|t8`zT8}9Bs*HtNrSbUU0_Yp3~C`E=BCS5dD2vp0V1O ztV##BBHyaR;%--F(m-9L>jOPJl8-#)yB?46eLcN#sh{3;Q1`&fke49W{R(~Ql&OL% z{!V5Ovqzf`fLX3P%s$KFzlaRgA1Q8r2~8$RI^|VA5i`tPaASe=3!!kCWD>>r90=gY09hDRB8_rxE8qzu?y((y|OL!y@B? z!42R-7Knna4sfN#Y5b}cMYQ}a*nXiUZ8=4Bs2mEm&kHL9_YHL#5rZ$BgINXV)^uD1=nR0CH*W8cQ> zwSn^j=xi;hiq2%vW>FMKF6E~7b~Z1_C?k@V8;k2!_vFI;!Wx!i^Z@bfqx>*8=ybJA5yN*r%IQuhenLiaf@zbd z#@J_C62Vz^`53$~A6ysWbgu?-X~^XPMc&^32?$Jf)px->TaKOVF;4f4J6#^F9knW{ zfiD~*^Fr-+TVk&w`q|ho)IQss1CEyyp%l3aU{<)3A>p$N&sT=o`NsQdH0wAg>S{(b zE1X{qvyYyX09QNS=^mKk9qw}J;%oT7%um<&8OVL2oUFic4SaBf$50s(PI;+8kQ*iQ z!tK`&Q`b<)qn*Y?tIYeI#?!uVd-$+y$b{)mV+M2b{`8{%Sj|!k`&iUdEs_{nFxEaM z=m0Qdw$s=&48L5x-({}e!lPsD6NW`)5Z)xG(KUE9&EB!3Up{1vctxQ8tAT0Ba&d$` zdRQxX=VGTZ%S)y`NiXj42>aA&ao5u1U*bIHbJ=9L61da(Nsn-4z!fi%A0zD3ET!O< zB@z;854Y5SGgrvGNc+r5o#6CzUI+W873@tz6fO31Cs-Dg?<({U^2_wOFO25BPAl&J zB2n+T2(qqr8p-Z8^<&4`Cs^t=mmy2XQJ^}&B^h$ZIC4qobrgUMc~#?daBGHqH;&R> z1kSux0>;~~kM0Ebu5!A!mLq38T<)iL+KA8r$wbRvCvT7E1!BRK*U2G`)4&7Q z$ur=|`QVgHr+fU^<%Ul8WWOc+FQuZ^xwjlU#hDTvMOa$E^_j8;Z1!DEj*zFLNPr|@ z>T21itrUQ3SBqtWeV(NroU}%kP9W%=-~(&qZt&#bHDrmkPWJ*Im$%+Jr!DkL;XlRC zHGGqRowBv^!36vDmP+uzI++%2zj(MV&mH>t8=NeiI-MEKvOk(EAHSB8_Wu`5am_Xr zBUG|6+CJaf1Wdot$#|jbga5lG(vDJDD2^ND<%#x-tr_56S zBeou)GskHpf$5JC@mU1>GQUOqvq6)qq0){Wf4MBiK7N?i7XItd%D2dKG4_kisbG_Q z6+@G`1ekrRjGjciHGrFMl@*ih<03o3>9;uzX6aoD#d`%#vyM88Tc7K7zTZB{zSfch zY|NEkC(&A~1LvW zsgnDOdv(^PQi_s~rcgKg+{knHIT^lm9f`AR5?z2P>_6(-^f3)#W}zIy0c!=gXp@sh zk*gA4Je4-{09@V!^4L^rw}hJr*=G4*Ds8@OFzw-~#9bvYvq+{*v#+uG+)NSK;xxW- z?dA8(21ZJEPqR<4ro-nv=rqb?|6U^Hk6zo*A$ddm#H&LoZ}0bIA0%-+vp7~~iW$*LvbI!m1wa%Zl+Ii-k%QyFV z=bd+E)SZ|Lcz4l=o=ANVFsj6ltzAg|AR+9@Zq}tuM{KmeCmXJF0H#uNGaGI=2Hp%)ve z%K^@$v%T0|N*SQ$Yyb5vYd*cXLAwgc^6l(a(0=v+ulvD|jkJvOP{@8Xjdj*VJ;6KI>NGY=Hy#k$)PRPqfWeczRf46( z8)BWHjy1YB>#47YL)9sIt~WYF+D!Cj+TWW!peqGTqt1QUL|r{#4lV4%?qq4R;NhJA z`Zhe@UCRP3jlS)JX~YhQ(};c8aD4@!=Nygf%WgN+16L!|7eYtq<-V-DF4N8Z31s8NFoefEFgErt28Wd8%e-`{z zf>s6ENILQp&SvHHW6ApHCo$MvrVahjX48O?y?(se0HWFSN6}US7SP!K$aKn6n6l{o z{%n-K0C3kIq`#Bl5;fpx8haW+2$d6QFtZfzVO02kIEeG7STs!Ss1kAT&-49p?uk(Iuee zQrkf&l1f0_VKWFl;0z#k?gp`kaETn+U<*1v2o<;-*hK6ulbV*L!uL9=!YVD|^(YBFw!V;y6vLCfqEP)|$n$34_#zzPey+c17ET2JQy zl;_a3I?+uTEJ^1AEtR@wur7v!fX*%faG2_*&+H7=Q6D`I1>c1>WU#?HD{waMfMX9B zb^)I28o*jt-3nW93?kRZ2D3z+=2;%yioxtzodYnBnh#;CbZrWG8G{0X&(SXR(R;6M(+S^jH=eLdrt)*C~O}MPBNy>0lPi);U4z zKnWw*19A0$!3P847V0e8oPopcO6%gpA^4rhVC%>208GFQSXtSOP8wwm1U(#3q0JDPuIk zRD-te`9R1bp6>Jhj@R54jb?)k0~TRgdLe+WK6ZY50PsH3 zyIHZJtOSGengFD*M{dH5eYcf8j9aA8muRmQE4h5YJ!=CvTBRQ0#PLK%L&mZMLp2=o z*9E}mOgoPrv}`OSVaZF;7eG73%QKn2ABz>ia?orq20|_PV=^d(dmsj^2MyOV+=F4& zvJ6SzLWl1`NiPTXyb=fvqLx3jhkoyu;BSZEMZ1J*IP7{A)rd0D;K~XvP0IrGgN}0| z;}Fk)83zK`t(x{I zrVsxC2&kLi3qM=oP(r=#We*vetwhql;gtnurZatVF9d)&ppE}F0MVJcr>K^raRM{x z%Hhz4dQSkWcmmLIJOJ6gdb-y!fweI-TZNVl+8d%JzCVF=OUMB&^M}9QqOdi5Qq&fLBjaj~vdftVV}B6@UQeuZ7v( z95&8S42SZ61i-JTH?`k>AM2_=$~~W<2k!%um%Ij5cQz23!w1C9bo@T_`4Z5gsO=;+ zid6&d`Xz8(XMuOP8qhQ}7tV$OYcXE_8o*@SYa4hP_2HwyB((PuIOP5w2;C)4A`HAA zqkau&7MgoMT4?+_)PkR0zn}H!%~=sE>^1&CXeeTqg1sH!Pcvf0YLTx(vbm6tZ^9PB zuaUY>Mn#14EHVuLnbGHXr zXSNj%ds@_nYzWAICHUI|S`^KAfGsv;mSQY#RU6tN)By1UWHcq(Aa^?m2RpPeZD0>O zyom1Ajt+C22W;(3iPPBN7@qJwuy5@`2OeZooAaJ!+K2%#wKnt*3JgQ{a7<&ZBg_=h zEIz)u9nN`hw%<_;sps{b^LCC1drVwPMw1J!N5*O&r1R5QvS}4uvf@m`;^Of(4n!a$ zV%7TaA)1=rwV~1C8m*xZqVt$v0?3t@RJGZe)LuMHw7$7?56zSE?Y?zL~5K zu~fYmwA6m|+(T@zKE4cD=uZb8Vx4Zc09W*{4K=&ojz-1Vw0niLdSomVk&RIJ930D6 z=6Uezx|0%fSr3B?c>AE*P!U(GXhSn{nKEcdTs*GI!F}Dl($B!dxw~p_Xb3^j&VUwf z2p0Hjwh7%GG&Q2`16~Tpp~{x5aO{wAVmhT_0vs^(TOhnY8j@ z)=6C#MQ?^EHnSERH)==6PVY^0`eDYjkwNk#v34yoVmUvN2XDr#+E6FH0#fLfM;MDK z2Q6wuZRqJ38Z;Ghj7J|~2@&6^p&~P4XHdq*`1U-nlku1GGW?FK4P}T^64j4@sVf1k z9<*+vkorA}39}NkbK`01qiFc4E--@k)8~(3>6r^0KbijIxD41infgozvv?KQJ*5^G z`_I0FVNPx6A5Le95$#p2o`~TTn9d$IRBb_>=GJ1e65#w#yHqJZYd+*>M#Nl5iE+Hk&p)hUq!wRm45J7FT#{3gVQ3&?VxpsZ4d1dC=ugk z9JHxXu{cT537AzdU6NUT?<*;HVcp2jx z=nTu~qnQ{lY{1zoC~g*}*X_Wz^|g2s2TBxpTw@kXiV1>NyrDKU4cA08V4HmZEG+B> zl%tYgr1Lyb3Gmj9wOIA4$p*KS*>t6-U`hG1=ps5q$SF@3VtT$2hyK6(YMbQquatkFqiCM1-#N-ca zAplS>rP%N!>yw!L7MkR~T5*j|fw;kgPYwe>x9_9#PhvJ)4($E7Hl*j=0h(tO-jSa6 z6zAXIu=v z;)u_;evrx{X!9J1bUL_Es9HKO2mNF`aJ81S1!zA`;1f6%S^)N<9ymU_4yP7p;9gSt zdjT75$lHlpHq=2wN!_*RJr`^63edbU^w?ZTJN>{{V`%eSc6&_9yJ#k{b)m6ZT6qU! zR5uqQpIi{jn^UWK@LURfv^fo%heUXRJH*j~dFZTHfxU5cIJ0}i4lebpd91S``#pTP zeI0Jjz!)O$JWqNS?XCy} zw-&N_h9Gd1xh}MT&!W&Z;qIC5W2JEi)fPgGng{H>gOvH~o|sDD^8R(9Z3eCacniHa zpLJA>e}nKUv+nxc(a9*{WY7vS>FfEdlOY?}2lw~H&bqPyOjsFc)}goygeR8cyJ_PB zNSot#qa>_#p>N`-2Z8(ieF5rzI*7Rs)PakGb{F(}W?`{8s0b5RB^=6ab$nZkKTW!# z2s^HtJt)5iaqS1bVg{~wh)x!<1^QjUISBY&(t*m&+>3$okvfbpVTp=? zS}tU*^@VV7JxW~{B8dk%eum~PM5P3Qqvq6cg%f@VW*_&P@&Wq!96GiTqfIVwPC*^c z@2cIj?{h4vmm9Ryd386Qj{q&D2`v-FRt;J*XotjsxlPYuKr(%Z#6F7)K9CMO$MbQS z2UGM;;F|d~=y~2kfvcaZ!{r$&E4cT0)SOzyWlsFEun?qMIQml9Z3%Cv+A-1J;TqhRF>uvEQ0ro_|UI>wR7F_d}(&ZP> z0UW?rmr{>K$k!R*s^xXKTm&3;GVNW&^Yte(fw1lm+V=-z!71;b59be2k#f%4@{#sqgEO$4$l%R`k1u^UO zI`E@^ZKKXD!KeLj=<0ObZUcY zsRz9r^gDqyxp79mBf*)tW}jkw*h?QQ#Ta4%uGvc$m!jRqQ0ra+xEDs0s`EXj3rcqmVC7Cx&}FCOlv^1 zfQDn4{7SC9D_MJ7;(;OWC>>jgLLUzt{cRm|D4^z(jN3XOjok{`HX6H%-5gU1SaqT< zlp8~nUW884`I%1=%|F5TJ=%#`t`fBAztx30$I{ensA~88Bwj~lPNcNW z7iim;>q5O~{|4|q=B@E9=~pK!(tF@=LPIlGvk!ER0}-0vW^fSXwzF#r}gZ~)-}Mko9ja-N8^j?M&<~b)dEK- z98r-SqExos64^Q_t|Tfm&KY$d%#1iVy`=}b7ZfYZp`0=<4rp)_KdRD<{cwcl4@%g8 ztU3Y9rqiGeY?96o{5RUf$;PiRbmY-T8`!X$CIgRm{6a-#*yn(RHcDRzifhj9uEgRZ z^iD7G^%3sPz)D7KW07*LEP$>AYw{Bik0@S^`Vub^!+b! zr7zG9{z^T{P_PGq{pagL$EepLzM?N<59zGmqCL~KGJMYtn0kQ{HzBPa;K{$!%uVRC zKH#$7X(gwdk0I-IbaE5YT?lNuL|r#ymM#abyi^}ruM>O1&u(VDW1_!9ANZpl&(Kg0 zE85%-o7ugF5)g~8)H8j$N5w-@{W4Hvi0M9-{8^gt!@9#09#L;;d8x~UnT-@SP zsI`2wdCC?x(a`L8gyxf{f5BQ{3vd74EvUm(&@_GN_!dN32<%P21a1j0T7#u{gWo^! z3U=A5;BaQprBE?gpOw&7cD;h$6#oPIc-AFe#@i5^D;;}ss;KnBD`1;*;kswcCA{jQ zO50rR(AWCCid61`L;M7K@Kuzn<^-nP`)S9k?10`2oIQgUY{k}p`j1$&%)S&_-;s7` z!Pz%|jlE}xKZ!-?s!JFjAmf7`{A=uf!#dE)*IdF=!s^AL>Y8}Q>yVH&JB6mXmOgkL zE6+S&W9cOvvw%1mcLBV?x*IA%%X#rq$U_T1L*gy3;NMGcu!LSlA6k*?(hb~7GH6wx zg_XznXqFCIC1`WSMq@-dhNyhdqF=cb^1mux_#RP?or`lIHqQJ7cYiJ1$Xdtoii|#u zv191vkg+W<&SYHv09G>x#N!&{mnq~&gdlPe_<{y}^XV8u}*=EC5;H+7fpM?4FS#+@ME{B&^4;aoyG_-x-B4~F4~Jm&WueG9isHUz z9qG2640rj#q2T+=xGWGF&e#?hjt0McCo7JbejZc($;+XsN#gbIf$y?+beX?JXnvx= zyJ#1=fCYbE4qfUZUQqA%9{WL;SA&ca+lAq1IUq!H{dciiUGaqo&HL2reJG!81&mI+ zf{kePoW_&yV?h&j5t4;ISFjvYH^L9S&z9-kpw;xm;+8-faC7i8Hle%){CxSfxS~bR=k&`>8FF%#zE~qU|nx5<#^#0aeo9P9ync% zCwXvv30l`KxW&T_iuEhMYoD}x@dxaM2wiS{gys~rtY9~HDh4e7@`~U;5O|~vJRTM0 zg4^~lX-owY5d=PS=n9TkLvILIq*p*VY`KK-;48XV!5-_aB4z_c|Xj~x8f4noF0j&x&4E^c?_nnV1 zyrczDQA&_Ka}{4jhJlzK_Bf$K~4wWb@oc=TiPEBo(#{ax1vFx zupYWfIBcTXpP(t70gU%wfxcr#YmA+5f5OJymh(r1ruDtyUgf%>C$2-r3gEs~7YzBh z7zVS!e9Q)Sf68X)j8`Kx57WL+(Q?gz2cvhN{FEsXI_tFvO;5U3$tPIA)SD^sGgO2Z zxCVPWpYbu{Pvo&P9sUeL!xG>&U8v9J$Zrj>t4k1^nJVFU|8p#5281xCqy!-_T->s z4~DRfH;yl*s<72*kI-tG^`XQs*cwB$R;$VF7Yu#FB~tRXr60dwkLt?caD_%3K;#vG z&Ws?WR+xSuje8XW_caHwaA_8))vO+ka-<}6Ry_d8bt-7y%pf0dzl78zbO1XJg`l~H zQ`aw1*OkD*;q>H}Xq=`fttLB*4u8qVQDE1IAb8}!_qdG6e2}FYc7c{MGKgIRb#F`E z!dQF|3u}!|tH~Q3ygn`Q7TN~1=}l-^prwG83)&SrU5|xpoGCtzLI<&-mk)>dyMuT; zeQX8B+Tn*Fi1YAB$I{G0s5z5f3vEX_dwNAFmza)JsR^HMAe55vs(;VH)%CdQ-ZkGZsF62W&X<$Y2N%58>n}~p(dB6 ze#PeL&Cyy-p`A{0>;|qWps8Lo9*qGtHlKEQvGPd=9zQ>bLqe*cA@&F~fU7vICV^TE(bV9u7Wgkn6d*&ZBcS`J1$WswdK6h5!djI(I*n2>ph zxY*Q|ZVt_PEY!)MDR0<2&piE(f&Jd=9Gsb7}8)*d`4E zM!kiK5W3;IYAh+uEw!5MZ&9ae@Ibl1=iZ_Tz=l%b{Ov(-*{WvPYt_hb5VYL4gOEAk z@`ctLzGo(VS}O$ELAQR79r^;``gej@*{X+b9pAGQT?J@Hdi#4MBnWtv!#fOI2$0rV zi>HJ-9|xD854h*uAk@{=;q2`-*w$Wp9E`{wIIMdw2o?e|amba9vqGHsMgOOaAF!oe z2I#Axl|Qg{o%aAAtq6+w2lF3VmwFtP_voW=tAg7EYIzOA#EBo6xtFP}R&(Ox;0=#S zrh#@2wAKj2f1Gj60<9i27X?~ly0D%AD_;y+jwcxU{<;dJf!3cu0UzZNz~N@m&3-$< zMfL5_`ahvoKcZ($26lf+V}68ubQf?|CB{5x46TPeYX6UDC7SlU3Ijhvqa_>AL<3J^ zXm@llMW8&5)m<{%t2wC^N#c+=vwn(~7|9CqZ_$IyUN5I;-@t@uzd z)Q`(6p)7I=x?*n73TewJs6o{OrqkI|tXpC-Lk)a&z4TNm2+#ch(A{5A4<9zW3xG3e zh7T*Fqk!kULEKfN9-ryi0wRNRKGsHORCsHQIL(IWascyb#A!76t$^jnf_$OG#m4(i zL&Krj%^14r+G#94CIkA9)0m&2cvTLZOfUX~PIm&(Oox8L2@7)vEtFxB{(*3Iz&x7v z50p>^poZQCG(;yL*r_1DMS`oKC}+UAOb2cJSw2Z_iB&q&b7zo;gP@sd-x)Semz>Dk zU)!@N-yFcBKLD`>%A&>^)n^8%`8=UMRf(H$}T{Ys5zA-l~4&N|OO zsdn-yKSOd^4qE^}KGs{!p3(fAA|Y^h)Q8QN5-Cf-LAeu3O}GN9K_ zV}8M~y&c#Wpv}KvI8RLiy_OQsVbZMxPPrV!PK|ms_Th8T6pQY}2bG3%Y?i(d(A|<| z{))a(3cRajgLvCU^aWM;R)`wi1-B}=4dHV;Sc_k|qSGyES3J+hG{DUE4Ny-Pni=Pr zQMVPe0$P6_RaFmI6;D5(hl77k^`T z4zn|_zp*ul!3|i`lU}L8ccX9RLsLTyN-h(ys#k+h6~ck53uwLtpl!XqAp{{i@3xK$ zY=F)S+GN^)0V)-yE{Lgj14by7;p%=7x@IoWD$*OUa#^?^*M+=y5!)|qQqau%H=wbq z*Ryu}9U8Z}piLjp5SoNrg2zER_RR0d&_NJwwC{JMvcqjC_@NZ%M}_18`$p1KKbv5v z0!|*&fU|e%YZX6WFVGO(6{G6i4PaEmlXNpm3b0!`=fI)O#0K#QuPOq)7wQ=!WBHJj z54RM!ea_D&$4lXN0OB|g9JWts2$e_D#m|w2qX8Ul>(Gt2^yanLu*(OGey9O@2kPCd zi)+Cuc|hBqOYhcVrVj!aKit4oYp__^P={lN>8WVmAo+#FKcf!vhJ4UU9!1*teR)_n z)}cXqK+B_@b?92nx@+;!&$T-CR7^2o@TrE-y%C}#tggp6R@7qA-2r{ZN58$kOnLxaz3=IKbf0;RjGwOin{@tS6j}v??k^{#YU>N4?4t78hnj))j5F6X!bRv?;xP}L;C0% zq(^Ce(LX+I2;~~ZMoh+^&;Z^JqM0`R2^CpmI&T&cAq1NY=siheLeQDs4(y^$ARB^! zZE6~zDuykk*6WnjMhzGw#o)z@!MJuPzVJPE#V3yL4_qFk=zQLoxApqM>LSLz_C`e0lr!{QaaD zuJ{nCT}QJc@c?S%W5&3W$kB1m$n3aMu$ivNNpQvWbx1`a0y{cUqgGjJXf^4APf@ z<{wOoP8k++j=N_yh8kMX%61Uj^LM7Ba2LzpXthpZx3ts6or}nf^GA$`3*yhA9gB-v zG+dUHJqV>Wu`yIF6c2vaDMNJ?py3i;z4AB?tYQS1+K6jcRsAvKxfvbNE8}$A;b5ZM zZc=_QEVp39eT3&nRn|Ow4#$LgMZ-_C4BnrXL@UD$Ie^7aH9~oa7dTyuRyrECf>!-> zBdQOA6Rc|tN=y4Dyf|Ws#w9Fuq^hh(j5w%ExChN>9T<(2OteG%XwjA#P%< z(p7I7g8sFL#>6U+rvRT=LYrfiVTKA|&9X)e%xZXDGi8Y0l!*?woW?X$o{T94u3rWB zZbIgBp_zhFXsA~68ue?g+-yh%w0_tqbelTR+~!J`=3D`!5OhmLBM!>09?TMAhj5mD zWSmzU`65l*!dT|VH^o(JXU6&Pvd=mE`L(0D#wiH~4;)f|XvC>+X!xSrL8KPfY&f!evN6;L zA|TBuI{6*iX|EPaN4*seP(_^3LYZW6b9|;T^cg?on?T1}D7e)r3mn8*iZd#=8q$E% ze{KwI6;eX0Q7O<@fj0gE9frHU9=Q4fH5!#2HgwUVw+9|iuVJq>EDJelAIKGFS; z>*uy?$Vnw=)u4SSj?bTMjap2}#+cuOdbCld8kPgQdi)WJ+no^^@vLFDJ3%REHP+mr z6~basB~AO?QL5ea%8jPKh+n^gtLQoi$+7QgAvm%~f4*=ynrl{8-D6f{w9>SW6ww*8 znyb--P5%NBt){!6TT9!h?v6rXnzBVWe}9_POIdk~^-ZzO?GFmNXSoRPd{x-pr7>%F zYO$wtyHa(ZNq*cIPQ+6(&=p~NrD^K!5{M-87q$bWo8Fwg) zi;N3}v)>_1Zwz0Z;zq;KA{u{=CK=4(`OguZEYn?k0RXtPYb)Vi!i;C?u!z3 zzx3~>Eq#;+difO5#*HtD;7)0`{E2xJKdUrt(sb_b)mQmNA8G%y8LwtaAEa0!troS; zcb5)Qrbi^1>>?vM()8UT>`rNi)Wo8k(rRXtHbeQSmsNHYTe#!MFWIHtAx)z+O%%vb zdiF9)t3{fgcSQayuZxUWiiK&Crjf=DR{9p1WPdPA)AO8Y&Sq&^B;6rRr!?&!iT>l? zCrr1b``#0Fhew#^EYYtluZnW@Nq<;Oh>{X< zi|0)_gvlYvu~gdS$mre7hoppCYz{&9hf8CL{QMRXt9Patx;%F%(MA40L|VPlG`%f6 zIfl!zWwLO$%VF6!N{%gERXq!h^OSIROS?7jU?7nZ9@<#MD%{lR1M;Af& z_Ymo^bQPw(r!bA(gz1u|Px?1&MD{f}3B`X#>E9|%4NbdS>Dbj1BZ^%!RD8xRO>?xE zDQtg=WcaVqn|CXTcet7hx?7so_eJ!UL&Ee)(;?lR&2K{SbS|=JL^y9q#Akj)`1e07 zO!HvzePgt6H*Oc%ayFCMlcrTxi!)l#O|lx?;bID#v7$Qc9o2Xr)Hr*I0G8guwB8|1 zr!0T#ts((FSs?B*nIKt@zHq_F4|whoA5aSy|4bAyR_Rz|T`i*3{7smSEOEoIOPba@ zWwnO0M4V1p zt3ElM7@v}1W$ie#L|Tn%SX|^hT-Y5eMB1FPwK(LU;_NO8(IqR(F-HtWzA+-4Ml?Qp zXPlB$WH}P8Ha@#vW^9@;?YGF9l&14jkx|z$S>oX?E4z^8l%V@%BD~2W6MnNur28xJ z9e;w%%+sp>B8{V~@Thr1L=f%@4q0MW*+op5!rk3bl)Uq_h)~l{(7m$D`AC$sQ<|Dd zvIZcz=09tS@NZO2&N|SM@#u4odqqM$R?#JGFNspq$f3?8O>=J%-gCbw5YIdj&L6Hl z+4s!r1l>1M)P`l0Fio=7&2I~L*HJZHMH*kK@L=mM9PHt-M4DEw$go*Xu)f!2jmU!0 z$U(rKB;qj+k_lZQ1__I7;=b@0k0+Y=&!SFkMHt-WpyZYx^cds^WtIB2%Lrux{KX=n zwhf{NO?F}Wh6>aBovhhvVH%~~I#hhvB-d>gZqgGIlvu4Tn&wTw_~4h_&$LE-!rMm# z@#3LU{`29AS^l${g=u+0v?^zc^p_x#>fIphHdz)9X}aZjWxiczp}G9doocx88m9mn z%Vg0CtkSgDX<0F{ zLd*d*-WZMVtoVSPj!aV87kU1N>CwpVdoGLb`CAL~|3P|Y-;eZo|A*6IzU7_D#c?%FBJ-;9sD+lm$#HXRR% zFS{jQecfCrnzr>D(M4QgGgtbTrgNYeHaya9yiK%x%O}kUl9H$IGqw>Q44ckrA_ABE zVAwQ^IaXtrG7ejzOz0EBw8?~8`ic+Q>GUjxBE6NdYOg4@D=F74K5j9c5-usTn^^4J z;(1YZ+3=)dB=b{BG&sI8;xuB_+Ce##W{z25b>2+ZmrD>ws1xn9< zdHs^3zaU+CB4~YG-1<4tLG~{6_;eX z?Ew)>*z}&Gxh0WSFI2ijdQ8HldZFSk@;xNymy2Rt^~m|fRWIz0 zrDE{0+$l>%+HKO*{3iSvrQN8L^Ozi;-AhDx`$AzFrD=1hb{hV?a@+q8iC`36tQh~- zQ$of6`^B;LeQnFJo>pQK@k?2>Pfk8zzQZhMJGTK<0Yv{ZCrzJ|ehzK|IX)v|KFT>O#v8@R%Z-V{6 zk+uhg2->k66K~dXtO1%(QX<_N!K73zM|>I{_waDEIV=A9gsTZY$FUcW?(*q;eFm>l=7QdYI}=|qq5$mz*R z)0|3Q;o5P-Y6S7G;vAS$$@x$G_FJv=jr8;u`E;&EnV6^RRDQ1-7Je(m8cglZt6U74 zK-1SKDO%f3F{is>0UwaG7Fi8m$HOB{5hAvdwTR8POfUsrZn4A*m-uxEX`_sFC{NYs z$%`gF(qj?sez-@v?-G{u^{{wH3yT951PQEHdXo7iC0^j+k)9>uGp-HDuNT|t^uz|` z{z$VVn<-4bwn2F{T!$V)%=YObWOONF)=;lfWY?T3zE;Xk-iX5)$azhz$Kj z;IXQXma>0x1R;ePFNr>6X(#GGY?^3c8Q7Arv(YcSg-uhPu&<(wGVn%WZ~lvd95zkV zaueqaYXsRUIj^v3r!AYnV$9j3wEXvedNTVk(P?c`H0c>6(rcn#oAHJJYv;KL9qCKr zMVd%oYzCtuED2ItsHBmKXKuC)iWNVit)QyX6W z3sY88i<4WzL8_ZtOk10{Oy?FE8M&Lf1e;ncuQdr%($wN@YKecni8otQOLht28(?q-(VWKQ^91L0v(F*Z|&(8t;xMpF}Bnch<(Jc anMX%